Parser.cpp 364 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  6. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/Debug.h>
  12. #include <AK/GenericLexer.h>
  13. #include <AK/SourceLocation.h>
  14. #include <LibWeb/CSS/CSSFontFaceRule.h>
  15. #include <LibWeb/CSS/CSSImportRule.h>
  16. #include <LibWeb/CSS/CSSKeyframeRule.h>
  17. #include <LibWeb/CSS/CSSKeyframesRule.h>
  18. #include <LibWeb/CSS/CSSMediaRule.h>
  19. #include <LibWeb/CSS/CSSNamespaceRule.h>
  20. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  21. #include <LibWeb/CSS/CSSStyleRule.h>
  22. #include <LibWeb/CSS/CSSStyleSheet.h>
  23. #include <LibWeb/CSS/CSSSupportsRule.h>
  24. #include <LibWeb/CSS/CalculatedOr.h>
  25. #include <LibWeb/CSS/EdgeRect.h>
  26. #include <LibWeb/CSS/MediaList.h>
  27. #include <LibWeb/CSS/Parser/Block.h>
  28. #include <LibWeb/CSS/Parser/ComponentValue.h>
  29. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  30. #include <LibWeb/CSS/Parser/Function.h>
  31. #include <LibWeb/CSS/Parser/Parser.h>
  32. #include <LibWeb/CSS/Parser/Rule.h>
  33. #include <LibWeb/CSS/Selector.h>
  34. #include <LibWeb/CSS/StyleValue.h>
  35. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  36. #include <LibWeb/CSS/StyleValues/BackgroundRepeatStyleValue.h>
  37. #include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h>
  38. #include <LibWeb/CSS/StyleValues/BackgroundStyleValue.h>
  39. #include <LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.h>
  40. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  41. #include <LibWeb/CSS/StyleValues/BorderStyleValue.h>
  42. #include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
  43. #include <LibWeb/CSS/StyleValues/CompositeStyleValue.h>
  44. #include <LibWeb/CSS/StyleValues/ConicGradientStyleValue.h>
  45. #include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
  46. #include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
  47. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  48. #include <LibWeb/CSS/StyleValues/EasingStyleValue.h>
  49. #include <LibWeb/CSS/StyleValues/EdgeStyleValue.h>
  50. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  51. #include <LibWeb/CSS/StyleValues/FlexFlowStyleValue.h>
  52. #include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
  53. #include <LibWeb/CSS/StyleValues/FontStyleValue.h>
  54. #include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
  55. #include <LibWeb/CSS/StyleValues/GridAreaShorthandStyleValue.h>
  56. #include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
  57. #include <LibWeb/CSS/StyleValues/GridTrackPlacementShorthandStyleValue.h>
  58. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  59. #include <LibWeb/CSS/StyleValues/GridTrackSizeListShorthandStyleValue.h>
  60. #include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
  61. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  62. #include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
  63. #include <LibWeb/CSS/StyleValues/InheritStyleValue.h>
  64. #include <LibWeb/CSS/StyleValues/InitialStyleValue.h>
  65. #include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
  66. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  67. #include <LibWeb/CSS/StyleValues/LinearGradientStyleValue.h>
  68. #include <LibWeb/CSS/StyleValues/ListStyleStyleValue.h>
  69. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  70. #include <LibWeb/CSS/StyleValues/OverflowStyleValue.h>
  71. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  72. #include <LibWeb/CSS/StyleValues/PlaceContentStyleValue.h>
  73. #include <LibWeb/CSS/StyleValues/PlaceItemsStyleValue.h>
  74. #include <LibWeb/CSS/StyleValues/PlaceSelfStyleValue.h>
  75. #include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
  76. #include <LibWeb/CSS/StyleValues/RadialGradientStyleValue.h>
  77. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  78. #include <LibWeb/CSS/StyleValues/RectStyleValue.h>
  79. #include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
  80. #include <LibWeb/CSS/StyleValues/RevertStyleValue.h>
  81. #include <LibWeb/CSS/StyleValues/ShadowStyleValue.h>
  82. #include <LibWeb/CSS/StyleValues/StringStyleValue.h>
  83. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  84. #include <LibWeb/CSS/StyleValues/TextDecorationStyleValue.h>
  85. #include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
  86. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  87. #include <LibWeb/CSS/StyleValues/URLStyleValue.h>
  88. #include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
  89. #include <LibWeb/CSS/StyleValues/UnsetStyleValue.h>
  90. #include <LibWeb/Dump.h>
  91. #include <LibWeb/Infra/Strings.h>
  92. static void log_parse_error(SourceLocation const& location = SourceLocation::current())
  93. {
  94. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  95. }
  96. namespace Web::CSS::Parser {
  97. ErrorOr<Parser> Parser::create(ParsingContext const& context, StringView input, StringView encoding)
  98. {
  99. auto tokens = TRY(Tokenizer::tokenize(input, encoding));
  100. return Parser { context, move(tokens) };
  101. }
  102. Parser::Parser(ParsingContext const& context, Vector<Token> tokens)
  103. : m_context(context)
  104. , m_tokens(move(tokens))
  105. , m_token_stream(m_tokens)
  106. {
  107. }
  108. Parser::Parser(Parser&& other)
  109. : m_context(other.m_context)
  110. , m_tokens(move(other.m_tokens))
  111. , m_token_stream(m_tokens)
  112. {
  113. // Moving the TokenStream directly from `other` would break it, because TokenStream holds
  114. // a reference to the Vector<Token>, so it would be pointing at the old Parser's tokens.
  115. // So instead, we create a new TokenStream from this Parser's tokens, and then tell it to
  116. // copy the other TokenStream's state. This is quite hacky.
  117. m_token_stream.copy_state({}, other.m_token_stream);
  118. }
  119. // 5.3.3. Parse a stylesheet
  120. // https://www.w3.org/TR/css-syntax-3/#parse-stylesheet
  121. template<typename T>
  122. Parser::ParsedStyleSheet Parser::parse_a_stylesheet(TokenStream<T>& tokens, Optional<AK::URL> location)
  123. {
  124. // To parse a stylesheet from an input given an optional url location:
  125. // 1. If input is a byte stream for stylesheet, decode bytes from input, and set input to the result.
  126. // 2. Normalize input, and set input to the result.
  127. // NOTE: These are done automatically when creating the Parser.
  128. // 3. Create a new stylesheet, with its location set to location (or null, if location was not passed).
  129. ParsedStyleSheet style_sheet;
  130. style_sheet.location = move(location);
  131. // 4. Consume a list of rules from input, with the top-level flag set, and set the stylesheet’s value to the result.
  132. style_sheet.rules = consume_a_list_of_rules(tokens, TopLevel::Yes);
  133. // 5. Return the stylesheet.
  134. return style_sheet;
  135. }
  136. // https://www.w3.org/TR/css-syntax-3/#parse-a-css-stylesheet
  137. CSSStyleSheet* Parser::parse_as_css_stylesheet(Optional<AK::URL> location)
  138. {
  139. // To parse a CSS stylesheet, first parse a stylesheet.
  140. auto style_sheet = parse_a_stylesheet(m_token_stream, {});
  141. // Interpret all of the resulting top-level qualified rules as style rules, defined below.
  142. JS::MarkedVector<CSSRule*> rules(m_context.realm().heap());
  143. for (auto& raw_rule : style_sheet.rules) {
  144. auto* rule = convert_to_rule(raw_rule);
  145. // If any style rule is invalid, or any at-rule is not recognized or is invalid according to its grammar or context, it’s a parse error. Discard that rule.
  146. if (rule)
  147. rules.append(rule);
  148. }
  149. auto rule_list = CSSRuleList::create(m_context.realm(), rules).release_value_but_fixme_should_propagate_errors();
  150. auto media_list = MediaList::create(m_context.realm(), {}).release_value_but_fixme_should_propagate_errors();
  151. return CSSStyleSheet::create(m_context.realm(), rule_list, media_list, move(location)).release_value_but_fixme_should_propagate_errors();
  152. }
  153. Optional<SelectorList> Parser::parse_as_selector(SelectorParsingMode parsing_mode)
  154. {
  155. auto selector_list = parse_a_selector_list(m_token_stream, SelectorType::Standalone, parsing_mode);
  156. if (!selector_list.is_error())
  157. return selector_list.release_value();
  158. return {};
  159. }
  160. Optional<SelectorList> Parser::parse_as_relative_selector(SelectorParsingMode parsing_mode)
  161. {
  162. auto selector_list = parse_a_selector_list(m_token_stream, SelectorType::Relative, parsing_mode);
  163. if (!selector_list.is_error())
  164. return selector_list.release_value();
  165. return {};
  166. }
  167. template<typename T>
  168. Parser::ParseErrorOr<SelectorList> Parser::parse_a_selector_list(TokenStream<T>& tokens, SelectorType mode, SelectorParsingMode parsing_mode)
  169. {
  170. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  171. Vector<NonnullRefPtr<Selector>> selectors;
  172. for (auto& selector_parts : comma_separated_lists) {
  173. auto stream = TokenStream(selector_parts);
  174. auto selector = parse_complex_selector(stream, mode);
  175. if (selector.is_error()) {
  176. if (parsing_mode == SelectorParsingMode::Forgiving)
  177. continue;
  178. return selector.error();
  179. }
  180. selectors.append(selector.release_value());
  181. }
  182. if (selectors.is_empty() && parsing_mode != SelectorParsingMode::Forgiving)
  183. return ParseError::SyntaxError;
  184. return selectors;
  185. }
  186. Parser::ParseErrorOr<NonnullRefPtr<Selector>> Parser::parse_complex_selector(TokenStream<ComponentValue>& tokens, SelectorType mode)
  187. {
  188. Vector<Selector::CompoundSelector> compound_selectors;
  189. auto first_selector = TRY(parse_compound_selector(tokens));
  190. if (!first_selector.has_value())
  191. return ParseError::SyntaxError;
  192. if (mode == SelectorType::Standalone) {
  193. if (first_selector->combinator != Selector::Combinator::Descendant)
  194. return ParseError::SyntaxError;
  195. first_selector->combinator = Selector::Combinator::None;
  196. }
  197. compound_selectors.append(first_selector.release_value());
  198. while (tokens.has_next_token()) {
  199. auto compound_selector = TRY(parse_compound_selector(tokens));
  200. if (!compound_selector.has_value())
  201. break;
  202. compound_selectors.append(compound_selector.release_value());
  203. }
  204. if (compound_selectors.is_empty())
  205. return ParseError::SyntaxError;
  206. return Selector::create(move(compound_selectors));
  207. }
  208. Parser::ParseErrorOr<Optional<Selector::CompoundSelector>> Parser::parse_compound_selector(TokenStream<ComponentValue>& tokens)
  209. {
  210. tokens.skip_whitespace();
  211. auto combinator = parse_selector_combinator(tokens).value_or(Selector::Combinator::Descendant);
  212. tokens.skip_whitespace();
  213. Vector<Selector::SimpleSelector> simple_selectors;
  214. while (tokens.has_next_token()) {
  215. auto component = TRY(parse_simple_selector(tokens));
  216. if (!component.has_value())
  217. break;
  218. simple_selectors.append(component.release_value());
  219. }
  220. if (simple_selectors.is_empty())
  221. return Optional<Selector::CompoundSelector> {};
  222. return Selector::CompoundSelector { combinator, move(simple_selectors) };
  223. }
  224. Optional<Selector::Combinator> Parser::parse_selector_combinator(TokenStream<ComponentValue>& tokens)
  225. {
  226. auto const& current_value = tokens.next_token();
  227. if (current_value.is(Token::Type::Delim)) {
  228. switch (current_value.token().delim()) {
  229. case '>':
  230. return Selector::Combinator::ImmediateChild;
  231. case '+':
  232. return Selector::Combinator::NextSibling;
  233. case '~':
  234. return Selector::Combinator::SubsequentSibling;
  235. case '|': {
  236. auto const& next = tokens.peek_token();
  237. if (next.is(Token::Type::EndOfFile))
  238. return {};
  239. if (next.is_delim('|')) {
  240. tokens.next_token();
  241. return Selector::Combinator::Column;
  242. }
  243. }
  244. }
  245. }
  246. tokens.reconsume_current_input_token();
  247. return {};
  248. }
  249. Optional<Selector::SimpleSelector::QualifiedName> Parser::parse_selector_qualified_name(TokenStream<ComponentValue>& tokens, AllowWildcardName allow_wildcard_name)
  250. {
  251. auto is_name = [](ComponentValue const& token) {
  252. return token.is_delim('*') || token.is(Token::Type::Ident);
  253. };
  254. auto get_name = [](ComponentValue const& token) {
  255. if (token.is_delim('*'))
  256. return FlyString::from_utf8("*"sv);
  257. return FlyString::from_utf8(token.token().ident());
  258. };
  259. // There are 3 possibilities here:
  260. // (Where <name> and <namespace> are either an <ident> or a `*` delim)
  261. // 1) `|<name>`
  262. // 2) `<namespace>|<name>`
  263. // 3) `<name>`
  264. // Whitespace is forbidden between any of these parts. https://www.w3.org/TR/selectors-4/#white-space
  265. auto transaction = tokens.begin_transaction();
  266. auto first_token = tokens.next_token();
  267. if (first_token.is_delim('|')) {
  268. // Case 1: `|<name>`
  269. if (is_name(tokens.peek_token())) {
  270. auto name_token = tokens.next_token();
  271. if (allow_wildcard_name == AllowWildcardName::No && name_token.is_delim('*'))
  272. return {};
  273. transaction.commit();
  274. return Selector::SimpleSelector::QualifiedName {
  275. .namespace_type = Selector::SimpleSelector::QualifiedName::NamespaceType::None,
  276. .name = get_name(name_token).release_value_but_fixme_should_propagate_errors(),
  277. };
  278. }
  279. return {};
  280. }
  281. if (!is_name(first_token))
  282. return {};
  283. if (tokens.peek_token().is_delim('|') && is_name(tokens.peek_token(1))) {
  284. // Case 2: `<namespace>|<name>`
  285. (void)tokens.next_token(); // `|`
  286. auto namespace_ = get_name(first_token).release_value_but_fixme_should_propagate_errors();
  287. auto name = get_name(tokens.next_token()).release_value_but_fixme_should_propagate_errors();
  288. if (allow_wildcard_name == AllowWildcardName::No && name == "*"sv)
  289. return {};
  290. auto namespace_type = namespace_ == "*"sv
  291. ? Selector::SimpleSelector::QualifiedName::NamespaceType::Any
  292. : Selector::SimpleSelector::QualifiedName::NamespaceType::Named;
  293. transaction.commit();
  294. return Selector::SimpleSelector::QualifiedName {
  295. .namespace_type = namespace_type,
  296. .namespace_ = namespace_,
  297. .name = name,
  298. };
  299. }
  300. // Case 3: `<name>`
  301. auto& name_token = first_token;
  302. if (allow_wildcard_name == AllowWildcardName::No && name_token.is_delim('*'))
  303. return {};
  304. transaction.commit();
  305. return Selector::SimpleSelector::QualifiedName {
  306. .namespace_type = Selector::SimpleSelector::QualifiedName::NamespaceType::Default,
  307. .name = get_name(name_token).release_value_but_fixme_should_propagate_errors(),
  308. };
  309. }
  310. Parser::ParseErrorOr<Selector::SimpleSelector> Parser::parse_attribute_simple_selector(ComponentValue const& first_value)
  311. {
  312. auto attribute_tokens = TokenStream { first_value.block().values() };
  313. attribute_tokens.skip_whitespace();
  314. if (!attribute_tokens.has_next_token()) {
  315. dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
  316. return ParseError::SyntaxError;
  317. }
  318. // FIXME: Handle namespace prefix for attribute name.
  319. auto const& attribute_part = attribute_tokens.next_token();
  320. if (!attribute_part.is(Token::Type::Ident)) {
  321. dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  322. return ParseError::SyntaxError;
  323. }
  324. Selector::SimpleSelector simple_selector {
  325. .type = Selector::SimpleSelector::Type::Attribute,
  326. .value = Selector::SimpleSelector::Attribute {
  327. .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
  328. // FIXME: Case-sensitivity is defined by the document language.
  329. // HTML is insensitive with attribute names, and our code generally assumes
  330. // they are converted to lowercase, so we do that here too. If we want to be
  331. // correct with XML later, we'll need to keep the original case and then do
  332. // a case-insensitive compare later.
  333. .name = FlyString::from_deprecated_fly_string(attribute_part.token().ident().to_lowercase_string()).release_value_but_fixme_should_propagate_errors(),
  334. .case_type = Selector::SimpleSelector::Attribute::CaseType::DefaultMatch,
  335. }
  336. };
  337. attribute_tokens.skip_whitespace();
  338. if (!attribute_tokens.has_next_token())
  339. return simple_selector;
  340. auto const& delim_part = attribute_tokens.next_token();
  341. if (!delim_part.is(Token::Type::Delim)) {
  342. dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  343. return ParseError::SyntaxError;
  344. }
  345. if (delim_part.token().delim() == '=') {
  346. simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
  347. } else {
  348. if (!attribute_tokens.has_next_token()) {
  349. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
  350. return ParseError::SyntaxError;
  351. }
  352. auto const& delim_second_part = attribute_tokens.next_token();
  353. if (!delim_second_part.is_delim('=')) {
  354. dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  355. return ParseError::SyntaxError;
  356. }
  357. switch (delim_part.token().delim()) {
  358. case '~':
  359. simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
  360. break;
  361. case '*':
  362. simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
  363. break;
  364. case '|':
  365. simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
  366. break;
  367. case '^':
  368. simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
  369. break;
  370. case '$':
  371. simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
  372. break;
  373. default:
  374. attribute_tokens.reconsume_current_input_token();
  375. }
  376. }
  377. attribute_tokens.skip_whitespace();
  378. if (!attribute_tokens.has_next_token()) {
  379. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
  380. return ParseError::SyntaxError;
  381. }
  382. auto const& value_part = attribute_tokens.next_token();
  383. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  384. dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  385. return ParseError::SyntaxError;
  386. }
  387. auto value_string_view = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  388. simple_selector.attribute().value = String::from_utf8(value_string_view).release_value_but_fixme_should_propagate_errors();
  389. attribute_tokens.skip_whitespace();
  390. // Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  391. if (attribute_tokens.has_next_token()) {
  392. auto const& case_sensitivity_part = attribute_tokens.next_token();
  393. if (case_sensitivity_part.is(Token::Type::Ident)) {
  394. auto case_sensitivity = case_sensitivity_part.token().ident();
  395. if (case_sensitivity.equals_ignoring_ascii_case("i"sv)) {
  396. simple_selector.attribute().case_type = Selector::SimpleSelector::Attribute::CaseType::CaseInsensitiveMatch;
  397. } else if (case_sensitivity.equals_ignoring_ascii_case("s"sv)) {
  398. simple_selector.attribute().case_type = Selector::SimpleSelector::Attribute::CaseType::CaseSensitiveMatch;
  399. } else {
  400. dbgln_if(CSS_PARSER_DEBUG, "Expected a \"i\" or \"s\" attribute selector case sensitivity identifier, got: '{}'", case_sensitivity_part.to_debug_string());
  401. return ParseError::SyntaxError;
  402. }
  403. } else {
  404. dbgln_if(CSS_PARSER_DEBUG, "Expected an attribute selector case sensitivity identifier, got: '{}'", case_sensitivity_part.to_debug_string());
  405. return ParseError::SyntaxError;
  406. }
  407. }
  408. if (attribute_tokens.has_next_token()) {
  409. dbgln_if(CSS_PARSER_DEBUG, "Was not expecting anything else inside attribute selector.");
  410. return ParseError::SyntaxError;
  411. }
  412. return simple_selector;
  413. }
  414. Parser::ParseErrorOr<Selector::SimpleSelector> Parser::parse_pseudo_simple_selector(TokenStream<ComponentValue>& tokens)
  415. {
  416. auto peek_token_ends_selector = [&]() -> bool {
  417. auto const& value = tokens.peek_token();
  418. return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
  419. };
  420. if (peek_token_ends_selector())
  421. return ParseError::SyntaxError;
  422. bool is_pseudo = false;
  423. if (tokens.peek_token().is(Token::Type::Colon)) {
  424. is_pseudo = true;
  425. tokens.next_token();
  426. if (peek_token_ends_selector())
  427. return ParseError::SyntaxError;
  428. }
  429. if (is_pseudo) {
  430. auto const& name_token = tokens.next_token();
  431. if (!name_token.is(Token::Type::Ident)) {
  432. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
  433. return ParseError::SyntaxError;
  434. }
  435. auto pseudo_name = name_token.token().ident();
  436. auto pseudo_element = pseudo_element_from_string(pseudo_name);
  437. // Note: We allow the "ignored" -webkit prefix here for -webkit-progress-bar/-webkit-progress-bar
  438. if (!pseudo_element.has_value() && has_ignored_vendor_prefix(pseudo_name))
  439. return ParseError::IncludesIgnoredVendorPrefix;
  440. if (!pseudo_element.has_value()) {
  441. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-element: '::{}'", pseudo_name);
  442. return ParseError::SyntaxError;
  443. }
  444. return Selector::SimpleSelector {
  445. .type = Selector::SimpleSelector::Type::PseudoElement,
  446. .value = pseudo_element.value()
  447. };
  448. }
  449. if (peek_token_ends_selector())
  450. return ParseError::SyntaxError;
  451. auto const& pseudo_class_token = tokens.next_token();
  452. if (pseudo_class_token.is(Token::Type::Ident)) {
  453. auto pseudo_name = pseudo_class_token.token().ident();
  454. if (has_ignored_vendor_prefix(pseudo_name))
  455. return ParseError::IncludesIgnoredVendorPrefix;
  456. auto make_pseudo_class_selector = [](auto pseudo_class) {
  457. return Selector::SimpleSelector {
  458. .type = Selector::SimpleSelector::Type::PseudoClass,
  459. .value = Selector::SimpleSelector::PseudoClass {
  460. .type = pseudo_class }
  461. };
  462. };
  463. if (pseudo_name.equals_ignoring_ascii_case("active"sv))
  464. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Active);
  465. if (pseudo_name.equals_ignoring_ascii_case("buffering"sv))
  466. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Buffering);
  467. if (pseudo_name.equals_ignoring_ascii_case("checked"sv))
  468. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Checked);
  469. if (pseudo_name.equals_ignoring_ascii_case("indeterminate"sv))
  470. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Indeterminate);
  471. if (pseudo_name.equals_ignoring_ascii_case("defined"sv))
  472. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Defined);
  473. if (pseudo_name.equals_ignoring_ascii_case("disabled"sv))
  474. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Disabled);
  475. if (pseudo_name.equals_ignoring_ascii_case("empty"sv))
  476. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Empty);
  477. if (pseudo_name.equals_ignoring_ascii_case("enabled"sv))
  478. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Enabled);
  479. if (pseudo_name.equals_ignoring_ascii_case("first-child"sv))
  480. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::FirstChild);
  481. if (pseudo_name.equals_ignoring_ascii_case("first-of-type"sv))
  482. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::FirstOfType);
  483. if (pseudo_name.equals_ignoring_ascii_case("focus"sv))
  484. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Focus);
  485. if (pseudo_name.equals_ignoring_ascii_case("focus-visible"sv))
  486. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::FocusVisible);
  487. if (pseudo_name.equals_ignoring_ascii_case("focus-within"sv))
  488. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::FocusWithin);
  489. if (pseudo_name.equals_ignoring_ascii_case("hover"sv))
  490. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Hover);
  491. if (pseudo_name.equals_ignoring_ascii_case("last-child"sv))
  492. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::LastChild);
  493. if (pseudo_name.equals_ignoring_ascii_case("last-of-type"sv))
  494. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::LastOfType);
  495. if (pseudo_name.equals_ignoring_ascii_case("link"sv))
  496. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Link);
  497. if (pseudo_name.equals_ignoring_ascii_case("muted"sv))
  498. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Muted);
  499. if (pseudo_name.equals_ignoring_ascii_case("only-child"sv))
  500. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::OnlyChild);
  501. if (pseudo_name.equals_ignoring_ascii_case("only-of-type"sv))
  502. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::OnlyOfType);
  503. if (pseudo_name.equals_ignoring_ascii_case("playing"sv))
  504. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Playing);
  505. if (pseudo_name.equals_ignoring_ascii_case("paused"sv))
  506. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Paused);
  507. if (pseudo_name.equals_ignoring_ascii_case("root"sv))
  508. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Root);
  509. if (pseudo_name.equals_ignoring_ascii_case("seeking"sv))
  510. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Seeking);
  511. if (pseudo_name.equals_ignoring_ascii_case("stalled"sv))
  512. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Stalled);
  513. if (pseudo_name.equals_ignoring_ascii_case("host"sv))
  514. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Host);
  515. if (pseudo_name.equals_ignoring_ascii_case("visited"sv))
  516. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Visited);
  517. if (pseudo_name.equals_ignoring_ascii_case("volume-locked"sv))
  518. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::VolumeLocked);
  519. if (pseudo_name.equals_ignoring_ascii_case("scope"sv))
  520. return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Scope);
  521. // Single-colon syntax allowed for ::after, ::before, ::first-letter and ::first-line for compatibility.
  522. // https://www.w3.org/TR/selectors/#pseudo-element-syntax
  523. if (auto pseudo_element = pseudo_element_from_string(pseudo_name); pseudo_element.has_value()) {
  524. switch (pseudo_element.value()) {
  525. case Selector::PseudoElement::After:
  526. case Selector::PseudoElement::Before:
  527. case Selector::PseudoElement::FirstLetter:
  528. case Selector::PseudoElement::FirstLine:
  529. return Selector::SimpleSelector {
  530. .type = Selector::SimpleSelector::Type::PseudoElement,
  531. .value = pseudo_element.value()
  532. };
  533. default:
  534. break;
  535. }
  536. }
  537. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-class: ':{}'", pseudo_name);
  538. return ParseError::SyntaxError;
  539. }
  540. if (pseudo_class_token.is_function()) {
  541. auto parse_nth_child_selector = [this](auto pseudo_class, Vector<ComponentValue> const& function_values, bool allow_of = false) -> ParseErrorOr<Selector::SimpleSelector> {
  542. auto tokens = TokenStream<ComponentValue>(function_values);
  543. auto nth_child_pattern = parse_a_n_plus_b_pattern(tokens);
  544. if (!nth_child_pattern.has_value()) {
  545. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid An+B format for {}", pseudo_class_name(pseudo_class));
  546. return ParseError::SyntaxError;
  547. }
  548. tokens.skip_whitespace();
  549. if (!tokens.has_next_token()) {
  550. return Selector::SimpleSelector {
  551. .type = Selector::SimpleSelector::Type::PseudoClass,
  552. .value = Selector::SimpleSelector::PseudoClass {
  553. .type = pseudo_class,
  554. .nth_child_pattern = nth_child_pattern.release_value() }
  555. };
  556. }
  557. if (!allow_of)
  558. return ParseError::SyntaxError;
  559. // Parse the `of <selector-list>` syntax
  560. auto const& maybe_of = tokens.next_token();
  561. if (!(maybe_of.is(Token::Type::Ident) && maybe_of.token().ident().equals_ignoring_ascii_case("of"sv)))
  562. return ParseError::SyntaxError;
  563. tokens.skip_whitespace();
  564. auto selector_list = TRY(parse_a_selector_list(tokens, SelectorType::Standalone));
  565. tokens.skip_whitespace();
  566. if (tokens.has_next_token())
  567. return ParseError::SyntaxError;
  568. return Selector::SimpleSelector {
  569. .type = Selector::SimpleSelector::Type::PseudoClass,
  570. .value = Selector::SimpleSelector::PseudoClass {
  571. .type = pseudo_class,
  572. .nth_child_pattern = nth_child_pattern.release_value(),
  573. .argument_selector_list = move(selector_list) }
  574. };
  575. };
  576. auto const& pseudo_function = pseudo_class_token.function();
  577. if (pseudo_function.name().equals_ignoring_ascii_case("is"sv)
  578. || pseudo_function.name().equals_ignoring_ascii_case("where"sv)) {
  579. auto function_token_stream = TokenStream(pseudo_function.values());
  580. // NOTE: Because it's forgiving, even complete garbage will parse OK as an empty selector-list.
  581. auto argument_selector_list = MUST(parse_a_selector_list(function_token_stream, SelectorType::Standalone, SelectorParsingMode::Forgiving));
  582. return Selector::SimpleSelector {
  583. .type = Selector::SimpleSelector::Type::PseudoClass,
  584. .value = Selector::SimpleSelector::PseudoClass {
  585. .type = pseudo_function.name().equals_ignoring_ascii_case("is"sv)
  586. ? Selector::SimpleSelector::PseudoClass::Type::Is
  587. : Selector::SimpleSelector::PseudoClass::Type::Where,
  588. .argument_selector_list = move(argument_selector_list) }
  589. };
  590. }
  591. if (pseudo_function.name().equals_ignoring_ascii_case("not"sv)) {
  592. auto function_token_stream = TokenStream(pseudo_function.values());
  593. auto not_selector = TRY(parse_a_selector_list(function_token_stream, SelectorType::Standalone));
  594. return Selector::SimpleSelector {
  595. .type = Selector::SimpleSelector::Type::PseudoClass,
  596. .value = Selector::SimpleSelector::PseudoClass {
  597. .type = Selector::SimpleSelector::PseudoClass::Type::Not,
  598. .argument_selector_list = move(not_selector) }
  599. };
  600. }
  601. if (pseudo_function.name().equals_ignoring_ascii_case("host"sv)) {
  602. auto function_token_stream = TokenStream(pseudo_function.values());
  603. auto host_selector = TRY(parse_a_selector_list(function_token_stream, SelectorType::Standalone));
  604. return Selector::SimpleSelector {
  605. .type = Selector::SimpleSelector::Type::PseudoClass,
  606. .value = Selector::SimpleSelector::PseudoClass {
  607. .type = Selector::SimpleSelector::PseudoClass::Type::Host,
  608. .argument_selector_list = move(host_selector) }
  609. };
  610. }
  611. if (pseudo_function.name().equals_ignoring_ascii_case("lang"sv)) {
  612. if (pseudo_function.values().is_empty()) {
  613. dbgln_if(CSS_PARSER_DEBUG, "Empty :lang() selector");
  614. return ParseError::SyntaxError;
  615. }
  616. // FIXME: Support multiple, comma-separated, language ranges.
  617. Vector<FlyString> languages;
  618. languages.append(pseudo_function.values().first().token().to_string().release_value_but_fixme_should_propagate_errors());
  619. return Selector::SimpleSelector {
  620. .type = Selector::SimpleSelector::Type::PseudoClass,
  621. .value = Selector::SimpleSelector::PseudoClass {
  622. .type = Selector::SimpleSelector::PseudoClass::Type::Lang,
  623. .languages = move(languages) }
  624. };
  625. }
  626. if (pseudo_function.name().equals_ignoring_ascii_case("nth-child"sv))
  627. return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthChild, pseudo_function.values(), true);
  628. if (pseudo_function.name().equals_ignoring_ascii_case("nth-last-child"sv))
  629. return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthLastChild, pseudo_function.values(), true);
  630. if (pseudo_function.name().equals_ignoring_ascii_case("nth-of-type"sv))
  631. return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthOfType, pseudo_function.values(), false);
  632. if (pseudo_function.name().equals_ignoring_ascii_case("nth-last-of-type"sv))
  633. return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthLastOfType, pseudo_function.values(), false);
  634. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-class function: ':{}'()", pseudo_function.name());
  635. return ParseError::SyntaxError;
  636. }
  637. dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
  638. return ParseError::SyntaxError;
  639. }
  640. Parser::ParseErrorOr<Optional<Selector::SimpleSelector>> Parser::parse_simple_selector(TokenStream<ComponentValue>& tokens)
  641. {
  642. auto peek_token_ends_selector = [&]() -> bool {
  643. auto const& value = tokens.peek_token();
  644. return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
  645. };
  646. if (peek_token_ends_selector())
  647. return Optional<Selector::SimpleSelector> {};
  648. auto const& first_value = tokens.next_token();
  649. if (first_value.is(Token::Type::Delim)) {
  650. u32 delim = first_value.token().delim();
  651. switch (delim) {
  652. case '*':
  653. return Selector::SimpleSelector {
  654. .type = Selector::SimpleSelector::Type::Universal
  655. };
  656. case '.': {
  657. if (peek_token_ends_selector())
  658. return ParseError::SyntaxError;
  659. auto const& class_name_value = tokens.next_token();
  660. if (!class_name_value.is(Token::Type::Ident)) {
  661. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident after '.', got: {}", class_name_value.to_debug_string());
  662. return ParseError::SyntaxError;
  663. }
  664. return Selector::SimpleSelector {
  665. .type = Selector::SimpleSelector::Type::Class,
  666. .value = Selector::SimpleSelector::Name { FlyString::from_utf8(class_name_value.token().ident()).release_value_but_fixme_should_propagate_errors() }
  667. };
  668. }
  669. case '>':
  670. case '+':
  671. case '~':
  672. case '|':
  673. // Whitespace is not required between the compound-selector and a combinator.
  674. // So, if we see a combinator, return that this compound-selector is done, instead of a syntax error.
  675. tokens.reconsume_current_input_token();
  676. return Optional<Selector::SimpleSelector> {};
  677. default:
  678. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  679. return ParseError::SyntaxError;
  680. }
  681. }
  682. if (first_value.is(Token::Type::Hash)) {
  683. if (first_value.token().hash_type() != Token::HashType::Id) {
  684. dbgln_if(CSS_PARSER_DEBUG, "Selector contains hash token that is not an id: {}", first_value.to_debug_string());
  685. return ParseError::SyntaxError;
  686. }
  687. return Selector::SimpleSelector {
  688. .type = Selector::SimpleSelector::Type::Id,
  689. .value = Selector::SimpleSelector::Name { FlyString::from_utf8(first_value.token().hash_value()).release_value_but_fixme_should_propagate_errors() }
  690. };
  691. }
  692. if (first_value.is(Token::Type::Ident)) {
  693. return Selector::SimpleSelector {
  694. .type = Selector::SimpleSelector::Type::TagName,
  695. // FIXME: XML requires case-sensitivity for identifiers, while HTML does not. As such, this should be reworked if XML support is added.
  696. .value = Selector::SimpleSelector::Name { FlyString::from_deprecated_fly_string(first_value.token().ident().to_lowercase_string()).release_value_but_fixme_should_propagate_errors() }
  697. };
  698. }
  699. if (first_value.is_block() && first_value.block().is_square())
  700. return TRY(parse_attribute_simple_selector(first_value));
  701. if (first_value.is(Token::Type::Colon))
  702. return TRY(parse_pseudo_simple_selector(tokens));
  703. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  704. return ParseError::SyntaxError;
  705. }
  706. Vector<NonnullRefPtr<MediaQuery>> Parser::parse_as_media_query_list()
  707. {
  708. return parse_a_media_query_list(m_token_stream);
  709. }
  710. template<typename T>
  711. Vector<NonnullRefPtr<MediaQuery>> Parser::parse_a_media_query_list(TokenStream<T>& tokens)
  712. {
  713. // https://www.w3.org/TR/mediaqueries-4/#mq-list
  714. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  715. AK::Vector<NonnullRefPtr<MediaQuery>> media_queries;
  716. for (auto& media_query_parts : comma_separated_lists) {
  717. auto stream = TokenStream(media_query_parts);
  718. media_queries.append(parse_media_query(stream));
  719. }
  720. return media_queries;
  721. }
  722. RefPtr<MediaQuery> Parser::parse_as_media_query()
  723. {
  724. // https://www.w3.org/TR/cssom-1/#parse-a-media-query
  725. auto media_query_list = parse_as_media_query_list();
  726. if (media_query_list.is_empty())
  727. return MediaQuery::create_not_all();
  728. if (media_query_list.size() == 1)
  729. return media_query_list.first();
  730. return nullptr;
  731. }
  732. // `<media-query>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-query
  733. NonnullRefPtr<MediaQuery> Parser::parse_media_query(TokenStream<ComponentValue>& tokens)
  734. {
  735. // `<media-query> = <media-condition>
  736. // | [ not | only ]? <media-type> [ and <media-condition-without-or> ]?`
  737. // `[ not | only ]?`, Returns whether to negate the query
  738. auto parse_initial_modifier = [](auto& tokens) -> Optional<bool> {
  739. auto transaction = tokens.begin_transaction();
  740. tokens.skip_whitespace();
  741. auto& token = tokens.next_token();
  742. if (!token.is(Token::Type::Ident))
  743. return {};
  744. auto ident = token.token().ident();
  745. if (ident.equals_ignoring_ascii_case("not"sv)) {
  746. transaction.commit();
  747. return true;
  748. }
  749. if (ident.equals_ignoring_ascii_case("only"sv)) {
  750. transaction.commit();
  751. return false;
  752. }
  753. return {};
  754. };
  755. auto invalid_media_query = [&]() {
  756. // "A media query that does not match the grammar in the previous section must be replaced by `not all`
  757. // during parsing." - https://www.w3.org/TR/mediaqueries-5/#error-handling
  758. if constexpr (CSS_PARSER_DEBUG) {
  759. dbgln("Invalid media query:");
  760. tokens.dump_all_tokens();
  761. }
  762. return MediaQuery::create_not_all();
  763. };
  764. auto media_query = MediaQuery::create();
  765. tokens.skip_whitespace();
  766. // `<media-condition>`
  767. if (auto media_condition = parse_media_condition(tokens, MediaCondition::AllowOr::Yes)) {
  768. tokens.skip_whitespace();
  769. if (tokens.has_next_token())
  770. return invalid_media_query();
  771. media_query->m_media_condition = move(media_condition);
  772. return media_query;
  773. }
  774. // `[ not | only ]?`
  775. if (auto modifier = parse_initial_modifier(tokens); modifier.has_value()) {
  776. media_query->m_negated = modifier.value();
  777. tokens.skip_whitespace();
  778. }
  779. // `<media-type>`
  780. if (auto media_type = parse_media_type(tokens); media_type.has_value()) {
  781. media_query->m_media_type = media_type.value();
  782. tokens.skip_whitespace();
  783. } else {
  784. return invalid_media_query();
  785. }
  786. if (!tokens.has_next_token())
  787. return media_query;
  788. // `[ and <media-condition-without-or> ]?`
  789. if (auto maybe_and = tokens.next_token(); maybe_and.is(Token::Type::Ident) && maybe_and.token().ident().equals_ignoring_ascii_case("and"sv)) {
  790. if (auto media_condition = parse_media_condition(tokens, MediaCondition::AllowOr::No)) {
  791. tokens.skip_whitespace();
  792. if (tokens.has_next_token())
  793. return invalid_media_query();
  794. media_query->m_media_condition = move(media_condition);
  795. return media_query;
  796. }
  797. return invalid_media_query();
  798. }
  799. return invalid_media_query();
  800. }
  801. // `<media-condition>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-condition
  802. // `<media-condition-widthout-or>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-condition-without-or
  803. // (We distinguish between these two with the `allow_or` parameter.)
  804. OwnPtr<MediaCondition> Parser::parse_media_condition(TokenStream<ComponentValue>& tokens, MediaCondition::AllowOr allow_or)
  805. {
  806. // `<media-not> | <media-in-parens> [ <media-and>* | <media-or>* ]`
  807. auto transaction = tokens.begin_transaction();
  808. tokens.skip_whitespace();
  809. // `<media-not> = not <media-in-parens>`
  810. auto parse_media_not = [&](auto& tokens) -> OwnPtr<MediaCondition> {
  811. auto local_transaction = tokens.begin_transaction();
  812. tokens.skip_whitespace();
  813. auto& first_token = tokens.next_token();
  814. if (first_token.is(Token::Type::Ident) && first_token.token().ident().equals_ignoring_ascii_case("not"sv)) {
  815. if (auto child_condition = parse_media_condition(tokens, MediaCondition::AllowOr::Yes)) {
  816. local_transaction.commit();
  817. return MediaCondition::from_not(child_condition.release_nonnull());
  818. }
  819. }
  820. return {};
  821. };
  822. auto parse_media_with_combinator = [&](auto& tokens, StringView combinator) -> OwnPtr<MediaCondition> {
  823. auto local_transaction = tokens.begin_transaction();
  824. tokens.skip_whitespace();
  825. auto& first = tokens.next_token();
  826. if (first.is(Token::Type::Ident) && first.token().ident().equals_ignoring_ascii_case(combinator)) {
  827. tokens.skip_whitespace();
  828. if (auto media_in_parens = parse_media_in_parens(tokens)) {
  829. local_transaction.commit();
  830. return media_in_parens;
  831. }
  832. }
  833. return {};
  834. };
  835. // `<media-and> = and <media-in-parens>`
  836. auto parse_media_and = [&](auto& tokens) { return parse_media_with_combinator(tokens, "and"sv); };
  837. // `<media-or> = or <media-in-parens>`
  838. auto parse_media_or = [&](auto& tokens) { return parse_media_with_combinator(tokens, "or"sv); };
  839. // `<media-not>`
  840. if (auto maybe_media_not = parse_media_not(tokens)) {
  841. transaction.commit();
  842. return maybe_media_not.release_nonnull();
  843. }
  844. // `<media-in-parens> [ <media-and>* | <media-or>* ]`
  845. if (auto maybe_media_in_parens = parse_media_in_parens(tokens)) {
  846. tokens.skip_whitespace();
  847. // Only `<media-in-parens>`
  848. if (!tokens.has_next_token()) {
  849. transaction.commit();
  850. return maybe_media_in_parens.release_nonnull();
  851. }
  852. Vector<NonnullOwnPtr<MediaCondition>> child_conditions;
  853. child_conditions.append(maybe_media_in_parens.release_nonnull());
  854. // `<media-and>*`
  855. if (auto media_and = parse_media_and(tokens)) {
  856. child_conditions.append(media_and.release_nonnull());
  857. tokens.skip_whitespace();
  858. while (tokens.has_next_token()) {
  859. if (auto next_media_and = parse_media_and(tokens)) {
  860. child_conditions.append(next_media_and.release_nonnull());
  861. tokens.skip_whitespace();
  862. continue;
  863. }
  864. // We failed - invalid syntax!
  865. return {};
  866. }
  867. transaction.commit();
  868. return MediaCondition::from_and_list(move(child_conditions));
  869. }
  870. // `<media-or>*`
  871. if (allow_or == MediaCondition::AllowOr::Yes) {
  872. if (auto media_or = parse_media_or(tokens)) {
  873. child_conditions.append(media_or.release_nonnull());
  874. tokens.skip_whitespace();
  875. while (tokens.has_next_token()) {
  876. if (auto next_media_or = parse_media_or(tokens)) {
  877. child_conditions.append(next_media_or.release_nonnull());
  878. tokens.skip_whitespace();
  879. continue;
  880. }
  881. // We failed - invalid syntax!
  882. return {};
  883. }
  884. transaction.commit();
  885. return MediaCondition::from_or_list(move(child_conditions));
  886. }
  887. }
  888. }
  889. return {};
  890. }
  891. // `<media-feature>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-feature
  892. Optional<MediaFeature> Parser::parse_media_feature(TokenStream<ComponentValue>& tokens)
  893. {
  894. // `[ <mf-plain> | <mf-boolean> | <mf-range> ]`
  895. tokens.skip_whitespace();
  896. // `<mf-name> = <ident>`
  897. struct MediaFeatureName {
  898. enum Type {
  899. Normal,
  900. Min,
  901. Max
  902. } type;
  903. MediaFeatureID id;
  904. };
  905. auto parse_mf_name = [](auto& tokens, bool allow_min_max_prefix) -> Optional<MediaFeatureName> {
  906. auto transaction = tokens.begin_transaction();
  907. auto& token = tokens.next_token();
  908. if (token.is(Token::Type::Ident)) {
  909. auto name = token.token().ident();
  910. if (auto id = media_feature_id_from_string(name); id.has_value()) {
  911. transaction.commit();
  912. return MediaFeatureName { MediaFeatureName::Type::Normal, id.value() };
  913. }
  914. if (allow_min_max_prefix && (name.starts_with("min-"sv, CaseSensitivity::CaseInsensitive) || name.starts_with("max-"sv, CaseSensitivity::CaseInsensitive))) {
  915. auto adjusted_name = name.substring_view(4);
  916. if (auto id = media_feature_id_from_string(adjusted_name); id.has_value() && media_feature_type_is_range(id.value())) {
  917. transaction.commit();
  918. return MediaFeatureName {
  919. name.starts_with("min-"sv, CaseSensitivity::CaseInsensitive) ? MediaFeatureName::Type::Min : MediaFeatureName::Type::Max,
  920. id.value()
  921. };
  922. }
  923. }
  924. }
  925. return {};
  926. };
  927. // `<mf-boolean> = <mf-name>`
  928. auto parse_mf_boolean = [&](auto& tokens) -> Optional<MediaFeature> {
  929. auto transaction = tokens.begin_transaction();
  930. tokens.skip_whitespace();
  931. if (auto maybe_name = parse_mf_name(tokens, false); maybe_name.has_value()) {
  932. tokens.skip_whitespace();
  933. if (!tokens.has_next_token()) {
  934. transaction.commit();
  935. return MediaFeature::boolean(maybe_name->id);
  936. }
  937. }
  938. return {};
  939. };
  940. // `<mf-plain> = <mf-name> : <mf-value>`
  941. auto parse_mf_plain = [&](auto& tokens) -> Optional<MediaFeature> {
  942. auto transaction = tokens.begin_transaction();
  943. tokens.skip_whitespace();
  944. if (auto maybe_name = parse_mf_name(tokens, true); maybe_name.has_value()) {
  945. tokens.skip_whitespace();
  946. if (tokens.next_token().is(Token::Type::Colon)) {
  947. tokens.skip_whitespace();
  948. if (auto maybe_value = parse_media_feature_value(maybe_name->id, tokens); maybe_value.has_value()) {
  949. tokens.skip_whitespace();
  950. if (!tokens.has_next_token()) {
  951. transaction.commit();
  952. switch (maybe_name->type) {
  953. case MediaFeatureName::Type::Normal:
  954. return MediaFeature::plain(maybe_name->id, maybe_value.release_value());
  955. case MediaFeatureName::Type::Min:
  956. return MediaFeature::min(maybe_name->id, maybe_value.release_value());
  957. case MediaFeatureName::Type::Max:
  958. return MediaFeature::max(maybe_name->id, maybe_value.release_value());
  959. }
  960. VERIFY_NOT_REACHED();
  961. }
  962. }
  963. }
  964. }
  965. return {};
  966. };
  967. // `<mf-lt> = '<' '='?
  968. // <mf-gt> = '>' '='?
  969. // <mf-eq> = '='
  970. // <mf-comparison> = <mf-lt> | <mf-gt> | <mf-eq>`
  971. auto parse_comparison = [](auto& tokens) -> Optional<MediaFeature::Comparison> {
  972. auto transaction = tokens.begin_transaction();
  973. tokens.skip_whitespace();
  974. auto& first = tokens.next_token();
  975. if (first.is(Token::Type::Delim)) {
  976. auto first_delim = first.token().delim();
  977. if (first_delim == '=') {
  978. transaction.commit();
  979. return MediaFeature::Comparison::Equal;
  980. }
  981. if (first_delim == '<') {
  982. auto& second = tokens.peek_token();
  983. if (second.is_delim('=')) {
  984. tokens.next_token();
  985. transaction.commit();
  986. return MediaFeature::Comparison::LessThanOrEqual;
  987. }
  988. transaction.commit();
  989. return MediaFeature::Comparison::LessThan;
  990. }
  991. if (first_delim == '>') {
  992. auto& second = tokens.peek_token();
  993. if (second.is_delim('=')) {
  994. tokens.next_token();
  995. transaction.commit();
  996. return MediaFeature::Comparison::GreaterThanOrEqual;
  997. }
  998. transaction.commit();
  999. return MediaFeature::Comparison::GreaterThan;
  1000. }
  1001. }
  1002. return {};
  1003. };
  1004. auto flip = [](MediaFeature::Comparison comparison) {
  1005. switch (comparison) {
  1006. case MediaFeature::Comparison::Equal:
  1007. return MediaFeature::Comparison::Equal;
  1008. case MediaFeature::Comparison::LessThan:
  1009. return MediaFeature::Comparison::GreaterThan;
  1010. case MediaFeature::Comparison::LessThanOrEqual:
  1011. return MediaFeature::Comparison::GreaterThanOrEqual;
  1012. case MediaFeature::Comparison::GreaterThan:
  1013. return MediaFeature::Comparison::LessThan;
  1014. case MediaFeature::Comparison::GreaterThanOrEqual:
  1015. return MediaFeature::Comparison::LessThanOrEqual;
  1016. }
  1017. VERIFY_NOT_REACHED();
  1018. };
  1019. auto comparisons_match = [](MediaFeature::Comparison a, MediaFeature::Comparison b) -> bool {
  1020. switch (a) {
  1021. case MediaFeature::Comparison::Equal:
  1022. return b == MediaFeature::Comparison::Equal;
  1023. case MediaFeature::Comparison::LessThan:
  1024. case MediaFeature::Comparison::LessThanOrEqual:
  1025. return b == MediaFeature::Comparison::LessThan || b == MediaFeature::Comparison::LessThanOrEqual;
  1026. case MediaFeature::Comparison::GreaterThan:
  1027. case MediaFeature::Comparison::GreaterThanOrEqual:
  1028. return b == MediaFeature::Comparison::GreaterThan || b == MediaFeature::Comparison::GreaterThanOrEqual;
  1029. }
  1030. VERIFY_NOT_REACHED();
  1031. };
  1032. // `<mf-range> = <mf-name> <mf-comparison> <mf-value>
  1033. // | <mf-value> <mf-comparison> <mf-name>
  1034. // | <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>
  1035. // | <mf-value> <mf-gt> <mf-name> <mf-gt> <mf-value>`
  1036. auto parse_mf_range = [&](auto& tokens) -> Optional<MediaFeature> {
  1037. auto transaction = tokens.begin_transaction();
  1038. tokens.skip_whitespace();
  1039. // `<mf-name> <mf-comparison> <mf-value>`
  1040. // NOTE: We have to check for <mf-name> first, since all <mf-name>s will also parse as <mf-value>.
  1041. if (auto maybe_name = parse_mf_name(tokens, false); maybe_name.has_value() && media_feature_type_is_range(maybe_name->id)) {
  1042. tokens.skip_whitespace();
  1043. if (auto maybe_comparison = parse_comparison(tokens); maybe_comparison.has_value()) {
  1044. tokens.skip_whitespace();
  1045. if (auto maybe_value = parse_media_feature_value(maybe_name->id, tokens); maybe_value.has_value()) {
  1046. tokens.skip_whitespace();
  1047. if (!tokens.has_next_token() && !maybe_value->is_ident()) {
  1048. transaction.commit();
  1049. return MediaFeature::half_range(maybe_value.release_value(), flip(maybe_comparison.release_value()), maybe_name->id);
  1050. }
  1051. }
  1052. }
  1053. }
  1054. // `<mf-value> <mf-comparison> <mf-name>
  1055. // | <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>
  1056. // | <mf-value> <mf-gt> <mf-name> <mf-gt> <mf-value>`
  1057. // NOTE: To parse the first value, we need to first find and parse the <mf-name> so we know what value types to parse.
  1058. // To allow for <mf-value> to be any number of tokens long, we scan forward until we find a comparison, and then
  1059. // treat the next non-whitespace token as the <mf-name>, which should be correct as long as they don't add a value
  1060. // type that can include a comparison in it. :^)
  1061. Optional<MediaFeatureName> maybe_name;
  1062. {
  1063. // This transaction is never committed, we just use it to rewind automatically.
  1064. auto temp_transaction = tokens.begin_transaction();
  1065. while (tokens.has_next_token() && !maybe_name.has_value()) {
  1066. if (auto maybe_comparison = parse_comparison(tokens); maybe_comparison.has_value()) {
  1067. // We found a comparison, so the next non-whitespace token should be the <mf-name>
  1068. tokens.skip_whitespace();
  1069. maybe_name = parse_mf_name(tokens, false);
  1070. break;
  1071. }
  1072. tokens.next_token();
  1073. tokens.skip_whitespace();
  1074. }
  1075. }
  1076. // Now, we can parse the range properly.
  1077. if (maybe_name.has_value() && media_feature_type_is_range(maybe_name->id)) {
  1078. if (auto maybe_left_value = parse_media_feature_value(maybe_name->id, tokens); maybe_left_value.has_value()) {
  1079. tokens.skip_whitespace();
  1080. if (auto maybe_left_comparison = parse_comparison(tokens); maybe_left_comparison.has_value()) {
  1081. tokens.skip_whitespace();
  1082. tokens.next_token(); // The <mf-name> which we already parsed above.
  1083. tokens.skip_whitespace();
  1084. if (!tokens.has_next_token()) {
  1085. transaction.commit();
  1086. return MediaFeature::half_range(maybe_left_value.release_value(), maybe_left_comparison.release_value(), maybe_name->id);
  1087. }
  1088. if (auto maybe_right_comparison = parse_comparison(tokens); maybe_right_comparison.has_value()) {
  1089. tokens.skip_whitespace();
  1090. if (auto maybe_right_value = parse_media_feature_value(maybe_name->id, tokens); maybe_right_value.has_value()) {
  1091. tokens.skip_whitespace();
  1092. // For this to be valid, the following must be true:
  1093. // - Comparisons must either both be >/>= or both be </<=.
  1094. // - Neither comparison can be `=`.
  1095. // - Neither value can be an ident.
  1096. auto left_comparison = maybe_left_comparison.release_value();
  1097. auto right_comparison = maybe_right_comparison.release_value();
  1098. if (!tokens.has_next_token()
  1099. && comparisons_match(left_comparison, right_comparison)
  1100. && left_comparison != MediaFeature::Comparison::Equal
  1101. && !maybe_left_value->is_ident() && !maybe_right_value->is_ident()) {
  1102. transaction.commit();
  1103. return MediaFeature::range(maybe_left_value.release_value(), left_comparison, maybe_name->id, right_comparison, maybe_right_value.release_value());
  1104. }
  1105. }
  1106. }
  1107. }
  1108. }
  1109. }
  1110. return {};
  1111. };
  1112. if (auto maybe_mf_boolean = parse_mf_boolean(tokens); maybe_mf_boolean.has_value())
  1113. return maybe_mf_boolean.release_value();
  1114. if (auto maybe_mf_plain = parse_mf_plain(tokens); maybe_mf_plain.has_value())
  1115. return maybe_mf_plain.release_value();
  1116. if (auto maybe_mf_range = parse_mf_range(tokens); maybe_mf_range.has_value())
  1117. return maybe_mf_range.release_value();
  1118. return {};
  1119. }
  1120. Optional<MediaQuery::MediaType> Parser::parse_media_type(TokenStream<ComponentValue>& tokens)
  1121. {
  1122. auto transaction = tokens.begin_transaction();
  1123. tokens.skip_whitespace();
  1124. auto const& token = tokens.next_token();
  1125. if (!token.is(Token::Type::Ident))
  1126. return {};
  1127. transaction.commit();
  1128. auto ident = token.token().ident();
  1129. return media_type_from_string(ident);
  1130. }
  1131. // `<media-in-parens>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-in-parens
  1132. OwnPtr<MediaCondition> Parser::parse_media_in_parens(TokenStream<ComponentValue>& tokens)
  1133. {
  1134. // `<media-in-parens> = ( <media-condition> ) | ( <media-feature> ) | <general-enclosed>`
  1135. auto transaction = tokens.begin_transaction();
  1136. tokens.skip_whitespace();
  1137. // `( <media-condition> ) | ( <media-feature> )`
  1138. auto const& first_token = tokens.peek_token();
  1139. if (first_token.is_block() && first_token.block().is_paren()) {
  1140. TokenStream inner_token_stream { first_token.block().values() };
  1141. if (auto maybe_media_condition = parse_media_condition(inner_token_stream, MediaCondition::AllowOr::Yes)) {
  1142. tokens.next_token();
  1143. transaction.commit();
  1144. return maybe_media_condition.release_nonnull();
  1145. }
  1146. if (auto maybe_media_feature = parse_media_feature(inner_token_stream); maybe_media_feature.has_value()) {
  1147. tokens.next_token();
  1148. transaction.commit();
  1149. return MediaCondition::from_feature(maybe_media_feature.release_value());
  1150. }
  1151. }
  1152. // `<general-enclosed>`
  1153. // FIXME: We should only be taking this branch if the grammar doesn't match the above options.
  1154. // Currently we take it if the above fail to parse, which is different.
  1155. // eg, `@media (min-width: 76yaks)` is valid grammar, but does not parse because `yaks` isn't a unit.
  1156. if (auto maybe_general_enclosed = parse_general_enclosed(tokens); maybe_general_enclosed.has_value()) {
  1157. transaction.commit();
  1158. return MediaCondition::from_general_enclosed(maybe_general_enclosed.release_value());
  1159. }
  1160. return {};
  1161. }
  1162. // `<mf-value>`, https://www.w3.org/TR/mediaqueries-4/#typedef-mf-value
  1163. Optional<MediaFeatureValue> Parser::parse_media_feature_value(MediaFeatureID media_feature, TokenStream<ComponentValue>& tokens)
  1164. {
  1165. // Identifiers
  1166. if (tokens.peek_token().is(Token::Type::Ident)) {
  1167. auto transaction = tokens.begin_transaction();
  1168. tokens.skip_whitespace();
  1169. auto ident = value_id_from_string(tokens.next_token().token().ident());
  1170. if (ident.has_value() && media_feature_accepts_identifier(media_feature, ident.value())) {
  1171. transaction.commit();
  1172. return MediaFeatureValue(ident.value());
  1173. }
  1174. }
  1175. // One branch for each member of the MediaFeatureValueType enum:
  1176. // Boolean (<mq-boolean> in the spec: a 1 or 0)
  1177. if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Boolean)) {
  1178. auto transaction = tokens.begin_transaction();
  1179. tokens.skip_whitespace();
  1180. auto const& first = tokens.next_token();
  1181. if (first.is(Token::Type::Number) && first.token().number().is_integer()
  1182. && (first.token().number_value() == 0 || first.token().number_value() == 1)) {
  1183. transaction.commit();
  1184. return MediaFeatureValue(first.token().number_value());
  1185. }
  1186. }
  1187. // Integer
  1188. if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Integer)) {
  1189. auto transaction = tokens.begin_transaction();
  1190. tokens.skip_whitespace();
  1191. auto const& first = tokens.next_token();
  1192. if (first.is(Token::Type::Number) && first.token().number().is_integer()) {
  1193. transaction.commit();
  1194. return MediaFeatureValue(first.token().number_value());
  1195. }
  1196. }
  1197. // Length
  1198. if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Length)) {
  1199. auto transaction = tokens.begin_transaction();
  1200. tokens.skip_whitespace();
  1201. auto const& first = tokens.next_token();
  1202. if (auto length = parse_length(first); length.has_value()) {
  1203. transaction.commit();
  1204. return MediaFeatureValue(length.release_value());
  1205. }
  1206. }
  1207. // Ratio
  1208. if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Ratio)) {
  1209. auto transaction = tokens.begin_transaction();
  1210. tokens.skip_whitespace();
  1211. if (auto ratio = parse_ratio(tokens); ratio.has_value()) {
  1212. transaction.commit();
  1213. return MediaFeatureValue(ratio.release_value());
  1214. }
  1215. }
  1216. // Resolution
  1217. if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Resolution)) {
  1218. auto transaction = tokens.begin_transaction();
  1219. tokens.skip_whitespace();
  1220. auto const& first = tokens.next_token();
  1221. if (auto resolution = parse_dimension(first); resolution.has_value() && resolution->is_resolution()) {
  1222. transaction.commit();
  1223. return MediaFeatureValue(resolution->resolution());
  1224. }
  1225. }
  1226. return {};
  1227. }
  1228. RefPtr<Supports> Parser::parse_as_supports()
  1229. {
  1230. return parse_a_supports(m_token_stream);
  1231. }
  1232. template<typename T>
  1233. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  1234. {
  1235. auto component_values = parse_a_list_of_component_values(tokens);
  1236. TokenStream<ComponentValue> token_stream { component_values };
  1237. auto maybe_condition = parse_supports_condition(token_stream);
  1238. token_stream.skip_whitespace();
  1239. if (maybe_condition && !token_stream.has_next_token())
  1240. return Supports::create(maybe_condition.release_nonnull());
  1241. return {};
  1242. }
  1243. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<ComponentValue>& tokens)
  1244. {
  1245. auto transaction = tokens.begin_transaction();
  1246. tokens.skip_whitespace();
  1247. auto const& peeked_token = tokens.peek_token();
  1248. // `not <supports-in-parens>`
  1249. if (peeked_token.is(Token::Type::Ident) && peeked_token.token().ident().equals_ignoring_ascii_case("not"sv)) {
  1250. tokens.next_token();
  1251. tokens.skip_whitespace();
  1252. auto child = parse_supports_in_parens(tokens);
  1253. if (!child.has_value())
  1254. return {};
  1255. transaction.commit();
  1256. auto condition = make<Supports::Condition>();
  1257. condition->type = Supports::Condition::Type::Not;
  1258. condition->children.append(child.release_value());
  1259. return condition;
  1260. }
  1261. // ` <supports-in-parens> [ and <supports-in-parens> ]*
  1262. // | <supports-in-parens> [ or <supports-in-parens> ]*`
  1263. Vector<Supports::InParens> children;
  1264. Optional<Supports::Condition::Type> condition_type {};
  1265. auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
  1266. if (!token.is(Token::Type::Ident))
  1267. return {};
  1268. auto ident = token.token().ident();
  1269. if (ident.equals_ignoring_ascii_case("and"sv))
  1270. return Supports::Condition::Type::And;
  1271. if (ident.equals_ignoring_ascii_case("or"sv))
  1272. return Supports::Condition::Type::Or;
  1273. return {};
  1274. };
  1275. while (tokens.has_next_token()) {
  1276. if (!children.is_empty()) {
  1277. // Expect `and` or `or` here
  1278. auto maybe_combination = as_condition_type(tokens.next_token());
  1279. if (!maybe_combination.has_value())
  1280. return {};
  1281. if (!condition_type.has_value()) {
  1282. condition_type = maybe_combination.value();
  1283. } else if (maybe_combination != condition_type) {
  1284. return {};
  1285. }
  1286. }
  1287. tokens.skip_whitespace();
  1288. if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
  1289. children.append(in_parens.release_value());
  1290. } else {
  1291. return {};
  1292. }
  1293. tokens.skip_whitespace();
  1294. }
  1295. if (children.is_empty())
  1296. return {};
  1297. transaction.commit();
  1298. auto condition = make<Supports::Condition>();
  1299. condition->type = condition_type.value_or(Supports::Condition::Type::Or);
  1300. condition->children = move(children);
  1301. return condition;
  1302. }
  1303. Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<ComponentValue>& tokens)
  1304. {
  1305. // `( <supports-condition> )`
  1306. auto const& first_token = tokens.peek_token();
  1307. if (first_token.is_block() && first_token.block().is_paren()) {
  1308. auto transaction = tokens.begin_transaction();
  1309. tokens.next_token();
  1310. tokens.skip_whitespace();
  1311. TokenStream child_tokens { first_token.block().values() };
  1312. if (auto condition = parse_supports_condition(child_tokens)) {
  1313. if (child_tokens.has_next_token())
  1314. return {};
  1315. transaction.commit();
  1316. return Supports::InParens {
  1317. .value = { condition.release_nonnull() }
  1318. };
  1319. }
  1320. }
  1321. // `<supports-feature>`
  1322. if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
  1323. return Supports::InParens {
  1324. .value = { feature.release_value() }
  1325. };
  1326. }
  1327. // `<general-enclosed>`
  1328. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  1329. return Supports::InParens {
  1330. .value = general_enclosed.release_value()
  1331. };
  1332. }
  1333. return {};
  1334. }
  1335. Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<ComponentValue>& tokens)
  1336. {
  1337. auto transaction = tokens.begin_transaction();
  1338. tokens.skip_whitespace();
  1339. auto const& first_token = tokens.next_token();
  1340. // `<supports-decl>`
  1341. if (first_token.is_block() && first_token.block().is_paren()) {
  1342. TokenStream block_tokens { first_token.block().values() };
  1343. // FIXME: Parsing and then converting back to a string is weird.
  1344. if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
  1345. transaction.commit();
  1346. return Supports::Feature {
  1347. Supports::Declaration { declaration->to_string().release_value_but_fixme_should_propagate_errors(), JS::make_handle(m_context.realm()) }
  1348. };
  1349. }
  1350. }
  1351. // `<supports-selector-fn>`
  1352. if (first_token.is_function() && first_token.function().name().equals_ignoring_ascii_case("selector"sv)) {
  1353. // FIXME: Parsing and then converting back to a string is weird.
  1354. StringBuilder builder;
  1355. for (auto const& item : first_token.function().values())
  1356. builder.append(item.to_string().release_value_but_fixme_should_propagate_errors());
  1357. transaction.commit();
  1358. return Supports::Feature {
  1359. Supports::Selector { builder.to_string().release_value_but_fixme_should_propagate_errors(), JS::make_handle(m_context.realm()) }
  1360. };
  1361. }
  1362. return {};
  1363. }
  1364. // https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
  1365. Optional<GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<ComponentValue>& tokens)
  1366. {
  1367. auto transaction = tokens.begin_transaction();
  1368. tokens.skip_whitespace();
  1369. auto const& first_token = tokens.next_token();
  1370. // `[ <function-token> <any-value>? ) ]`
  1371. if (first_token.is_function()) {
  1372. transaction.commit();
  1373. return GeneralEnclosed { first_token.to_string().release_value_but_fixme_should_propagate_errors() };
  1374. }
  1375. // `( <any-value>? )`
  1376. if (first_token.is_block() && first_token.block().is_paren()) {
  1377. transaction.commit();
  1378. return GeneralEnclosed { first_token.to_string().release_value_but_fixme_should_propagate_errors() };
  1379. }
  1380. return {};
  1381. }
  1382. // 5.4.1. Consume a list of rules
  1383. // https://www.w3.org/TR/css-syntax-3/#consume-list-of-rules
  1384. template<typename T>
  1385. Vector<NonnullRefPtr<Rule>> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, TopLevel top_level)
  1386. {
  1387. // To consume a list of rules, given a top-level flag:
  1388. // Create an initially empty list of rules.
  1389. Vector<NonnullRefPtr<Rule>> rules;
  1390. // Repeatedly consume the next input token:
  1391. for (;;) {
  1392. auto& token = tokens.next_token();
  1393. // <whitespace-token>
  1394. if (token.is(Token::Type::Whitespace)) {
  1395. // Do nothing.
  1396. continue;
  1397. }
  1398. // <EOF-token>
  1399. if (token.is(Token::Type::EndOfFile)) {
  1400. // Return the list of rules.
  1401. return rules;
  1402. }
  1403. // <CDO-token>
  1404. // <CDC-token>
  1405. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  1406. // If the top-level flag is set, do nothing.
  1407. if (top_level == TopLevel::Yes)
  1408. continue;
  1409. // Otherwise, reconsume the current input token.
  1410. tokens.reconsume_current_input_token();
  1411. // Consume a qualified rule. If anything is returned, append it to the list of rules.
  1412. if (auto maybe_qualified = consume_a_qualified_rule(tokens))
  1413. rules.append(maybe_qualified.release_nonnull());
  1414. continue;
  1415. }
  1416. // <at-keyword-token>
  1417. if (token.is(Token::Type::AtKeyword)) {
  1418. // Reconsume the current input token.
  1419. tokens.reconsume_current_input_token();
  1420. // Consume an at-rule, and append the returned value to the list of rules.
  1421. rules.append(consume_an_at_rule(tokens));
  1422. continue;
  1423. }
  1424. // anything else
  1425. {
  1426. // Reconsume the current input token.
  1427. tokens.reconsume_current_input_token();
  1428. // Consume a qualified rule. If anything is returned, append it to the list of rules.
  1429. if (auto maybe_qualified = consume_a_qualified_rule(tokens))
  1430. rules.append(maybe_qualified.release_nonnull());
  1431. continue;
  1432. }
  1433. }
  1434. }
  1435. // 5.4.2. Consume an at-rule
  1436. // https://www.w3.org/TR/css-syntax-3/#consume-at-rule
  1437. template<typename T>
  1438. NonnullRefPtr<Rule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  1439. {
  1440. // To consume an at-rule:
  1441. // Consume the next input token.
  1442. auto& name_ident = tokens.next_token();
  1443. VERIFY(name_ident.is(Token::Type::AtKeyword));
  1444. // Create a new at-rule with its name set to the value of the current input token, its prelude initially set to an empty list, and its value initially set to nothing.
  1445. // NOTE: We create the Rule fully initialized when we return it instead.
  1446. auto at_rule_name = FlyString::from_utf8(((Token)name_ident).at_keyword()).release_value_but_fixme_should_propagate_errors();
  1447. Vector<ComponentValue> prelude;
  1448. RefPtr<Block> block;
  1449. // Repeatedly consume the next input token:
  1450. for (;;) {
  1451. auto& token = tokens.next_token();
  1452. // <semicolon-token>
  1453. if (token.is(Token::Type::Semicolon)) {
  1454. // Return the at-rule.
  1455. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  1456. }
  1457. // <EOF-token>
  1458. if (token.is(Token::Type::EndOfFile)) {
  1459. // This is a parse error. Return the at-rule.
  1460. log_parse_error();
  1461. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  1462. }
  1463. // <{-token>
  1464. if (token.is(Token::Type::OpenCurly)) {
  1465. // Consume a simple block and assign it to the at-rule’s block. Return the at-rule.
  1466. block = consume_a_simple_block(tokens);
  1467. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  1468. }
  1469. // simple block with an associated token of <{-token>
  1470. if constexpr (IsSame<T, ComponentValue>) {
  1471. ComponentValue const& component_value = token;
  1472. if (component_value.is_block() && component_value.block().is_curly()) {
  1473. // Assign the block to the at-rule’s block. Return the at-rule.
  1474. block = component_value.block();
  1475. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  1476. }
  1477. }
  1478. // anything else
  1479. {
  1480. // Reconsume the current input token.
  1481. tokens.reconsume_current_input_token();
  1482. // Consume a component value. Append the returned value to the at-rule’s prelude.
  1483. prelude.append(consume_a_component_value(tokens));
  1484. }
  1485. }
  1486. }
  1487. // 5.4.3. Consume a qualified rule
  1488. // https://www.w3.org/TR/css-syntax-3/#consume-qualified-rule
  1489. template<typename T>
  1490. RefPtr<Rule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  1491. {
  1492. // To consume a qualified rule:
  1493. // Create a new qualified rule with its prelude initially set to an empty list, and its value initially set to nothing.
  1494. // NOTE: We create the Rule fully initialized when we return it instead.
  1495. Vector<ComponentValue> prelude;
  1496. RefPtr<Block> block;
  1497. // Repeatedly consume the next input token:
  1498. for (;;) {
  1499. auto& token = tokens.next_token();
  1500. // <EOF-token>
  1501. if (token.is(Token::Type::EndOfFile)) {
  1502. // This is a parse error. Return nothing.
  1503. log_parse_error();
  1504. return {};
  1505. }
  1506. // <{-token>
  1507. if (token.is(Token::Type::OpenCurly)) {
  1508. // Consume a simple block and assign it to the qualified rule’s block. Return the qualified rule.
  1509. block = consume_a_simple_block(tokens);
  1510. return Rule::make_qualified_rule(move(prelude), move(block));
  1511. }
  1512. // simple block with an associated token of <{-token>
  1513. if constexpr (IsSame<T, ComponentValue>) {
  1514. ComponentValue const& component_value = token;
  1515. if (component_value.is_block() && component_value.block().is_curly()) {
  1516. // Assign the block to the qualified rule’s block. Return the qualified rule.
  1517. block = component_value.block();
  1518. return Rule::make_qualified_rule(move(prelude), move(block));
  1519. }
  1520. }
  1521. // anything else
  1522. {
  1523. // Reconsume the current input token.
  1524. tokens.reconsume_current_input_token();
  1525. // Consume a component value. Append the returned value to the qualified rule’s prelude.
  1526. prelude.append(consume_a_component_value(tokens));
  1527. }
  1528. }
  1529. }
  1530. // 5.4.4. Consume a style block’s contents
  1531. // https://www.w3.org/TR/css-syntax-3/#consume-a-style-blocks-contents
  1532. template<typename T>
  1533. Vector<DeclarationOrAtRule> Parser::consume_a_style_blocks_contents(TokenStream<T>& tokens)
  1534. {
  1535. // To consume a style block’s contents:
  1536. // Create an initially empty list of declarations decls, and an initially empty list of rules rules.
  1537. Vector<DeclarationOrAtRule> declarations;
  1538. Vector<DeclarationOrAtRule> rules;
  1539. // Repeatedly consume the next input token:
  1540. for (;;) {
  1541. auto& token = tokens.next_token();
  1542. // <whitespace-token>
  1543. // <semicolon-token>
  1544. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  1545. // Do nothing.
  1546. continue;
  1547. }
  1548. // <EOF-token>
  1549. if (token.is(Token::Type::EndOfFile)) {
  1550. // Extend decls with rules, then return decls.
  1551. declarations.extend(move(rules));
  1552. return declarations;
  1553. }
  1554. // <at-keyword-token>
  1555. if (token.is(Token::Type::AtKeyword)) {
  1556. // Reconsume the current input token.
  1557. tokens.reconsume_current_input_token();
  1558. // Consume an at-rule, and append the result to rules.
  1559. rules.empend(consume_an_at_rule(tokens));
  1560. continue;
  1561. }
  1562. // <ident-token>
  1563. if (token.is(Token::Type::Ident)) {
  1564. // Initialize a temporary list initially filled with the current input token.
  1565. Vector<ComponentValue> temporary_list;
  1566. temporary_list.append(token);
  1567. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  1568. // consume a component value and append it to the temporary list.
  1569. for (;;) {
  1570. auto& next_input_token = tokens.peek_token();
  1571. if (next_input_token.is(Token::Type::Semicolon) || next_input_token.is(Token::Type::EndOfFile))
  1572. break;
  1573. temporary_list.append(consume_a_component_value(tokens));
  1574. }
  1575. // Consume a declaration from the temporary list. If anything was returned, append it to decls.
  1576. auto token_stream = TokenStream(temporary_list);
  1577. if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
  1578. declarations.empend(maybe_declaration.release_value());
  1579. continue;
  1580. }
  1581. // <delim-token> with a value of "&" (U+0026 AMPERSAND)
  1582. if (token.is_delim('&')) {
  1583. // Reconsume the current input token.
  1584. tokens.reconsume_current_input_token();
  1585. // Consume a qualified rule. If anything was returned, append it to rules.
  1586. if (auto qualified_rule = consume_a_qualified_rule(tokens))
  1587. rules.empend(qualified_rule);
  1588. continue;
  1589. }
  1590. // anything else
  1591. {
  1592. // This is a parse error.
  1593. log_parse_error();
  1594. // Reconsume the current input token.
  1595. tokens.reconsume_current_input_token();
  1596. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  1597. // consume a component value and throw away the returned value.
  1598. for (;;) {
  1599. auto& peek = tokens.peek_token();
  1600. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  1601. break;
  1602. (void)consume_a_component_value(tokens);
  1603. }
  1604. }
  1605. }
  1606. }
  1607. template<>
  1608. ComponentValue Parser::consume_a_component_value(TokenStream<ComponentValue>& tokens)
  1609. {
  1610. // Note: This overload is called once tokens have already been converted into component values,
  1611. // so we do not need to do the work in the more general overload.
  1612. return tokens.next_token();
  1613. }
  1614. // 5.4.7. Consume a component value
  1615. // https://www.w3.org/TR/css-syntax-3/#consume-component-value
  1616. template<typename T>
  1617. ComponentValue Parser::consume_a_component_value(TokenStream<T>& tokens)
  1618. {
  1619. // To consume a component value:
  1620. // Consume the next input token.
  1621. auto& token = tokens.next_token();
  1622. // If the current input token is a <{-token>, <[-token>, or <(-token>, consume a simple block and return it.
  1623. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  1624. return ComponentValue(consume_a_simple_block(tokens));
  1625. // Otherwise, if the current input token is a <function-token>, consume a function and return it.
  1626. if (token.is(Token::Type::Function))
  1627. return ComponentValue(consume_a_function(tokens));
  1628. // Otherwise, return the current input token.
  1629. return ComponentValue(token);
  1630. }
  1631. // 5.4.8. Consume a simple block
  1632. // https://www.w3.org/TR/css-syntax-3/#consume-simple-block
  1633. template<typename T>
  1634. NonnullRefPtr<Block> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  1635. {
  1636. // Note: This algorithm assumes that the current input token has already been checked
  1637. // to be an <{-token>, <[-token>, or <(-token>.
  1638. // To consume a simple block:
  1639. // The ending token is the mirror variant of the current input token.
  1640. // (E.g. if it was called with <[-token>, the ending token is <]-token>.)
  1641. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  1642. // Create a simple block with its associated token set to the current input token
  1643. // and with its value initially set to an empty list.
  1644. // NOTE: We create the Block fully initialized when we return it instead.
  1645. Token block_token = tokens.current_token();
  1646. Vector<ComponentValue> block_values;
  1647. // Repeatedly consume the next input token and process it as follows:
  1648. for (;;) {
  1649. auto& token = tokens.next_token();
  1650. // ending token
  1651. if (token.is(ending_token)) {
  1652. // Return the block.
  1653. return Block::create(move(block_token), move(block_values));
  1654. }
  1655. // <EOF-token>
  1656. if (token.is(Token::Type::EndOfFile)) {
  1657. // This is a parse error. Return the block.
  1658. log_parse_error();
  1659. return Block::create(move(block_token), move(block_values));
  1660. }
  1661. // anything else
  1662. {
  1663. // Reconsume the current input token.
  1664. tokens.reconsume_current_input_token();
  1665. // Consume a component value and append it to the value of the block.
  1666. block_values.empend(consume_a_component_value(tokens));
  1667. }
  1668. }
  1669. }
  1670. // 5.4.9. Consume a function
  1671. // https://www.w3.org/TR/css-syntax-3/#consume-function
  1672. template<typename T>
  1673. NonnullRefPtr<Function> Parser::consume_a_function(TokenStream<T>& tokens)
  1674. {
  1675. // Note: This algorithm assumes that the current input token has already been checked to be a <function-token>.
  1676. auto name_ident = tokens.current_token();
  1677. VERIFY(name_ident.is(Token::Type::Function));
  1678. // To consume a function:
  1679. // Create a function with its name equal to the value of the current input token
  1680. // and with its value initially set to an empty list.
  1681. // NOTE: We create the Function fully initialized when we return it instead.
  1682. auto function_name = FlyString::from_utf8(((Token)name_ident).function()).release_value_but_fixme_should_propagate_errors();
  1683. Vector<ComponentValue> function_values;
  1684. // Repeatedly consume the next input token and process it as follows:
  1685. for (;;) {
  1686. auto& token = tokens.next_token();
  1687. // <)-token>
  1688. if (token.is(Token::Type::CloseParen)) {
  1689. // Return the function.
  1690. return Function::create(move(function_name), move(function_values));
  1691. }
  1692. // <EOF-token>
  1693. if (token.is(Token::Type::EndOfFile)) {
  1694. // This is a parse error. Return the function.
  1695. log_parse_error();
  1696. return Function::create(move(function_name), move(function_values));
  1697. }
  1698. // anything else
  1699. {
  1700. // Reconsume the current input token.
  1701. tokens.reconsume_current_input_token();
  1702. // Consume a component value and append the returned value to the function’s value.
  1703. function_values.append(consume_a_component_value(tokens));
  1704. }
  1705. }
  1706. }
  1707. // 5.4.6. Consume a declaration
  1708. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  1709. template<typename T>
  1710. Optional<Declaration> Parser::consume_a_declaration(TokenStream<T>& tokens)
  1711. {
  1712. // Note: This algorithm assumes that the next input token has already been checked to
  1713. // be an <ident-token>.
  1714. // NOTE: This is not true in our implementation! For convenience, we both skip whitespace
  1715. // and gracefully handle the first token not being an <ident-token>.
  1716. // To consume a declaration:
  1717. // Consume the next input token.
  1718. auto transaction = tokens.begin_transaction();
  1719. tokens.skip_whitespace();
  1720. auto& token = tokens.next_token();
  1721. // NOTE: Not to spec, handle the case where the input token *isn't* an <ident-token>.
  1722. if (!token.is(Token::Type::Ident))
  1723. return {};
  1724. // Create a new declaration with its name set to the value of the current input token
  1725. // and its value initially set to the empty list.
  1726. // NOTE: We create a fully-initialized Declaration just before returning it instead.
  1727. auto declaration_name = FlyString::from_utf8(((Token)token).ident()).release_value_but_fixme_should_propagate_errors();
  1728. Vector<ComponentValue> declaration_values;
  1729. Important declaration_important = Important::No;
  1730. // 1. While the next input token is a <whitespace-token>, consume the next input token.
  1731. tokens.skip_whitespace();
  1732. // 2. If the next input token is anything other than a <colon-token>, this is a parse error.
  1733. // Return nothing.
  1734. auto& maybe_colon = tokens.peek_token();
  1735. if (!maybe_colon.is(Token::Type::Colon)) {
  1736. log_parse_error();
  1737. return {};
  1738. }
  1739. // Otherwise, consume the next input token.
  1740. tokens.next_token();
  1741. // 3. While the next input token is a <whitespace-token>, consume the next input token.
  1742. tokens.skip_whitespace();
  1743. // 4. As long as the next input token is anything other than an <EOF-token>, consume a
  1744. // component value and append it to the declaration’s value.
  1745. for (;;) {
  1746. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1747. break;
  1748. }
  1749. declaration_values.append(consume_a_component_value(tokens));
  1750. }
  1751. // 5. If the last two non-<whitespace-token>s in the declaration’s value are a <delim-token>
  1752. // with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive
  1753. // match for "important", remove them from the declaration’s value and set the declaration’s
  1754. // important flag to true.
  1755. if (declaration_values.size() >= 2) {
  1756. // Walk backwards from the end until we find "important"
  1757. Optional<size_t> important_index;
  1758. for (size_t i = declaration_values.size() - 1; i > 0; i--) {
  1759. auto value = declaration_values[i];
  1760. if (value.is(Token::Type::Ident) && Infra::is_ascii_case_insensitive_match(value.token().ident(), "important"sv)) {
  1761. important_index = i;
  1762. break;
  1763. }
  1764. if (value.is(Token::Type::Whitespace))
  1765. continue;
  1766. break;
  1767. }
  1768. // Walk backwards from important until we find "!"
  1769. if (important_index.has_value()) {
  1770. Optional<size_t> bang_index;
  1771. for (size_t i = important_index.value() - 1; i > 0; i--) {
  1772. auto value = declaration_values[i];
  1773. if (value.is_delim('!')) {
  1774. bang_index = i;
  1775. break;
  1776. }
  1777. if (value.is(Token::Type::Whitespace))
  1778. continue;
  1779. break;
  1780. }
  1781. if (bang_index.has_value()) {
  1782. declaration_values.remove(important_index.value());
  1783. declaration_values.remove(bang_index.value());
  1784. declaration_important = Important::Yes;
  1785. }
  1786. }
  1787. }
  1788. // 6. While the last token in the declaration’s value is a <whitespace-token>, remove that token.
  1789. while (!declaration_values.is_empty()) {
  1790. auto maybe_whitespace = declaration_values.last();
  1791. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  1792. break;
  1793. }
  1794. declaration_values.take_last();
  1795. }
  1796. // 7. Return the declaration.
  1797. transaction.commit();
  1798. return Declaration { move(declaration_name), move(declaration_values), declaration_important };
  1799. }
  1800. // 5.4.5. Consume a list of declarations
  1801. // https://www.w3.org/TR/css-syntax-3/#consume-list-of-declarations
  1802. template<typename T>
  1803. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  1804. {
  1805. // To consume a list of declarations:
  1806. // Create an initially empty list of declarations.
  1807. Vector<DeclarationOrAtRule> list_of_declarations;
  1808. // Repeatedly consume the next input token:
  1809. for (;;) {
  1810. auto& token = tokens.next_token();
  1811. // <whitespace-token>
  1812. // <semicolon-token>
  1813. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  1814. // Do nothing.
  1815. continue;
  1816. }
  1817. // <EOF-token>
  1818. if (token.is(Token::Type::EndOfFile)) {
  1819. // Return the list of declarations.
  1820. return list_of_declarations;
  1821. }
  1822. // <at-keyword-token>
  1823. if (token.is(Token::Type::AtKeyword)) {
  1824. // Reconsume the current input token.
  1825. tokens.reconsume_current_input_token();
  1826. // Consume an at-rule. Append the returned rule to the list of declarations.
  1827. list_of_declarations.empend(consume_an_at_rule(tokens));
  1828. continue;
  1829. }
  1830. // <ident-token>
  1831. if (token.is(Token::Type::Ident)) {
  1832. // Initialize a temporary list initially filled with the current input token.
  1833. Vector<ComponentValue> temporary_list;
  1834. temporary_list.append(token);
  1835. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  1836. // consume a component value and append it to the temporary list.
  1837. for (;;) {
  1838. auto& peek = tokens.peek_token();
  1839. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  1840. break;
  1841. temporary_list.append(consume_a_component_value(tokens));
  1842. }
  1843. // Consume a declaration from the temporary list. If anything was returned, append it to the list of declarations.
  1844. auto token_stream = TokenStream(temporary_list);
  1845. if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
  1846. list_of_declarations.empend(maybe_declaration.value());
  1847. continue;
  1848. }
  1849. // anything else
  1850. {
  1851. // This is a parse error.
  1852. log_parse_error();
  1853. // Reconsume the current input token.
  1854. tokens.reconsume_current_input_token();
  1855. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  1856. // consume a component value and throw away the returned value.
  1857. for (;;) {
  1858. auto& peek = tokens.peek_token();
  1859. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  1860. break;
  1861. dbgln_if(CSS_PARSER_DEBUG, "Discarding token: '{}'", peek.to_debug_string());
  1862. (void)consume_a_component_value(tokens);
  1863. }
  1864. }
  1865. }
  1866. }
  1867. CSSRule* Parser::parse_as_css_rule()
  1868. {
  1869. auto maybe_rule = parse_a_rule(m_token_stream);
  1870. if (maybe_rule)
  1871. return convert_to_rule(maybe_rule.release_nonnull());
  1872. return {};
  1873. }
  1874. // 5.3.5. Parse a rule
  1875. // https://www.w3.org/TR/css-syntax-3/#parse-rule
  1876. template<typename T>
  1877. RefPtr<Rule> Parser::parse_a_rule(TokenStream<T>& tokens)
  1878. {
  1879. // To parse a rule from input:
  1880. RefPtr<Rule> rule;
  1881. // 1. Normalize input, and set input to the result.
  1882. // Note: This is done when initializing the Parser.
  1883. // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  1884. tokens.skip_whitespace();
  1885. // 3. If the next input token from input is an <EOF-token>, return a syntax error.
  1886. auto& token = tokens.peek_token();
  1887. if (token.is(Token::Type::EndOfFile)) {
  1888. return {};
  1889. }
  1890. // Otherwise, if the next input token from input is an <at-keyword-token>, consume an at-rule from input, and let rule be the return value.
  1891. else if (token.is(Token::Type::AtKeyword)) {
  1892. rule = consume_an_at_rule(m_token_stream);
  1893. }
  1894. // Otherwise, consume a qualified rule from input and let rule be the return value. If nothing was returned, return a syntax error.
  1895. else {
  1896. auto qualified_rule = consume_a_qualified_rule(tokens);
  1897. if (!qualified_rule)
  1898. return {};
  1899. rule = qualified_rule;
  1900. }
  1901. // 4. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  1902. tokens.skip_whitespace();
  1903. // 5. If the next input token from input is an <EOF-token>, return rule. Otherwise, return a syntax error.
  1904. if (tokens.peek_token().is(Token::Type::EndOfFile))
  1905. return rule;
  1906. return {};
  1907. }
  1908. // 5.3.4. Parse a list of rules
  1909. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-rules
  1910. template<typename T>
  1911. Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  1912. {
  1913. // To parse a list of rules from input:
  1914. // 1. Normalize input, and set input to the result.
  1915. // Note: This is done when initializing the Parser.
  1916. // 2. Consume a list of rules from the input, with the top-level flag unset.
  1917. auto list_of_rules = consume_a_list_of_rules(tokens, TopLevel::No);
  1918. // 3. Return the returned list.
  1919. return list_of_rules;
  1920. }
  1921. Optional<StyleProperty> Parser::parse_as_supports_condition()
  1922. {
  1923. auto maybe_declaration = parse_a_declaration(m_token_stream);
  1924. if (maybe_declaration.has_value())
  1925. return convert_to_style_property(maybe_declaration.release_value());
  1926. return {};
  1927. }
  1928. // 5.3.6. Parse a declaration
  1929. // https://www.w3.org/TR/css-syntax-3/#parse-a-declaration
  1930. template<typename T>
  1931. Optional<Declaration> Parser::parse_a_declaration(TokenStream<T>& tokens)
  1932. {
  1933. // To parse a declaration from input:
  1934. // 1. Normalize input, and set input to the result.
  1935. // Note: This is done when initializing the Parser.
  1936. // 2. While the next input token from input is a <whitespace-token>, consume the next input token.
  1937. tokens.skip_whitespace();
  1938. // 3. If the next input token from input is not an <ident-token>, return a syntax error.
  1939. auto& token = tokens.peek_token();
  1940. if (!token.is(Token::Type::Ident)) {
  1941. return {};
  1942. }
  1943. // 4. Consume a declaration from input. If anything was returned, return it. Otherwise, return a syntax error.
  1944. if (auto declaration = consume_a_declaration(tokens); declaration.has_value())
  1945. return declaration.release_value();
  1946. return {};
  1947. }
  1948. // 5.3.7. Parse a style block’s contents
  1949. // https://www.w3.org/TR/css-syntax-3/#parse-style-blocks-contents
  1950. template<typename T>
  1951. Vector<DeclarationOrAtRule> Parser::parse_a_style_blocks_contents(TokenStream<T>& tokens)
  1952. {
  1953. // To parse a style block’s contents from input:
  1954. // 1. Normalize input, and set input to the result.
  1955. // Note: This is done when initializing the Parser.
  1956. // 2. Consume a style block’s contents from input, and return the result.
  1957. return consume_a_style_blocks_contents(tokens);
  1958. }
  1959. // 5.3.8. Parse a list of declarations
  1960. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-declarations
  1961. template<typename T>
  1962. Vector<DeclarationOrAtRule> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  1963. {
  1964. // To parse a list of declarations from input:
  1965. // 1. Normalize input, and set input to the result.
  1966. // Note: This is done when initializing the Parser.
  1967. // 2. Consume a list of declarations from input, and return the result.
  1968. return consume_a_list_of_declarations(tokens);
  1969. }
  1970. // 5.3.9. Parse a component value
  1971. // https://www.w3.org/TR/css-syntax-3/#parse-component-value
  1972. template<typename T>
  1973. Optional<ComponentValue> Parser::parse_a_component_value(TokenStream<T>& tokens)
  1974. {
  1975. // To parse a component value from input:
  1976. // 1. Normalize input, and set input to the result.
  1977. // Note: This is done when initializing the Parser.
  1978. // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  1979. tokens.skip_whitespace();
  1980. // 3. If the next input token from input is an <EOF-token>, return a syntax error.
  1981. if (tokens.peek_token().is(Token::Type::EndOfFile))
  1982. return {};
  1983. // 4. Consume a component value from input and let value be the return value.
  1984. auto value = consume_a_component_value(tokens);
  1985. // 5. While the next input token from input is a <whitespace-token>, consume the next input token.
  1986. tokens.skip_whitespace();
  1987. // 6. If the next input token from input is an <EOF-token>, return value. Otherwise, return a syntax error.
  1988. if (tokens.peek_token().is(Token::Type::EndOfFile))
  1989. return value;
  1990. return {};
  1991. }
  1992. // 5.3.10. Parse a list of component values
  1993. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-component-values
  1994. template<typename T>
  1995. Vector<ComponentValue> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  1996. {
  1997. // To parse a list of component values from input:
  1998. // 1. Normalize input, and set input to the result.
  1999. // Note: This is done when initializing the Parser.
  2000. // 2. Repeatedly consume a component value from input until an <EOF-token> is returned, appending the returned values (except the final <EOF-token>) into a list. Return the list.
  2001. Vector<ComponentValue> component_values;
  2002. for (;;) {
  2003. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  2004. break;
  2005. }
  2006. component_values.append(consume_a_component_value(tokens));
  2007. }
  2008. return component_values;
  2009. }
  2010. // 5.3.11. Parse a comma-separated list of component values
  2011. // https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
  2012. template<typename T>
  2013. Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  2014. {
  2015. // To parse a comma-separated list of component values from input:
  2016. // 1. Normalize input, and set input to the result.
  2017. // Note: This is done when initializing the Parser.
  2018. // 2. Let list of cvls be an initially empty list of component value lists.
  2019. Vector<Vector<ComponentValue>> list_of_component_value_lists;
  2020. // 3. Repeatedly consume a component value from input until an <EOF-token> or <comma-token> is returned,
  2021. // appending the returned values (except the final <EOF-token> or <comma-token>) into a list.
  2022. // Append the list to list of cvls.
  2023. // If it was a <comma-token> that was returned, repeat this step.
  2024. Vector<ComponentValue> current_list;
  2025. for (;;) {
  2026. auto component_value = consume_a_component_value(tokens);
  2027. if (component_value.is(Token::Type::EndOfFile)) {
  2028. list_of_component_value_lists.append(move(current_list));
  2029. break;
  2030. }
  2031. if (component_value.is(Token::Type::Comma)) {
  2032. list_of_component_value_lists.append(move(current_list));
  2033. current_list = {};
  2034. continue;
  2035. }
  2036. current_list.append(component_value);
  2037. }
  2038. // 4. Return list of cvls.
  2039. return list_of_component_value_lists;
  2040. }
  2041. template Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<ComponentValue>&);
  2042. ElementInlineCSSStyleDeclaration* Parser::parse_as_style_attribute(DOM::Element& element)
  2043. {
  2044. auto declarations_and_at_rules = parse_a_list_of_declarations(m_token_stream);
  2045. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  2046. return ElementInlineCSSStyleDeclaration::create(element, move(properties), move(custom_properties)).release_value_but_fixme_should_propagate_errors();
  2047. }
  2048. Optional<AK::URL> Parser::parse_url_function(ComponentValue const& component_value)
  2049. {
  2050. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  2051. auto convert_string_to_url = [&](StringView& url_string) -> Optional<AK::URL> {
  2052. auto url = m_context.complete_url(url_string);
  2053. if (url.is_valid())
  2054. return url;
  2055. return {};
  2056. };
  2057. if (component_value.is(Token::Type::Url)) {
  2058. auto url_string = component_value.token().url();
  2059. return convert_string_to_url(url_string);
  2060. }
  2061. if (component_value.is_function() && component_value.function().name().equals_ignoring_ascii_case("url"sv)) {
  2062. auto const& function_values = component_value.function().values();
  2063. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  2064. for (size_t i = 0; i < function_values.size(); ++i) {
  2065. auto const& value = function_values[i];
  2066. if (value.is(Token::Type::Whitespace))
  2067. continue;
  2068. if (value.is(Token::Type::String)) {
  2069. auto url_string = value.token().string();
  2070. return convert_string_to_url(url_string);
  2071. }
  2072. break;
  2073. }
  2074. }
  2075. return {};
  2076. }
  2077. ErrorOr<RefPtr<StyleValue>> Parser::parse_url_value(ComponentValue const& component_value)
  2078. {
  2079. auto url = parse_url_function(component_value);
  2080. if (!url.has_value())
  2081. return nullptr;
  2082. return URLStyleValue::create(*url);
  2083. }
  2084. template<typename TElement>
  2085. static Optional<Vector<TElement>> parse_color_stop_list(auto& tokens, auto is_position, auto get_position, auto parse_color, auto parse_dimension)
  2086. {
  2087. enum class ElementType {
  2088. Garbage,
  2089. ColorStop,
  2090. ColorHint
  2091. };
  2092. auto parse_color_stop_list_element = [&](TElement& element) -> ElementType {
  2093. tokens.skip_whitespace();
  2094. if (!tokens.has_next_token())
  2095. return ElementType::Garbage;
  2096. auto const& token = tokens.next_token();
  2097. Gfx::Color color;
  2098. Optional<typename TElement::PositionType> position;
  2099. Optional<typename TElement::PositionType> second_position;
  2100. auto dimension = parse_dimension(token);
  2101. if (dimension.has_value() && is_position(*dimension)) {
  2102. // [<T-percentage> <color>] or [<T-percentage>]
  2103. position = get_position(*dimension);
  2104. tokens.skip_whitespace();
  2105. // <T-percentage>
  2106. if (!tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma)) {
  2107. element.transition_hint = typename TElement::ColorHint { *position };
  2108. return ElementType::ColorHint;
  2109. }
  2110. // <T-percentage> <color>
  2111. auto maybe_color = parse_color(tokens.next_token());
  2112. if (!maybe_color.has_value())
  2113. return ElementType::Garbage;
  2114. color = *maybe_color;
  2115. } else {
  2116. // [<color> <T-percentage>?]
  2117. auto maybe_color = parse_color(token);
  2118. if (!maybe_color.has_value())
  2119. return ElementType::Garbage;
  2120. color = *maybe_color;
  2121. tokens.skip_whitespace();
  2122. // Allow up to [<color> <T-percentage> <T-percentage>] (double-position color stops)
  2123. // Note: Double-position color stops only appear to be valid in this order.
  2124. for (auto stop_position : Array { &position, &second_position }) {
  2125. if (tokens.has_next_token() && !tokens.peek_token().is(Token::Type::Comma)) {
  2126. auto token = tokens.next_token();
  2127. auto dimension = parse_dimension(token);
  2128. if (!dimension.has_value() || !is_position(*dimension))
  2129. return ElementType::Garbage;
  2130. *stop_position = get_position(*dimension);
  2131. tokens.skip_whitespace();
  2132. }
  2133. }
  2134. }
  2135. element.color_stop = typename TElement::ColorStop { color, position, second_position };
  2136. return ElementType::ColorStop;
  2137. };
  2138. TElement first_element {};
  2139. if (parse_color_stop_list_element(first_element) != ElementType::ColorStop)
  2140. return {};
  2141. if (!tokens.has_next_token())
  2142. return {};
  2143. Vector<TElement> color_stops { first_element };
  2144. while (tokens.has_next_token()) {
  2145. TElement list_element {};
  2146. tokens.skip_whitespace();
  2147. if (!tokens.next_token().is(Token::Type::Comma))
  2148. return {};
  2149. auto element_type = parse_color_stop_list_element(list_element);
  2150. if (element_type == ElementType::ColorHint) {
  2151. // <color-hint>, <color-stop>
  2152. tokens.skip_whitespace();
  2153. if (!tokens.next_token().is(Token::Type::Comma))
  2154. return {};
  2155. // Note: This fills in the color stop on the same list_element as the color hint (it does not overwrite it).
  2156. if (parse_color_stop_list_element(list_element) != ElementType::ColorStop)
  2157. return {};
  2158. } else if (element_type == ElementType::ColorStop) {
  2159. // <color-stop>
  2160. } else {
  2161. return {};
  2162. }
  2163. color_stops.append(list_element);
  2164. }
  2165. return color_stops;
  2166. }
  2167. Optional<Vector<LinearColorStopListElement>> Parser::parse_linear_color_stop_list(TokenStream<ComponentValue>& tokens)
  2168. {
  2169. // <color-stop-list> =
  2170. // <linear-color-stop> , [ <linear-color-hint>? , <linear-color-stop> ]#
  2171. return parse_color_stop_list<LinearColorStopListElement>(
  2172. tokens,
  2173. [](Dimension& dimension) { return dimension.is_length_percentage(); },
  2174. [](Dimension& dimension) { return dimension.length_percentage(); },
  2175. [&](auto& token) { return parse_color(token); },
  2176. [&](auto& token) { return parse_dimension(token); });
  2177. }
  2178. Optional<Vector<AngularColorStopListElement>> Parser::parse_angular_color_stop_list(TokenStream<ComponentValue>& tokens)
  2179. {
  2180. // <angular-color-stop-list> =
  2181. // <angular-color-stop> , [ <angular-color-hint>? , <angular-color-stop> ]#
  2182. return parse_color_stop_list<AngularColorStopListElement>(
  2183. tokens,
  2184. [](Dimension& dimension) { return dimension.is_angle_percentage(); },
  2185. [](Dimension& dimension) { return dimension.angle_percentage(); },
  2186. [&](auto& token) { return parse_color(token); },
  2187. [&](auto& token) { return parse_dimension(token); });
  2188. }
  2189. static StringView consume_if_starts_with(StringView str, StringView start, auto found_callback)
  2190. {
  2191. if (str.starts_with(start, CaseSensitivity::CaseInsensitive)) {
  2192. found_callback();
  2193. return str.substring_view(start.length());
  2194. }
  2195. return str;
  2196. }
  2197. ErrorOr<RefPtr<StyleValue>> Parser::parse_linear_gradient_function(ComponentValue const& component_value)
  2198. {
  2199. using GradientType = LinearGradientStyleValue::GradientType;
  2200. if (!component_value.is_function())
  2201. return nullptr;
  2202. GradientRepeating repeating_gradient = GradientRepeating::No;
  2203. GradientType gradient_type { GradientType::Standard };
  2204. auto function_name = component_value.function().name();
  2205. function_name = consume_if_starts_with(function_name, "-webkit-"sv, [&] {
  2206. gradient_type = GradientType::WebKit;
  2207. });
  2208. function_name = consume_if_starts_with(function_name, "repeating-"sv, [&] {
  2209. repeating_gradient = GradientRepeating::Yes;
  2210. });
  2211. if (!function_name.equals_ignoring_ascii_case("linear-gradient"sv))
  2212. return nullptr;
  2213. // linear-gradient() = linear-gradient([ <angle> | to <side-or-corner> ]?, <color-stop-list>)
  2214. TokenStream tokens { component_value.function().values() };
  2215. tokens.skip_whitespace();
  2216. if (!tokens.has_next_token())
  2217. return nullptr;
  2218. bool has_direction_param = true;
  2219. LinearGradientStyleValue::GradientDirection gradient_direction = gradient_type == GradientType::Standard
  2220. ? SideOrCorner::Bottom
  2221. : SideOrCorner::Top;
  2222. auto to_side = [](StringView value) -> Optional<SideOrCorner> {
  2223. if (value.equals_ignoring_ascii_case("top"sv))
  2224. return SideOrCorner::Top;
  2225. if (value.equals_ignoring_ascii_case("bottom"sv))
  2226. return SideOrCorner::Bottom;
  2227. if (value.equals_ignoring_ascii_case("left"sv))
  2228. return SideOrCorner::Left;
  2229. if (value.equals_ignoring_ascii_case("right"sv))
  2230. return SideOrCorner::Right;
  2231. return {};
  2232. };
  2233. auto is_to_side_or_corner = [&](auto const& token) {
  2234. if (!token.is(Token::Type::Ident))
  2235. return false;
  2236. if (gradient_type == GradientType::WebKit)
  2237. return to_side(token.token().ident()).has_value();
  2238. return token.token().ident().equals_ignoring_ascii_case("to"sv);
  2239. };
  2240. auto const& first_param = tokens.peek_token();
  2241. if (first_param.is(Token::Type::Dimension)) {
  2242. // <angle>
  2243. tokens.next_token();
  2244. float angle_value = first_param.token().dimension_value();
  2245. auto unit_string = first_param.token().dimension_unit();
  2246. auto angle_type = Angle::unit_from_name(unit_string);
  2247. if (!angle_type.has_value())
  2248. return nullptr;
  2249. gradient_direction = Angle { angle_value, angle_type.release_value() };
  2250. } else if (is_to_side_or_corner(first_param)) {
  2251. // <side-or-corner> = [left | right] || [top | bottom]
  2252. // Note: -webkit-linear-gradient does not include to the "to" prefix on the side or corner
  2253. if (gradient_type == GradientType::Standard) {
  2254. tokens.next_token();
  2255. tokens.skip_whitespace();
  2256. if (!tokens.has_next_token())
  2257. return nullptr;
  2258. }
  2259. // [left | right] || [top | bottom]
  2260. auto const& first_side = tokens.next_token();
  2261. if (!first_side.is(Token::Type::Ident))
  2262. return nullptr;
  2263. auto side_a = to_side(first_side.token().ident());
  2264. tokens.skip_whitespace();
  2265. Optional<SideOrCorner> side_b;
  2266. if (tokens.has_next_token() && tokens.peek_token().is(Token::Type::Ident))
  2267. side_b = to_side(tokens.next_token().token().ident());
  2268. if (side_a.has_value() && !side_b.has_value()) {
  2269. gradient_direction = *side_a;
  2270. } else if (side_a.has_value() && side_b.has_value()) {
  2271. // Convert two sides to a corner
  2272. if (to_underlying(*side_b) < to_underlying(*side_a))
  2273. swap(side_a, side_b);
  2274. if (side_a == SideOrCorner::Top && side_b == SideOrCorner::Left)
  2275. gradient_direction = SideOrCorner::TopLeft;
  2276. else if (side_a == SideOrCorner::Top && side_b == SideOrCorner::Right)
  2277. gradient_direction = SideOrCorner::TopRight;
  2278. else if (side_a == SideOrCorner::Bottom && side_b == SideOrCorner::Left)
  2279. gradient_direction = SideOrCorner::BottomLeft;
  2280. else if (side_a == SideOrCorner::Bottom && side_b == SideOrCorner::Right)
  2281. gradient_direction = SideOrCorner::BottomRight;
  2282. else
  2283. return nullptr;
  2284. } else {
  2285. return nullptr;
  2286. }
  2287. } else {
  2288. has_direction_param = false;
  2289. }
  2290. tokens.skip_whitespace();
  2291. if (!tokens.has_next_token())
  2292. return nullptr;
  2293. if (has_direction_param && !tokens.next_token().is(Token::Type::Comma))
  2294. return nullptr;
  2295. auto color_stops = parse_linear_color_stop_list(tokens);
  2296. if (!color_stops.has_value())
  2297. return nullptr;
  2298. return LinearGradientStyleValue::create(gradient_direction, move(*color_stops), gradient_type, repeating_gradient);
  2299. }
  2300. ErrorOr<RefPtr<StyleValue>> Parser::parse_conic_gradient_function(ComponentValue const& component_value)
  2301. {
  2302. if (!component_value.is_function())
  2303. return nullptr;
  2304. GradientRepeating repeating_gradient = GradientRepeating::No;
  2305. auto function_name = component_value.function().name();
  2306. function_name = consume_if_starts_with(function_name, "repeating-"sv, [&] {
  2307. repeating_gradient = GradientRepeating::Yes;
  2308. });
  2309. if (!function_name.equals_ignoring_ascii_case("conic-gradient"sv))
  2310. return nullptr;
  2311. TokenStream tokens { component_value.function().values() };
  2312. tokens.skip_whitespace();
  2313. if (!tokens.has_next_token())
  2314. return nullptr;
  2315. Angle from_angle(0, Angle::Type::Deg);
  2316. PositionValue at_position = PositionValue::center();
  2317. // conic-gradient( [ [ from <angle> ]? [ at <position> ]? ] ||
  2318. // <color-interpolation-method> , <angular-color-stop-list> )
  2319. auto token = tokens.peek_token();
  2320. bool got_from_angle = false;
  2321. bool got_color_interpolation_method = false;
  2322. bool got_at_position = false;
  2323. while (token.is(Token::Type::Ident)) {
  2324. auto consume_identifier = [&](auto identifier) {
  2325. auto token_string = token.token().ident();
  2326. if (token_string.equals_ignoring_ascii_case(identifier)) {
  2327. (void)tokens.next_token();
  2328. tokens.skip_whitespace();
  2329. return true;
  2330. }
  2331. return false;
  2332. };
  2333. if (consume_identifier("from"sv)) {
  2334. // from <angle>
  2335. if (got_from_angle || got_at_position)
  2336. return nullptr;
  2337. if (!tokens.has_next_token())
  2338. return nullptr;
  2339. auto angle_token = tokens.next_token();
  2340. if (!angle_token.is(Token::Type::Dimension))
  2341. return nullptr;
  2342. float angle = angle_token.token().dimension_value();
  2343. auto angle_unit = angle_token.token().dimension_unit();
  2344. auto angle_type = Angle::unit_from_name(angle_unit);
  2345. if (!angle_type.has_value())
  2346. return nullptr;
  2347. from_angle = Angle(angle, *angle_type);
  2348. got_from_angle = true;
  2349. } else if (consume_identifier("at"sv)) {
  2350. // at <position>
  2351. if (got_at_position)
  2352. return nullptr;
  2353. auto position = parse_position(tokens);
  2354. if (!position.has_value())
  2355. return nullptr;
  2356. at_position = *position;
  2357. got_at_position = true;
  2358. } else if (consume_identifier("in"sv)) {
  2359. // <color-interpolation-method>
  2360. if (got_color_interpolation_method)
  2361. return nullptr;
  2362. dbgln("FIXME: Parse color interpolation method for conic-gradient()");
  2363. got_color_interpolation_method = true;
  2364. } else {
  2365. break;
  2366. }
  2367. tokens.skip_whitespace();
  2368. if (!tokens.has_next_token())
  2369. return nullptr;
  2370. token = tokens.peek_token();
  2371. }
  2372. tokens.skip_whitespace();
  2373. if (!tokens.has_next_token())
  2374. return nullptr;
  2375. if ((got_from_angle || got_at_position || got_color_interpolation_method) && !tokens.next_token().is(Token::Type::Comma))
  2376. return nullptr;
  2377. auto color_stops = parse_angular_color_stop_list(tokens);
  2378. if (!color_stops.has_value())
  2379. return nullptr;
  2380. return ConicGradientStyleValue::create(from_angle, at_position, move(*color_stops), repeating_gradient);
  2381. }
  2382. ErrorOr<RefPtr<StyleValue>> Parser::parse_radial_gradient_function(ComponentValue const& component_value)
  2383. {
  2384. using EndingShape = RadialGradientStyleValue::EndingShape;
  2385. using Extent = RadialGradientStyleValue::Extent;
  2386. using CircleSize = RadialGradientStyleValue::CircleSize;
  2387. using EllipseSize = RadialGradientStyleValue::EllipseSize;
  2388. using Size = RadialGradientStyleValue::Size;
  2389. if (!component_value.is_function())
  2390. return nullptr;
  2391. auto repeating_gradient = GradientRepeating::No;
  2392. auto function_name = component_value.function().name();
  2393. function_name = consume_if_starts_with(function_name, "repeating-"sv, [&] {
  2394. repeating_gradient = GradientRepeating::Yes;
  2395. });
  2396. if (!function_name.equals_ignoring_ascii_case("radial-gradient"sv))
  2397. return nullptr;
  2398. TokenStream tokens { component_value.function().values() };
  2399. tokens.skip_whitespace();
  2400. if (!tokens.has_next_token())
  2401. return nullptr;
  2402. bool expect_comma = false;
  2403. auto commit_value = [&]<typename... T>(auto value, T&... transactions) {
  2404. (transactions.commit(), ...);
  2405. return value;
  2406. };
  2407. // radial-gradient( [ <ending-shape> || <size> ]? [ at <position> ]? , <color-stop-list> )
  2408. Size size = Extent::FarthestCorner;
  2409. EndingShape ending_shape = EndingShape::Circle;
  2410. PositionValue at_position = PositionValue::center();
  2411. auto parse_ending_shape = [&]() -> Optional<EndingShape> {
  2412. auto transaction = tokens.begin_transaction();
  2413. tokens.skip_whitespace();
  2414. auto& token = tokens.next_token();
  2415. if (!token.is(Token::Type::Ident))
  2416. return {};
  2417. auto ident = token.token().ident();
  2418. if (ident.equals_ignoring_ascii_case("circle"sv))
  2419. return commit_value(EndingShape::Circle, transaction);
  2420. if (ident.equals_ignoring_ascii_case("ellipse"sv))
  2421. return commit_value(EndingShape::Ellipse, transaction);
  2422. return {};
  2423. };
  2424. auto parse_extent_keyword = [](StringView keyword) -> Optional<Extent> {
  2425. if (keyword.equals_ignoring_ascii_case("closest-corner"sv))
  2426. return Extent::ClosestCorner;
  2427. if (keyword.equals_ignoring_ascii_case("closest-side"sv))
  2428. return Extent::ClosestSide;
  2429. if (keyword.equals_ignoring_ascii_case("farthest-corner"sv))
  2430. return Extent::FarthestCorner;
  2431. if (keyword.equals_ignoring_ascii_case("farthest-side"sv))
  2432. return Extent::FarthestSide;
  2433. return {};
  2434. };
  2435. auto parse_size = [&]() -> Optional<Size> {
  2436. // <size> =
  2437. // <extent-keyword> |
  2438. // <length [0,∞]> |
  2439. // <length-percentage [0,∞]>{2}
  2440. auto transaction_size = tokens.begin_transaction();
  2441. tokens.skip_whitespace();
  2442. if (!tokens.has_next_token())
  2443. return {};
  2444. auto& token = tokens.next_token();
  2445. if (token.is(Token::Type::Ident)) {
  2446. auto extent = parse_extent_keyword(token.token().ident());
  2447. if (!extent.has_value())
  2448. return {};
  2449. return commit_value(*extent, transaction_size);
  2450. }
  2451. auto first_dimension = parse_dimension(token);
  2452. if (!first_dimension.has_value())
  2453. return {};
  2454. if (!first_dimension->is_length_percentage())
  2455. return {};
  2456. auto transaction_second_dimension = tokens.begin_transaction();
  2457. tokens.skip_whitespace();
  2458. if (tokens.has_next_token()) {
  2459. auto& second_token = tokens.next_token();
  2460. auto second_dimension = parse_dimension(second_token);
  2461. if (second_dimension.has_value() && second_dimension->is_length_percentage())
  2462. return commit_value(EllipseSize { first_dimension->length_percentage(), second_dimension->length_percentage() },
  2463. transaction_size, transaction_second_dimension);
  2464. }
  2465. if (first_dimension->is_length())
  2466. return commit_value(CircleSize { first_dimension->length() }, transaction_size);
  2467. return {};
  2468. };
  2469. {
  2470. // [ <ending-shape> || <size> ]?
  2471. auto maybe_ending_shape = parse_ending_shape();
  2472. auto maybe_size = parse_size();
  2473. if (!maybe_ending_shape.has_value() && maybe_size.has_value())
  2474. maybe_ending_shape = parse_ending_shape();
  2475. if (maybe_size.has_value()) {
  2476. size = *maybe_size;
  2477. expect_comma = true;
  2478. }
  2479. if (maybe_ending_shape.has_value()) {
  2480. expect_comma = true;
  2481. ending_shape = *maybe_ending_shape;
  2482. if (ending_shape == EndingShape::Circle && size.has<EllipseSize>())
  2483. return nullptr;
  2484. if (ending_shape == EndingShape::Ellipse && size.has<CircleSize>())
  2485. return nullptr;
  2486. } else {
  2487. ending_shape = size.has<CircleSize>() ? EndingShape::Circle : EndingShape::Ellipse;
  2488. }
  2489. }
  2490. tokens.skip_whitespace();
  2491. if (!tokens.has_next_token())
  2492. return nullptr;
  2493. auto& token = tokens.peek_token();
  2494. if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("at"sv)) {
  2495. (void)tokens.next_token();
  2496. auto position = parse_position(tokens);
  2497. if (!position.has_value())
  2498. return nullptr;
  2499. at_position = *position;
  2500. expect_comma = true;
  2501. }
  2502. tokens.skip_whitespace();
  2503. if (!tokens.has_next_token())
  2504. return nullptr;
  2505. if (expect_comma && !tokens.next_token().is(Token::Type::Comma))
  2506. return nullptr;
  2507. // <color-stop-list>
  2508. auto color_stops = parse_linear_color_stop_list(tokens);
  2509. if (!color_stops.has_value())
  2510. return nullptr;
  2511. return RadialGradientStyleValue::create(ending_shape, size, at_position, move(*color_stops), repeating_gradient);
  2512. }
  2513. Optional<PositionValue> Parser::parse_position(TokenStream<ComponentValue>& tokens, PositionValue initial_value)
  2514. {
  2515. auto transaction = tokens.begin_transaction();
  2516. tokens.skip_whitespace();
  2517. if (!tokens.has_next_token())
  2518. return {};
  2519. auto parse_horizontal_preset = [&](auto ident) -> Optional<PositionValue::HorizontalPreset> {
  2520. if (ident.equals_ignoring_ascii_case("left"sv))
  2521. return PositionValue::HorizontalPreset::Left;
  2522. if (ident.equals_ignoring_ascii_case("center"sv))
  2523. return PositionValue::HorizontalPreset::Center;
  2524. if (ident.equals_ignoring_ascii_case("right"sv))
  2525. return PositionValue::HorizontalPreset::Right;
  2526. return {};
  2527. };
  2528. auto parse_vertical_preset = [&](auto ident) -> Optional<PositionValue::VerticalPreset> {
  2529. if (ident.equals_ignoring_ascii_case("top"sv))
  2530. return PositionValue::VerticalPreset::Top;
  2531. if (ident.equals_ignoring_ascii_case("center"sv))
  2532. return PositionValue::VerticalPreset::Center;
  2533. if (ident.equals_ignoring_ascii_case("bottom"sv))
  2534. return PositionValue::VerticalPreset::Bottom;
  2535. return {};
  2536. };
  2537. auto parse_horizontal_edge = [&](auto ident) -> Optional<PositionValue::HorizontalEdge> {
  2538. if (ident.equals_ignoring_ascii_case("left"sv))
  2539. return PositionValue::HorizontalEdge::Left;
  2540. if (ident.equals_ignoring_ascii_case("right"sv))
  2541. return PositionValue::HorizontalEdge::Right;
  2542. return {};
  2543. };
  2544. auto parse_vertical_edge = [&](auto ident) -> Optional<PositionValue::VerticalEdge> {
  2545. if (ident.equals_ignoring_ascii_case("top"sv))
  2546. return PositionValue::VerticalEdge::Top;
  2547. if (ident.equals_ignoring_ascii_case("bottom"sv))
  2548. return PositionValue::VerticalEdge::Bottom;
  2549. return {};
  2550. };
  2551. // <position> = [
  2552. // [ left | center | right ] || [ top | center | bottom ]
  2553. // |
  2554. // [ left | center | right | <length-percentage> ]
  2555. // [ top | center | bottom | <length-percentage> ]?
  2556. // |
  2557. // [ [ left | right ] <length-percentage> ] &&
  2558. // [ [ top | bottom ] <length-percentage> ]
  2559. // ]
  2560. // [ left | center | right ] || [ top | center | bottom ]
  2561. auto alternation_1 = [&]() -> Optional<PositionValue> {
  2562. auto transaction = tokens.begin_transaction();
  2563. PositionValue position = initial_value;
  2564. auto& first_token = tokens.next_token();
  2565. if (!first_token.is(Token::Type::Ident))
  2566. return {};
  2567. auto ident = first_token.token().ident();
  2568. // <horizontal-position> <vertical-position>?
  2569. auto horizontal_position = parse_horizontal_preset(ident);
  2570. if (horizontal_position.has_value()) {
  2571. position.horizontal_position = *horizontal_position;
  2572. auto transaction_optional_parse = tokens.begin_transaction();
  2573. tokens.skip_whitespace();
  2574. if (tokens.has_next_token()) {
  2575. auto& second_token = tokens.next_token();
  2576. if (second_token.is(Token::Type::Ident)) {
  2577. auto vertical_position = parse_vertical_preset(second_token.token().ident());
  2578. if (vertical_position.has_value()) {
  2579. transaction_optional_parse.commit();
  2580. position.vertical_position = *vertical_position;
  2581. }
  2582. }
  2583. }
  2584. } else {
  2585. // <vertical-position> <horizontal-position>?
  2586. auto vertical_position = parse_vertical_preset(ident);
  2587. if (!vertical_position.has_value())
  2588. return {};
  2589. position.vertical_position = *vertical_position;
  2590. auto transaction_optional_parse = tokens.begin_transaction();
  2591. tokens.skip_whitespace();
  2592. if (tokens.has_next_token()) {
  2593. auto& second_token = tokens.next_token();
  2594. if (second_token.is(Token::Type::Ident)) {
  2595. auto horizontal_position = parse_horizontal_preset(second_token.token().ident());
  2596. if (horizontal_position.has_value()) {
  2597. transaction_optional_parse.commit();
  2598. position.horizontal_position = *horizontal_position;
  2599. }
  2600. }
  2601. }
  2602. }
  2603. transaction.commit();
  2604. return position;
  2605. };
  2606. // [ left | center | right | <length-percentage> ]
  2607. // [ top | center | bottom | <length-percentage> ]?
  2608. auto alternation_2 = [&]() -> Optional<PositionValue> {
  2609. auto transaction = tokens.begin_transaction();
  2610. PositionValue position = initial_value;
  2611. auto& first_token = tokens.next_token();
  2612. if (first_token.is(Token::Type::Ident)) {
  2613. auto horizontal_position = parse_horizontal_preset(first_token.token().ident());
  2614. if (!horizontal_position.has_value())
  2615. return {};
  2616. position.horizontal_position = *horizontal_position;
  2617. } else {
  2618. auto dimension = parse_dimension(first_token);
  2619. if (!dimension.has_value() || !dimension->is_length_percentage())
  2620. return {};
  2621. position.horizontal_position = dimension->length_percentage();
  2622. }
  2623. auto transaction_optional_parse = tokens.begin_transaction();
  2624. tokens.skip_whitespace();
  2625. if (tokens.has_next_token()) {
  2626. auto& second_token = tokens.next_token();
  2627. if (second_token.is(Token::Type::Ident)) {
  2628. auto vertical_position = parse_vertical_preset(second_token.token().ident());
  2629. if (vertical_position.has_value()) {
  2630. transaction_optional_parse.commit();
  2631. position.vertical_position = *vertical_position;
  2632. }
  2633. } else {
  2634. auto dimension = parse_dimension(second_token);
  2635. if (dimension.has_value() && dimension->is_length_percentage()) {
  2636. transaction_optional_parse.commit();
  2637. position.vertical_position = dimension->length_percentage();
  2638. }
  2639. }
  2640. }
  2641. transaction.commit();
  2642. return position;
  2643. };
  2644. // [ [ left | right ] <length-percentage> ] &&
  2645. // [ [ top | bottom ] <length-percentage> ]
  2646. auto alternation_3 = [&]() -> Optional<PositionValue> {
  2647. auto transaction = tokens.begin_transaction();
  2648. PositionValue position {};
  2649. auto parse_horizontal = [&] {
  2650. // [ left | right ] <length-percentage> ]
  2651. auto transaction = tokens.begin_transaction();
  2652. tokens.skip_whitespace();
  2653. if (!tokens.has_next_token())
  2654. return false;
  2655. auto& first_token = tokens.next_token();
  2656. if (!first_token.is(Token::Type::Ident))
  2657. return false;
  2658. auto horizontal_egde = parse_horizontal_edge(first_token.token().ident());
  2659. if (!horizontal_egde.has_value())
  2660. return false;
  2661. position.x_relative_to = *horizontal_egde;
  2662. tokens.skip_whitespace();
  2663. if (!tokens.has_next_token())
  2664. return false;
  2665. auto& second_token = tokens.next_token();
  2666. auto dimension = parse_dimension(second_token);
  2667. if (!dimension.has_value() || !dimension->is_length_percentage())
  2668. return false;
  2669. position.horizontal_position = dimension->length_percentage();
  2670. transaction.commit();
  2671. return true;
  2672. };
  2673. auto parse_vertical = [&] {
  2674. // [ top | bottom ] <length-percentage> ]
  2675. auto transaction = tokens.begin_transaction();
  2676. tokens.skip_whitespace();
  2677. if (!tokens.has_next_token())
  2678. return false;
  2679. auto& first_token = tokens.next_token();
  2680. if (!first_token.is(Token::Type::Ident))
  2681. return false;
  2682. auto vertical_edge = parse_vertical_edge(first_token.token().ident());
  2683. if (!vertical_edge.has_value())
  2684. return false;
  2685. position.y_relative_to = *vertical_edge;
  2686. tokens.skip_whitespace();
  2687. if (!tokens.has_next_token())
  2688. return false;
  2689. auto& second_token = tokens.next_token();
  2690. auto dimension = parse_dimension(second_token);
  2691. if (!dimension.has_value() || !dimension->is_length_percentage())
  2692. return false;
  2693. position.vertical_position = dimension->length_percentage();
  2694. transaction.commit();
  2695. return true;
  2696. };
  2697. if ((parse_horizontal() && parse_vertical()) || (parse_vertical() && parse_horizontal())) {
  2698. transaction.commit();
  2699. return position;
  2700. }
  2701. return {};
  2702. };
  2703. // Note: The alternatives must be attempted in this order since `alternation_2' can match a prefix of `alternation_3'
  2704. auto position = alternation_3();
  2705. if (!position.has_value())
  2706. position = alternation_2();
  2707. if (!position.has_value())
  2708. position = alternation_1();
  2709. if (position.has_value())
  2710. transaction.commit();
  2711. return position;
  2712. }
  2713. CSSRule* Parser::convert_to_rule(NonnullRefPtr<Rule> rule)
  2714. {
  2715. if (rule->is_at_rule()) {
  2716. if (has_ignored_vendor_prefix(rule->at_rule_name()))
  2717. return {};
  2718. if (rule->at_rule_name().equals_ignoring_ascii_case("font-face"sv)) {
  2719. if (!rule->block() || !rule->block()->is_curly()) {
  2720. dbgln_if(CSS_PARSER_DEBUG, "@font-face rule is malformed.");
  2721. return {};
  2722. }
  2723. TokenStream tokens { rule->block()->values() };
  2724. return parse_font_face_rule(tokens);
  2725. }
  2726. if (rule->at_rule_name().equals_ignoring_ascii_case("import"sv) && !rule->prelude().is_empty()) {
  2727. Optional<AK::URL> url;
  2728. for (auto const& token : rule->prelude()) {
  2729. if (token.is(Token::Type::Whitespace))
  2730. continue;
  2731. if (token.is(Token::Type::String)) {
  2732. url = m_context.complete_url(token.token().string());
  2733. } else {
  2734. url = parse_url_function(token);
  2735. }
  2736. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  2737. if (url.has_value())
  2738. break;
  2739. }
  2740. if (url.has_value())
  2741. return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document())).release_value_but_fixme_should_propagate_errors();
  2742. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse url from @import rule");
  2743. return {};
  2744. }
  2745. if (rule->at_rule_name().equals_ignoring_ascii_case("media"sv)) {
  2746. auto media_query_tokens = TokenStream { rule->prelude() };
  2747. auto media_query_list = parse_a_media_query_list(media_query_tokens);
  2748. if (media_query_list.is_empty() || !rule->block())
  2749. return {};
  2750. auto child_tokens = TokenStream { rule->block()->values() };
  2751. auto parser_rules = parse_a_list_of_rules(child_tokens);
  2752. JS::MarkedVector<CSSRule*> child_rules(m_context.realm().heap());
  2753. for (auto& raw_rule : parser_rules) {
  2754. if (auto* child_rule = convert_to_rule(raw_rule))
  2755. child_rules.append(child_rule);
  2756. }
  2757. auto media_list = MediaList::create(m_context.realm(), move(media_query_list)).release_value_but_fixme_should_propagate_errors();
  2758. auto rule_list = CSSRuleList::create(m_context.realm(), child_rules).release_value_but_fixme_should_propagate_errors();
  2759. return CSSMediaRule::create(m_context.realm(), media_list, rule_list).release_value_but_fixme_should_propagate_errors();
  2760. }
  2761. if (rule->at_rule_name().equals_ignoring_ascii_case("supports"sv)) {
  2762. auto supports_tokens = TokenStream { rule->prelude() };
  2763. auto supports = parse_a_supports(supports_tokens);
  2764. if (!supports) {
  2765. if constexpr (CSS_PARSER_DEBUG) {
  2766. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @supports rule invalid; discarding.");
  2767. supports_tokens.dump_all_tokens();
  2768. }
  2769. return {};
  2770. }
  2771. if (!rule->block())
  2772. return {};
  2773. auto child_tokens = TokenStream { rule->block()->values() };
  2774. auto parser_rules = parse_a_list_of_rules(child_tokens);
  2775. JS::MarkedVector<CSSRule*> child_rules(m_context.realm().heap());
  2776. for (auto& raw_rule : parser_rules) {
  2777. if (auto* child_rule = convert_to_rule(raw_rule))
  2778. child_rules.append(child_rule);
  2779. }
  2780. auto rule_list = CSSRuleList::create(m_context.realm(), child_rules).release_value_but_fixme_should_propagate_errors();
  2781. return CSSSupportsRule::create(m_context.realm(), supports.release_nonnull(), rule_list).release_value_but_fixme_should_propagate_errors();
  2782. }
  2783. if (rule->at_rule_name().equals_ignoring_ascii_case("keyframes"sv)) {
  2784. auto prelude_stream = TokenStream { rule->prelude() };
  2785. prelude_stream.skip_whitespace();
  2786. auto token = prelude_stream.next_token();
  2787. if (!token.is_token()) {
  2788. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes has invalid prelude, prelude = {}; discarding.", rule->prelude());
  2789. return {};
  2790. }
  2791. auto name_token = token.token();
  2792. prelude_stream.skip_whitespace();
  2793. if (prelude_stream.has_next_token()) {
  2794. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes has invalid prelude, prelude = {}; discarding.", rule->prelude());
  2795. return {};
  2796. }
  2797. if (name_token.is(Token::Type::Ident) && (is_builtin(name_token.ident()) || name_token.ident().equals_ignoring_ascii_case("none"sv))) {
  2798. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule name is invalid: {}; discarding.", name_token.ident());
  2799. return {};
  2800. }
  2801. if (!name_token.is(Token::Type::String) && !name_token.is(Token::Type::Ident)) {
  2802. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule name is invalid: {}; discarding.", name_token.to_debug_string());
  2803. return {};
  2804. }
  2805. auto name = name_token.to_string().release_value_but_fixme_should_propagate_errors();
  2806. if (!rule->block())
  2807. return {};
  2808. auto child_tokens = TokenStream { rule->block()->values() };
  2809. Vector<JS::NonnullGCPtr<CSSKeyframeRule>> keyframes;
  2810. while (child_tokens.has_next_token()) {
  2811. child_tokens.skip_whitespace();
  2812. // keyframe-selector = <keyframe-keyword> | <percentage>
  2813. // keyframe-keyword = "from" | "to"
  2814. // selector = <keyframe-selector>#
  2815. // keyframes-block = "{" <declaration-list>? "}"
  2816. // keyframe-rule = <selector> <keyframes-block>
  2817. auto selectors = Vector<CSS::Percentage> {};
  2818. while (child_tokens.has_next_token()) {
  2819. child_tokens.skip_whitespace();
  2820. if (!child_tokens.has_next_token())
  2821. break;
  2822. auto tok = child_tokens.next_token();
  2823. if (!tok.is_token()) {
  2824. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule has invalid selector: {}; discarding.", tok.to_debug_string());
  2825. child_tokens.reconsume_current_input_token();
  2826. break;
  2827. }
  2828. auto token = tok.token();
  2829. auto read_a_selector = false;
  2830. if (token.is(Token::Type::Ident)) {
  2831. if (token.ident().equals_ignoring_ascii_case("from"sv)) {
  2832. selectors.append(CSS::Percentage(0));
  2833. read_a_selector = true;
  2834. }
  2835. if (token.ident().equals_ignoring_ascii_case("to"sv)) {
  2836. selectors.append(CSS::Percentage(100));
  2837. read_a_selector = true;
  2838. }
  2839. } else if (token.is(Token::Type::Percentage)) {
  2840. selectors.append(CSS::Percentage(token.percentage()));
  2841. read_a_selector = true;
  2842. }
  2843. if (read_a_selector) {
  2844. child_tokens.skip_whitespace();
  2845. if (child_tokens.next_token().is(Token::Type::Comma))
  2846. continue;
  2847. }
  2848. child_tokens.reconsume_current_input_token();
  2849. break;
  2850. }
  2851. if (!child_tokens.has_next_token())
  2852. break;
  2853. child_tokens.skip_whitespace();
  2854. auto token = child_tokens.next_token();
  2855. if (token.is_block()) {
  2856. auto block_tokens = token.block().values();
  2857. auto block_stream = TokenStream { block_tokens };
  2858. auto block_declarations = parse_a_list_of_declarations(block_stream);
  2859. auto style = convert_to_style_declaration(block_declarations);
  2860. for (auto& selector : selectors) {
  2861. auto keyframe_rule = CSSKeyframeRule::create(m_context.realm(), selector, *style).release_value_but_fixme_should_propagate_errors();
  2862. keyframes.append(keyframe_rule);
  2863. }
  2864. } else {
  2865. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule has invalid block: {}; discarding.", token.to_debug_string());
  2866. }
  2867. }
  2868. return CSSKeyframesRule::create(m_context.realm(), name, move(keyframes)).release_value_but_fixme_should_propagate_errors();
  2869. }
  2870. if (rule->at_rule_name().equals_ignoring_ascii_case("namespace"sv)) {
  2871. // https://drafts.csswg.org/css-namespaces/#syntax
  2872. auto token_stream = TokenStream { rule->prelude() };
  2873. token_stream.skip_whitespace();
  2874. auto token = token_stream.next_token();
  2875. Optional<DeprecatedString> prefix = {};
  2876. if (token.is(Token::Type::Ident)) {
  2877. prefix = token.token().ident();
  2878. token_stream.skip_whitespace();
  2879. token = token_stream.next_token();
  2880. }
  2881. DeprecatedString namespace_uri;
  2882. if (token.is(Token::Type::String)) {
  2883. namespace_uri = token.token().string();
  2884. } else if (auto url = parse_url_function(token); url.has_value()) {
  2885. namespace_uri = url.value().to_deprecated_string();
  2886. } else {
  2887. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @namespace rule invalid; discarding.");
  2888. return {};
  2889. }
  2890. token_stream.skip_whitespace();
  2891. if (token_stream.has_next_token()) {
  2892. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @namespace rule invalid; discarding.");
  2893. return {};
  2894. }
  2895. return CSSNamespaceRule::create(m_context.realm(), prefix, namespace_uri).release_value_but_fixme_should_propagate_errors();
  2896. }
  2897. // FIXME: More at rules!
  2898. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS at-rule: @{}", rule->at_rule_name());
  2899. return {};
  2900. }
  2901. auto prelude_stream = TokenStream(rule->prelude());
  2902. auto selectors = parse_a_selector_list(prelude_stream, SelectorType::Standalone);
  2903. if (selectors.is_error()) {
  2904. if (selectors.error() == ParseError::SyntaxError) {
  2905. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule selectors invalid; discarding.");
  2906. if constexpr (CSS_PARSER_DEBUG) {
  2907. prelude_stream.dump_all_tokens();
  2908. }
  2909. }
  2910. return {};
  2911. }
  2912. if (selectors.value().is_empty()) {
  2913. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: empty selector; discarding.");
  2914. return {};
  2915. }
  2916. if (!rule->block()->is_curly())
  2917. return {};
  2918. auto stream = TokenStream(rule->block()->values());
  2919. auto declarations_and_at_rules = parse_a_style_blocks_contents(stream);
  2920. auto* declaration = convert_to_style_declaration(declarations_and_at_rules);
  2921. if (!declaration) {
  2922. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule declaration invalid; discarding.");
  2923. return {};
  2924. }
  2925. return CSSStyleRule::create(m_context.realm(), move(selectors.value()), *declaration).release_value_but_fixme_should_propagate_errors();
  2926. }
  2927. auto Parser::extract_properties(Vector<DeclarationOrAtRule> const& declarations_and_at_rules) -> PropertiesAndCustomProperties
  2928. {
  2929. PropertiesAndCustomProperties result;
  2930. for (auto const& declaration_or_at_rule : declarations_and_at_rules) {
  2931. if (declaration_or_at_rule.is_at_rule()) {
  2932. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  2933. continue;
  2934. }
  2935. auto const& declaration = declaration_or_at_rule.declaration();
  2936. if (auto maybe_property = convert_to_style_property(declaration); maybe_property.has_value()) {
  2937. auto property = maybe_property.release_value();
  2938. if (property.property_id == PropertyID::Custom) {
  2939. result.custom_properties.set(property.custom_name, property);
  2940. } else {
  2941. result.properties.append(move(property));
  2942. }
  2943. }
  2944. }
  2945. return result;
  2946. }
  2947. PropertyOwningCSSStyleDeclaration* Parser::convert_to_style_declaration(Vector<DeclarationOrAtRule> const& declarations_and_at_rules)
  2948. {
  2949. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  2950. return PropertyOwningCSSStyleDeclaration::create(m_context.realm(), move(properties), move(custom_properties)).release_value_but_fixme_should_propagate_errors();
  2951. }
  2952. Optional<StyleProperty> Parser::convert_to_style_property(Declaration const& declaration)
  2953. {
  2954. auto property_name = declaration.name();
  2955. auto property_id = property_id_from_string(property_name);
  2956. if (!property_id.has_value()) {
  2957. if (property_name.starts_with("--"sv)) {
  2958. property_id = PropertyID::Custom;
  2959. } else if (has_ignored_vendor_prefix(property_name)) {
  2960. return {};
  2961. } else if (!property_name.starts_with('-')) {
  2962. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS property '{}'", property_name);
  2963. return {};
  2964. }
  2965. }
  2966. auto value_token_stream = TokenStream(declaration.values());
  2967. auto value = parse_css_value(property_id.value(), value_token_stream);
  2968. if (value.is_error()) {
  2969. if (value.error() == ParseError::SyntaxError) {
  2970. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse value for CSS property '{}'.", property_name);
  2971. if constexpr (CSS_PARSER_DEBUG) {
  2972. value_token_stream.dump_all_tokens();
  2973. }
  2974. }
  2975. return {};
  2976. }
  2977. if (property_id.value() == PropertyID::Custom)
  2978. return StyleProperty { declaration.importance(), property_id.value(), value.release_value(), declaration.name() };
  2979. return StyleProperty { declaration.importance(), property_id.value(), value.release_value(), {} };
  2980. }
  2981. ErrorOr<RefPtr<StyleValue>> Parser::parse_builtin_value(ComponentValue const& component_value)
  2982. {
  2983. if (component_value.is(Token::Type::Ident)) {
  2984. auto ident = component_value.token().ident();
  2985. if (ident.equals_ignoring_ascii_case("inherit"sv))
  2986. return InheritStyleValue::the();
  2987. if (ident.equals_ignoring_ascii_case("initial"sv))
  2988. return InitialStyleValue::the();
  2989. if (ident.equals_ignoring_ascii_case("unset"sv))
  2990. return UnsetStyleValue::the();
  2991. if (ident.equals_ignoring_ascii_case("revert"sv))
  2992. return RevertStyleValue::the();
  2993. // FIXME: Implement `revert-layer` from CSS-CASCADE-5.
  2994. }
  2995. return nullptr;
  2996. }
  2997. ErrorOr<RefPtr<CalculatedStyleValue>> Parser::parse_calculated_value(Vector<ComponentValue> const& component_values)
  2998. {
  2999. auto calculation_tree = TRY(parse_a_calculation(component_values));
  3000. if (calculation_tree == nullptr) {
  3001. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse calculation tree");
  3002. return nullptr;
  3003. } else {
  3004. if constexpr (CSS_PARSER_DEBUG) {
  3005. dbgln("Parsed calculation tree:");
  3006. StringBuilder builder;
  3007. TRY(calculation_tree->dump(builder, 0));
  3008. dbgln(builder.string_view());
  3009. }
  3010. }
  3011. auto calc_type = calculation_tree->determine_type(m_context.current_property_id());
  3012. if (!calc_type.has_value()) {
  3013. dbgln_if(CSS_PARSER_DEBUG, "calc() resolved as invalid!!!");
  3014. return nullptr;
  3015. }
  3016. dbgln_if(CSS_PARSER_DEBUG, "Deduced calc() resolved type as: {}", calc_type->dump());
  3017. return CalculatedStyleValue::create(calculation_tree.release_nonnull(), calc_type.release_value());
  3018. }
  3019. ErrorOr<RefPtr<StyleValue>> Parser::parse_dynamic_value(ComponentValue const& component_value)
  3020. {
  3021. if (component_value.is_function()) {
  3022. auto const& function = component_value.function();
  3023. if (function.name().equals_ignoring_ascii_case("var"sv)) {
  3024. // Declarations using `var()` should already be parsed as an UnresolvedStyleValue before this point.
  3025. VERIFY_NOT_REACHED();
  3026. }
  3027. auto function_node = TRY(parse_a_calc_function_node(function));
  3028. if (!function_node)
  3029. return nullptr;
  3030. auto function_type = function_node->determine_type(m_context.current_property_id());
  3031. if (!function_type.has_value())
  3032. return nullptr;
  3033. return CalculatedStyleValue::create(function_node.release_nonnull(), function_type.release_value());
  3034. }
  3035. return nullptr;
  3036. }
  3037. ErrorOr<OwnPtr<CalculationNode>> Parser::parse_a_calc_function_node(Function const& function)
  3038. {
  3039. if (function.name().equals_ignoring_ascii_case("calc"sv))
  3040. return TRY(parse_a_calculation(function.values()));
  3041. if (auto maybe_function = TRY(parse_math_function(m_context.current_property_id(), function)); maybe_function)
  3042. return maybe_function;
  3043. return nullptr;
  3044. }
  3045. Optional<Parser::Dimension> Parser::parse_dimension(ComponentValue const& component_value)
  3046. {
  3047. if (component_value.is(Token::Type::Dimension)) {
  3048. float numeric_value = component_value.token().dimension_value();
  3049. auto unit_string = component_value.token().dimension_unit();
  3050. if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
  3051. return Length { numeric_value, length_type.release_value() };
  3052. if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
  3053. return Angle { numeric_value, angle_type.release_value() };
  3054. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  3055. return Frequency { numeric_value, frequency_type.release_value() };
  3056. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  3057. return Resolution { numeric_value, resolution_type.release_value() };
  3058. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  3059. return Time { numeric_value, time_type.release_value() };
  3060. }
  3061. if (component_value.is(Token::Type::Percentage))
  3062. return Percentage { static_cast<float>(component_value.token().percentage()) };
  3063. if (component_value.is(Token::Type::Number)) {
  3064. float numeric_value = component_value.token().number_value();
  3065. if (numeric_value == 0)
  3066. return Length::make_px(0);
  3067. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  3068. // https://quirks.spec.whatwg.org/#quirky-length-value
  3069. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  3070. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  3071. // expression, and must not be supported in the supports() static method of the CSS interface."
  3072. return Length::make_px(numeric_value);
  3073. }
  3074. }
  3075. return {};
  3076. }
  3077. Optional<LengthOrCalculated> Parser::parse_source_size_value(ComponentValue const& component_value)
  3078. {
  3079. if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_ascii_case("auto"sv)) {
  3080. return LengthOrCalculated { Length::make_auto() };
  3081. }
  3082. if (auto dynamic_value = parse_dynamic_value(component_value); !dynamic_value.is_error() && dynamic_value.value()) {
  3083. return LengthOrCalculated { dynamic_value.value()->as_calculated().as_calculated() };
  3084. }
  3085. if (auto length = parse_length(component_value); length.has_value()) {
  3086. return LengthOrCalculated { length.release_value() };
  3087. }
  3088. return {};
  3089. }
  3090. Optional<Length> Parser::parse_length(ComponentValue const& component_value)
  3091. {
  3092. auto dimension = parse_dimension(component_value);
  3093. if (!dimension.has_value())
  3094. return {};
  3095. if (dimension->is_length())
  3096. return dimension->length();
  3097. return {};
  3098. }
  3099. Optional<Ratio> Parser::parse_ratio(TokenStream<ComponentValue>& tokens)
  3100. {
  3101. auto transaction = tokens.begin_transaction();
  3102. tokens.skip_whitespace();
  3103. auto read_number_value = [this](ComponentValue const& component_value) -> Optional<float> {
  3104. if (component_value.is(Token::Type::Number)) {
  3105. return component_value.token().number_value();
  3106. } else if (component_value.is_function()) {
  3107. auto maybe_calc = parse_dynamic_value(component_value).release_value_but_fixme_should_propagate_errors();
  3108. if (!maybe_calc || !maybe_calc->is_calculated() || !maybe_calc->as_calculated().resolves_to_number())
  3109. return {};
  3110. if (auto resolved_number = maybe_calc->as_calculated().resolve_number(); resolved_number.has_value() && resolved_number.value() >= 0) {
  3111. return resolved_number.value();
  3112. }
  3113. }
  3114. return {};
  3115. };
  3116. // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
  3117. auto maybe_numerator = read_number_value(tokens.next_token());
  3118. if (!maybe_numerator.has_value() || maybe_numerator.value() < 0)
  3119. return {};
  3120. auto numerator = maybe_numerator.value();
  3121. {
  3122. auto two_value_transaction = tokens.begin_transaction();
  3123. tokens.skip_whitespace();
  3124. auto solidus = tokens.next_token();
  3125. tokens.skip_whitespace();
  3126. auto maybe_denominator = read_number_value(tokens.next_token());
  3127. if (solidus.is_delim('/') && maybe_denominator.has_value() && maybe_denominator.value() >= 0) {
  3128. auto denominator = maybe_denominator.value();
  3129. // Two-value ratio
  3130. two_value_transaction.commit();
  3131. transaction.commit();
  3132. return Ratio { numerator, denominator };
  3133. }
  3134. }
  3135. // Single-value ratio
  3136. transaction.commit();
  3137. return Ratio { numerator };
  3138. }
  3139. // https://www.w3.org/TR/css-syntax-3/#urange-syntax
  3140. Optional<UnicodeRange> Parser::parse_unicode_range(TokenStream<ComponentValue>& tokens)
  3141. {
  3142. auto transaction = tokens.begin_transaction();
  3143. tokens.skip_whitespace();
  3144. // <urange> =
  3145. // u '+' <ident-token> '?'* |
  3146. // u <dimension-token> '?'* |
  3147. // u <number-token> '?'* |
  3148. // u <number-token> <dimension-token> |
  3149. // u <number-token> <number-token> |
  3150. // u '+' '?'+
  3151. // (All with no whitespace in between tokens.)
  3152. // NOTE: Parsing this is different from usual. We take these steps:
  3153. // 1. Match the grammar above against the tokens, concatenating them into a string using their original representation.
  3154. // 2. Then, parse that string according to the spec algorithm.
  3155. // Step 2 is performed by calling the other parse_unicode_range() overload.
  3156. auto is_ending_token = [](ComponentValue const& component_value) {
  3157. return component_value.is(Token::Type::EndOfFile)
  3158. || component_value.is(Token::Type::Comma)
  3159. || component_value.is(Token::Type::Semicolon)
  3160. || component_value.is(Token::Type::Whitespace);
  3161. };
  3162. auto create_unicode_range = [&](StringView text, auto& local_transaction) -> Optional<UnicodeRange> {
  3163. auto maybe_unicode_range = parse_unicode_range(text);
  3164. if (maybe_unicode_range.has_value()) {
  3165. local_transaction.commit();
  3166. transaction.commit();
  3167. }
  3168. return maybe_unicode_range;
  3169. };
  3170. // All options start with 'u'/'U'.
  3171. auto const& u = tokens.next_token();
  3172. if (!(u.is(Token::Type::Ident) && u.token().ident().equals_ignoring_ascii_case("u"sv))) {
  3173. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> does not start with 'u'");
  3174. return {};
  3175. }
  3176. auto const& second_token = tokens.next_token();
  3177. // u '+' <ident-token> '?'* |
  3178. // u '+' '?'+
  3179. if (second_token.is_delim('+')) {
  3180. auto local_transaction = tokens.begin_transaction();
  3181. StringBuilder string_builder;
  3182. string_builder.append(second_token.token().representation());
  3183. auto const& third_token = tokens.next_token();
  3184. if (third_token.is(Token::Type::Ident) || third_token.is_delim('?')) {
  3185. string_builder.append(third_token.token().representation());
  3186. while (tokens.peek_token().is_delim('?'))
  3187. string_builder.append(tokens.next_token().token().representation());
  3188. if (is_ending_token(tokens.peek_token()))
  3189. return create_unicode_range(string_builder.string_view(), local_transaction);
  3190. }
  3191. }
  3192. // u <dimension-token> '?'*
  3193. if (second_token.is(Token::Type::Dimension)) {
  3194. auto local_transaction = tokens.begin_transaction();
  3195. StringBuilder string_builder;
  3196. string_builder.append(second_token.token().representation());
  3197. while (tokens.peek_token().is_delim('?'))
  3198. string_builder.append(tokens.next_token().token().representation());
  3199. if (is_ending_token(tokens.peek_token()))
  3200. return create_unicode_range(string_builder.string_view(), local_transaction);
  3201. }
  3202. // u <number-token> '?'* |
  3203. // u <number-token> <dimension-token> |
  3204. // u <number-token> <number-token>
  3205. if (second_token.is(Token::Type::Number)) {
  3206. auto local_transaction = tokens.begin_transaction();
  3207. StringBuilder string_builder;
  3208. string_builder.append(second_token.token().representation());
  3209. if (is_ending_token(tokens.peek_token()))
  3210. return create_unicode_range(string_builder.string_view(), local_transaction);
  3211. auto const& third_token = tokens.next_token();
  3212. if (third_token.is_delim('?')) {
  3213. string_builder.append(third_token.token().representation());
  3214. while (tokens.peek_token().is_delim('?'))
  3215. string_builder.append(tokens.next_token().token().representation());
  3216. if (is_ending_token(tokens.peek_token()))
  3217. return create_unicode_range(string_builder.string_view(), local_transaction);
  3218. } else if (third_token.is(Token::Type::Dimension)) {
  3219. string_builder.append(third_token.token().representation());
  3220. if (is_ending_token(tokens.peek_token()))
  3221. return create_unicode_range(string_builder.string_view(), local_transaction);
  3222. } else if (third_token.is(Token::Type::Number)) {
  3223. string_builder.append(third_token.token().representation());
  3224. if (is_ending_token(tokens.peek_token()))
  3225. return create_unicode_range(string_builder.string_view(), local_transaction);
  3226. }
  3227. }
  3228. if constexpr (CSS_PARSER_DEBUG) {
  3229. dbgln("CSSParser: Tokens did not match <urange> grammar.");
  3230. tokens.dump_all_tokens();
  3231. }
  3232. return {};
  3233. }
  3234. Optional<UnicodeRange> Parser::parse_unicode_range(StringView text)
  3235. {
  3236. auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<UnicodeRange> {
  3237. // https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point
  3238. constexpr u32 maximum_allowed_code_point = 0x10FFFF;
  3239. // To determine what codepoints the <urange> represents:
  3240. // 1. If end value is greater than the maximum allowed code point,
  3241. // the <urange> is invalid and a syntax error.
  3242. if (end_value > maximum_allowed_code_point) {
  3243. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: end_value ({}) > maximum ({})", end_value, maximum_allowed_code_point);
  3244. return {};
  3245. }
  3246. // 2. If start value is greater than end value, the <urange> is invalid and a syntax error.
  3247. if (start_value > end_value) {
  3248. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: start_value ({}) > end_value ({})", start_value, end_value);
  3249. return {};
  3250. }
  3251. // 3. Otherwise, the <urange> represents a contiguous range of codepoints from start value to end value, inclusive.
  3252. return UnicodeRange { start_value, end_value };
  3253. };
  3254. // 1. Skipping the first u token, concatenate the representations of all the tokens in the production together.
  3255. // Let this be text.
  3256. // NOTE: The concatenation is already done by the caller.
  3257. GenericLexer lexer { text };
  3258. // 2. If the first character of text is U+002B PLUS SIGN, consume it.
  3259. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  3260. if (lexer.next_is('+')) {
  3261. lexer.consume();
  3262. } else {
  3263. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Second character of <urange> was not '+'; got: '{}'", lexer.consume());
  3264. return {};
  3265. }
  3266. // 3. Consume as many hex digits from text as possible.
  3267. // then consume as many U+003F QUESTION MARK (?) code points as possible.
  3268. auto hex_digits = lexer.consume_while(is_ascii_hex_digit);
  3269. auto question_marks = lexer.consume_while([](auto it) { return it == '?'; });
  3270. // If zero code points were consumed, or more than six code points were consumed,
  3271. // this is an invalid <urange>, and this algorithm must exit.
  3272. size_t consumed_code_points = hex_digits.length() + question_marks.length();
  3273. if (consumed_code_points == 0 || consumed_code_points > 6) {
  3274. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value had {} digits/?s, expected between 1 and 6.", consumed_code_points);
  3275. return {};
  3276. }
  3277. StringView start_value_code_points { hex_digits.characters_without_null_termination(), consumed_code_points };
  3278. // If any U+003F QUESTION MARK (?) code points were consumed, then:
  3279. if (question_marks.length() > 0) {
  3280. // 1. If there are any code points left in text, this is an invalid <urange>,
  3281. // and this algorithm must exit.
  3282. if (lexer.tell_remaining() != 0) {
  3283. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  3284. return {};
  3285. }
  3286. // 2. Interpret the consumed code points as a hexadecimal number,
  3287. // with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
  3288. // This is the start value.
  3289. auto start_value_string = start_value_code_points.replace("?"sv, "0"sv, ReplaceMode::All);
  3290. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
  3291. if (!maybe_start_value.has_value()) {
  3292. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
  3293. return {};
  3294. }
  3295. u32 start_value = maybe_start_value.release_value();
  3296. // 3. Interpret the consumed code points as a hexadecimal number again,
  3297. // with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
  3298. // This is the end value.
  3299. auto end_value_string = start_value_code_points.replace("?"sv, "F"sv, ReplaceMode::All);
  3300. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
  3301. if (!maybe_end_value.has_value()) {
  3302. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");
  3303. return {};
  3304. }
  3305. u32 end_value = maybe_end_value.release_value();
  3306. // 4. Exit this algorithm.
  3307. return make_valid_unicode_range(start_value, end_value);
  3308. }
  3309. // Otherwise, interpret the consumed code points as a hexadecimal number. This is the start value.
  3310. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_code_points);
  3311. if (!maybe_start_value.has_value()) {
  3312. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value did not parse as hex number.");
  3313. return {};
  3314. }
  3315. u32 start_value = maybe_start_value.release_value();
  3316. // 4. If there are no code points left in text, The end value is the same as the start value.
  3317. // Exit this algorithm.
  3318. if (lexer.tell_remaining() == 0)
  3319. return make_valid_unicode_range(start_value, start_value);
  3320. // 5. If the next code point in text is U+002D HYPHEN-MINUS (-), consume it.
  3321. if (lexer.next_is('-')) {
  3322. lexer.consume();
  3323. }
  3324. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  3325. else {
  3326. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start and end values not separated by '-'.");
  3327. return {};
  3328. }
  3329. // 6. Consume as many hex digits as possible from text.
  3330. auto end_hex_digits = lexer.consume_while(is_ascii_hex_digit);
  3331. // If zero hex digits were consumed, or more than 6 hex digits were consumed,
  3332. // this is an invalid <urange>, and this algorithm must exit.
  3333. if (end_hex_digits.length() == 0 || end_hex_digits.length() > 6) {
  3334. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value had {} digits, expected between 1 and 6.", end_hex_digits.length());
  3335. return {};
  3336. }
  3337. // If there are any code points left in text, this is an invalid <urange>, and this algorithm must exit.
  3338. if (lexer.tell_remaining() != 0) {
  3339. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  3340. return {};
  3341. }
  3342. // 7. Interpret the consumed code points as a hexadecimal number. This is the end value.
  3343. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_hex_digits);
  3344. if (!maybe_end_value.has_value()) {
  3345. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value did not parse as hex number.");
  3346. return {};
  3347. }
  3348. u32 end_value = maybe_end_value.release_value();
  3349. return make_valid_unicode_range(start_value, end_value);
  3350. }
  3351. ErrorOr<RefPtr<StyleValue>> Parser::parse_dimension_value(ComponentValue const& component_value)
  3352. {
  3353. // Numbers with no units can be lengths, in two situations:
  3354. // 1) We're in quirks mode, and it's an integer.
  3355. // 2) It's a 0.
  3356. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  3357. if (component_value.is(Token::Type::Number) && component_value.token().number_value() != 0 && !(m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)))
  3358. return nullptr;
  3359. auto dimension = parse_dimension(component_value);
  3360. if (!dimension.has_value())
  3361. return nullptr;
  3362. if (dimension->is_angle())
  3363. return AngleStyleValue::create(dimension->angle());
  3364. if (dimension->is_frequency())
  3365. return FrequencyStyleValue::create(dimension->frequency());
  3366. if (dimension->is_length())
  3367. return LengthStyleValue::create(dimension->length());
  3368. if (dimension->is_percentage())
  3369. return PercentageStyleValue::create(dimension->percentage());
  3370. if (dimension->is_resolution())
  3371. return ResolutionStyleValue::create(dimension->resolution());
  3372. if (dimension->is_time())
  3373. return TimeStyleValue::create(dimension->time());
  3374. VERIFY_NOT_REACHED();
  3375. }
  3376. ErrorOr<RefPtr<StyleValue>> Parser::parse_integer_value(TokenStream<ComponentValue>& tokens)
  3377. {
  3378. auto peek_token = tokens.peek_token();
  3379. if (peek_token.is(Token::Type::Number) && peek_token.token().number().is_integer()) {
  3380. (void)tokens.next_token();
  3381. return IntegerStyleValue::create(peek_token.token().number().integer_value());
  3382. }
  3383. return nullptr;
  3384. }
  3385. ErrorOr<RefPtr<StyleValue>> Parser::parse_number_value(TokenStream<ComponentValue>& tokens)
  3386. {
  3387. auto peek_token = tokens.peek_token();
  3388. if (peek_token.is(Token::Type::Number)) {
  3389. (void)tokens.next_token();
  3390. return NumberStyleValue::create(peek_token.token().number().value());
  3391. }
  3392. return nullptr;
  3393. }
  3394. ErrorOr<RefPtr<StyleValue>> Parser::parse_identifier_value(ComponentValue const& component_value)
  3395. {
  3396. if (component_value.is(Token::Type::Ident)) {
  3397. auto value_id = value_id_from_string(component_value.token().ident());
  3398. if (value_id.has_value())
  3399. return IdentifierStyleValue::create(value_id.value());
  3400. }
  3401. return nullptr;
  3402. }
  3403. Optional<Color> Parser::parse_rgb_or_hsl_color(StringView function_name, Vector<ComponentValue> const& component_values)
  3404. {
  3405. Token params[4];
  3406. bool legacy_syntax = false;
  3407. auto tokens = TokenStream { component_values };
  3408. tokens.skip_whitespace();
  3409. auto const& component1 = tokens.next_token();
  3410. if (!component1.is(Token::Type::Number)
  3411. && !component1.is(Token::Type::Percentage)
  3412. && !component1.is(Token::Type::Dimension))
  3413. return {};
  3414. params[0] = component1.token();
  3415. tokens.skip_whitespace();
  3416. if (tokens.peek_token().is(Token::Type::Comma)) {
  3417. legacy_syntax = true;
  3418. tokens.next_token();
  3419. }
  3420. tokens.skip_whitespace();
  3421. auto const& component2 = tokens.next_token();
  3422. if (!component2.is(Token::Type::Number) && !component2.is(Token::Type::Percentage))
  3423. return {};
  3424. params[1] = component2.token();
  3425. tokens.skip_whitespace();
  3426. if (legacy_syntax && !tokens.next_token().is(Token::Type::Comma))
  3427. return {};
  3428. tokens.skip_whitespace();
  3429. auto const& component3 = tokens.next_token();
  3430. if (!component3.is(Token::Type::Number) && !component3.is(Token::Type::Percentage))
  3431. return {};
  3432. params[2] = component3.token();
  3433. tokens.skip_whitespace();
  3434. auto const& alpha_separator = tokens.peek_token();
  3435. bool has_comma = alpha_separator.is(Token::Type::Comma);
  3436. bool has_slash = alpha_separator.is_delim('/');
  3437. if (legacy_syntax ? has_comma : has_slash) {
  3438. tokens.next_token();
  3439. tokens.skip_whitespace();
  3440. auto const& component4 = tokens.next_token();
  3441. if (!component4.is(Token::Type::Number) && !component4.is(Token::Type::Percentage))
  3442. return {};
  3443. params[3] = component4.token();
  3444. }
  3445. tokens.skip_whitespace();
  3446. if (tokens.has_next_token())
  3447. return {};
  3448. if (function_name.equals_ignoring_ascii_case("rgb"sv)
  3449. || function_name.equals_ignoring_ascii_case("rgba"sv)) {
  3450. // https://www.w3.org/TR/css-color-4/#rgb-functions
  3451. u8 a_val = 255;
  3452. if (params[3].is(Token::Type::Number))
  3453. a_val = clamp(lroundf(params[3].number_value() * 255.0f), 0, 255);
  3454. else if (params[3].is(Token::Type::Percentage))
  3455. a_val = clamp(lroundf(params[3].percentage() * 2.55f), 0, 255);
  3456. if (params[0].is(Token::Type::Number)
  3457. && params[1].is(Token::Type::Number)
  3458. && params[2].is(Token::Type::Number)) {
  3459. u8 r_val = clamp(llroundf(params[0].number_value()), 0, 255);
  3460. u8 g_val = clamp(llroundf(params[1].number_value()), 0, 255);
  3461. u8 b_val = clamp(llroundf(params[2].number_value()), 0, 255);
  3462. return Color(r_val, g_val, b_val, a_val);
  3463. }
  3464. if (params[0].is(Token::Type::Percentage)
  3465. && params[1].is(Token::Type::Percentage)
  3466. && params[2].is(Token::Type::Percentage)) {
  3467. u8 r_val = lroundf(clamp(params[0].percentage() * 2.55f, 0, 255));
  3468. u8 g_val = lroundf(clamp(params[1].percentage() * 2.55f, 0, 255));
  3469. u8 b_val = lroundf(clamp(params[2].percentage() * 2.55f, 0, 255));
  3470. return Color(r_val, g_val, b_val, a_val);
  3471. }
  3472. } else if (function_name.equals_ignoring_ascii_case("hsl"sv)
  3473. || function_name.equals_ignoring_ascii_case("hsla"sv)) {
  3474. // https://www.w3.org/TR/css-color-4/#the-hsl-notation
  3475. float a_val = 1.0f;
  3476. if (params[3].is(Token::Type::Number))
  3477. a_val = params[3].number_value();
  3478. else if (params[3].is(Token::Type::Percentage))
  3479. a_val = params[3].percentage() / 100.0f;
  3480. if (params[0].is(Token::Type::Dimension)
  3481. && params[1].is(Token::Type::Percentage)
  3482. && params[2].is(Token::Type::Percentage)) {
  3483. float numeric_value = params[0].dimension_value();
  3484. auto unit_string = params[0].dimension_unit();
  3485. auto angle_type = Angle::unit_from_name(unit_string);
  3486. if (!angle_type.has_value())
  3487. return {};
  3488. auto angle = Angle { numeric_value, angle_type.release_value() };
  3489. float h_val = fmodf(angle.to_degrees(), 360.0f);
  3490. float s_val = params[1].percentage() / 100.0f;
  3491. float l_val = params[2].percentage() / 100.0f;
  3492. return Color::from_hsla(h_val, s_val, l_val, a_val);
  3493. }
  3494. if (params[0].is(Token::Type::Number)
  3495. && params[1].is(Token::Type::Percentage)
  3496. && params[2].is(Token::Type::Percentage)) {
  3497. float h_val = fmodf(params[0].number_value(), 360.0f);
  3498. float s_val = params[1].percentage() / 100.0f;
  3499. float l_val = params[2].percentage() / 100.0f;
  3500. return Color::from_hsla(h_val, s_val, l_val, a_val);
  3501. }
  3502. }
  3503. return {};
  3504. }
  3505. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  3506. ErrorOr<RefPtr<StyleValue>> Parser::parse_rect_value(ComponentValue const& component_value)
  3507. {
  3508. if (!component_value.is_function())
  3509. return nullptr;
  3510. auto const& function = component_value.function();
  3511. if (!function.name().equals_ignoring_ascii_case("rect"sv))
  3512. return nullptr;
  3513. Vector<Length, 4> params;
  3514. auto tokens = TokenStream { function.values() };
  3515. enum class CommaRequirement {
  3516. Unknown,
  3517. RequiresCommas,
  3518. RequiresNoCommas
  3519. };
  3520. enum class Side {
  3521. Top = 0,
  3522. Right = 1,
  3523. Bottom = 2,
  3524. Left = 3
  3525. };
  3526. auto comma_requirement = CommaRequirement::Unknown;
  3527. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  3528. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  3529. // <left> specify offsets from the left border edge of the box.
  3530. for (size_t side = 0; side < 4; side++) {
  3531. tokens.skip_whitespace();
  3532. // <top>, <right>, <bottom>, and <left> may either have a <length> value or 'auto'.
  3533. // Negative lengths are permitted.
  3534. auto current_token = tokens.next_token().token();
  3535. if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto"sv)) {
  3536. params.append(Length::make_auto());
  3537. } else {
  3538. auto maybe_length = parse_length(current_token);
  3539. if (!maybe_length.has_value())
  3540. return nullptr;
  3541. params.append(maybe_length.value());
  3542. }
  3543. tokens.skip_whitespace();
  3544. // The last side, should be no more tokens following it.
  3545. if (static_cast<Side>(side) == Side::Left) {
  3546. if (tokens.has_next_token())
  3547. return nullptr;
  3548. break;
  3549. }
  3550. bool next_is_comma = tokens.peek_token().is(Token::Type::Comma);
  3551. // Authors should separate offset values with commas. User agents must support separation
  3552. // with commas, but may also support separation without commas (but not a combination),
  3553. // because a previous revision of this specification was ambiguous in this respect.
  3554. if (comma_requirement == CommaRequirement::Unknown)
  3555. comma_requirement = next_is_comma ? CommaRequirement::RequiresCommas : CommaRequirement::RequiresNoCommas;
  3556. if (comma_requirement == CommaRequirement::RequiresCommas) {
  3557. if (next_is_comma)
  3558. tokens.next_token();
  3559. else
  3560. return nullptr;
  3561. } else if (comma_requirement == CommaRequirement::RequiresNoCommas) {
  3562. if (next_is_comma)
  3563. return nullptr;
  3564. } else {
  3565. VERIFY_NOT_REACHED();
  3566. }
  3567. }
  3568. return RectStyleValue::create(EdgeRect { params[0], params[1], params[2], params[3] });
  3569. }
  3570. Optional<Color> Parser::parse_color(ComponentValue const& component_value)
  3571. {
  3572. // https://www.w3.org/TR/css-color-4/
  3573. if (component_value.is(Token::Type::Ident)) {
  3574. auto ident = component_value.token().ident();
  3575. auto color = Color::from_string(ident);
  3576. if (color.has_value())
  3577. return color;
  3578. } else if (component_value.is(Token::Type::Hash)) {
  3579. auto color = Color::from_string(DeprecatedString::formatted("#{}", component_value.token().hash_value()));
  3580. if (color.has_value())
  3581. return color;
  3582. return {};
  3583. } else if (component_value.is_function()) {
  3584. auto const& function = component_value.function();
  3585. auto const& values = function.values();
  3586. return parse_rgb_or_hsl_color(function.name(), values);
  3587. }
  3588. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  3589. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  3590. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  3591. // aborting on the first step that returns a value:
  3592. // 1. Let cv be the component value.
  3593. auto const& cv = component_value;
  3594. DeprecatedString serialization;
  3595. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  3596. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  3597. // 1. If cv’s type flag is not "integer", return an error.
  3598. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  3599. if (!cv.token().number().is_integer())
  3600. return {};
  3601. // 2. If cv’s value is less than zero, return an error.
  3602. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  3603. if (value < 0)
  3604. return {};
  3605. // 3. Let serialization be the serialization of cv’s value, as a base-ten integer using digits 0-9 (U+0030 to U+0039) in the shortest form possible.
  3606. StringBuilder serialization_builder;
  3607. serialization_builder.appendff("{}", value);
  3608. // 4. If cv is a <dimension-token>, append the unit to serialization.
  3609. if (cv.is(Token::Type::Dimension))
  3610. serialization_builder.append(cv.token().dimension_unit());
  3611. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  3612. serialization = serialization_builder.to_deprecated_string();
  3613. if (serialization_builder.length() < 6) {
  3614. StringBuilder builder;
  3615. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  3616. builder.append('0');
  3617. builder.append(serialization_builder.string_view());
  3618. serialization = builder.to_deprecated_string();
  3619. }
  3620. }
  3621. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  3622. else {
  3623. if (!cv.is(Token::Type::Ident))
  3624. return {};
  3625. serialization = cv.token().ident();
  3626. }
  3627. // 4. If serialization does not consist of three or six characters, return an error.
  3628. if (serialization.length() != 3 && serialization.length() != 6)
  3629. return {};
  3630. // 5. If serialization contains any characters not in the range [0-9A-Fa-f] (U+0030 to U+0039, U+0041 to U+0046, U+0061 to U+0066), return an error.
  3631. for (auto c : serialization) {
  3632. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  3633. return {};
  3634. }
  3635. // 6. Return the concatenation of "#" (U+0023) and serialization.
  3636. DeprecatedString concatenation = DeprecatedString::formatted("#{}", serialization);
  3637. return Color::from_string(concatenation);
  3638. }
  3639. return {};
  3640. }
  3641. ErrorOr<RefPtr<StyleValue>> Parser::parse_color_value(ComponentValue const& component_value)
  3642. {
  3643. auto color = parse_color(component_value);
  3644. if (color.has_value())
  3645. return ColorStyleValue::create(color.value());
  3646. if (component_value.is(Token::Type::Ident)) {
  3647. if (auto ident = value_id_from_string(component_value.token().ident()); ident.has_value()) {
  3648. switch (ident.value()) {
  3649. case ValueID::Currentcolor:
  3650. case ValueID::LibwebLink:
  3651. case ValueID::LibwebPaletteActiveLink:
  3652. case ValueID::LibwebPaletteActiveWindowBorder1:
  3653. case ValueID::LibwebPaletteActiveWindowBorder2:
  3654. case ValueID::LibwebPaletteActiveWindowTitle:
  3655. case ValueID::LibwebPaletteBase:
  3656. case ValueID::LibwebPaletteBaseText:
  3657. case ValueID::LibwebPaletteButton:
  3658. case ValueID::LibwebPaletteButtonText:
  3659. case ValueID::LibwebPaletteDesktopBackground:
  3660. case ValueID::LibwebPaletteFocusOutline:
  3661. case ValueID::LibwebPaletteHighlightWindowBorder1:
  3662. case ValueID::LibwebPaletteHighlightWindowBorder2:
  3663. case ValueID::LibwebPaletteHighlightWindowTitle:
  3664. case ValueID::LibwebPaletteHoverHighlight:
  3665. case ValueID::LibwebPaletteInactiveSelection:
  3666. case ValueID::LibwebPaletteInactiveSelectionText:
  3667. case ValueID::LibwebPaletteInactiveWindowBorder1:
  3668. case ValueID::LibwebPaletteInactiveWindowBorder2:
  3669. case ValueID::LibwebPaletteInactiveWindowTitle:
  3670. case ValueID::LibwebPaletteLink:
  3671. case ValueID::LibwebPaletteMenuBase:
  3672. case ValueID::LibwebPaletteMenuBaseText:
  3673. case ValueID::LibwebPaletteMenuSelection:
  3674. case ValueID::LibwebPaletteMenuSelectionText:
  3675. case ValueID::LibwebPaletteMenuStripe:
  3676. case ValueID::LibwebPaletteMovingWindowBorder1:
  3677. case ValueID::LibwebPaletteMovingWindowBorder2:
  3678. case ValueID::LibwebPaletteMovingWindowTitle:
  3679. case ValueID::LibwebPaletteRubberBandBorder:
  3680. case ValueID::LibwebPaletteRubberBandFill:
  3681. case ValueID::LibwebPaletteRuler:
  3682. case ValueID::LibwebPaletteRulerActiveText:
  3683. case ValueID::LibwebPaletteRulerBorder:
  3684. case ValueID::LibwebPaletteRulerInactiveText:
  3685. case ValueID::LibwebPaletteSelection:
  3686. case ValueID::LibwebPaletteSelectionText:
  3687. case ValueID::LibwebPaletteSyntaxComment:
  3688. case ValueID::LibwebPaletteSyntaxControlKeyword:
  3689. case ValueID::LibwebPaletteSyntaxIdentifier:
  3690. case ValueID::LibwebPaletteSyntaxKeyword:
  3691. case ValueID::LibwebPaletteSyntaxNumber:
  3692. case ValueID::LibwebPaletteSyntaxOperator:
  3693. case ValueID::LibwebPaletteSyntaxPreprocessorStatement:
  3694. case ValueID::LibwebPaletteSyntaxPreprocessorValue:
  3695. case ValueID::LibwebPaletteSyntaxPunctuation:
  3696. case ValueID::LibwebPaletteSyntaxString:
  3697. case ValueID::LibwebPaletteSyntaxType:
  3698. case ValueID::LibwebPaletteTextCursor:
  3699. case ValueID::LibwebPaletteThreedHighlight:
  3700. case ValueID::LibwebPaletteThreedShadow1:
  3701. case ValueID::LibwebPaletteThreedShadow2:
  3702. case ValueID::LibwebPaletteVisitedLink:
  3703. case ValueID::LibwebPaletteWindow:
  3704. case ValueID::LibwebPaletteWindowText:
  3705. return IdentifierStyleValue::create(ident.value());
  3706. default:
  3707. break;
  3708. }
  3709. }
  3710. }
  3711. return nullptr;
  3712. }
  3713. ErrorOr<RefPtr<StyleValue>> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  3714. {
  3715. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  3716. return RatioStyleValue::create(ratio.release_value());
  3717. return nullptr;
  3718. }
  3719. ErrorOr<RefPtr<StyleValue>> Parser::parse_string_value(ComponentValue const& component_value)
  3720. {
  3721. if (component_value.is(Token::Type::String))
  3722. return StringStyleValue::create(TRY(String::from_utf8(component_value.token().string())));
  3723. return nullptr;
  3724. }
  3725. ErrorOr<RefPtr<StyleValue>> Parser::parse_image_value(ComponentValue const& component_value)
  3726. {
  3727. auto url = parse_url_function(component_value);
  3728. if (url.has_value())
  3729. return ImageStyleValue::create(url.value());
  3730. auto linear_gradient = TRY(parse_linear_gradient_function(component_value));
  3731. if (linear_gradient)
  3732. return linear_gradient;
  3733. auto conic_gradient = TRY(parse_conic_gradient_function(component_value));
  3734. if (conic_gradient)
  3735. return conic_gradient;
  3736. return parse_radial_gradient_function(component_value);
  3737. }
  3738. // https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint
  3739. ErrorOr<RefPtr<StyleValue>> Parser::parse_paint_value(TokenStream<ComponentValue>& tokens)
  3740. {
  3741. // `<paint> = none | <color> | <url> [none | <color>]? | context-fill | context-stroke`
  3742. auto parse_color_or_none = [&]() -> ErrorOr<Optional<RefPtr<StyleValue>>> {
  3743. if (auto color = TRY(parse_color_value(tokens.peek_token()))) {
  3744. (void)tokens.next_token();
  3745. return color;
  3746. }
  3747. // NOTE: <color> also accepts identifiers, so we do this identifier check last.
  3748. if (tokens.peek_token().is(Token::Type::Ident)) {
  3749. auto maybe_ident = value_id_from_string(tokens.peek_token().token().ident());
  3750. if (maybe_ident.has_value()) {
  3751. // FIXME: Accept `context-fill` and `context-stroke`
  3752. switch (*maybe_ident) {
  3753. case ValueID::None:
  3754. (void)tokens.next_token();
  3755. return IdentifierStyleValue::create(*maybe_ident);
  3756. default:
  3757. return nullptr;
  3758. }
  3759. }
  3760. }
  3761. return OptionalNone {};
  3762. };
  3763. // FIMXE: Allow context-fill/context-stroke here
  3764. if (auto color_or_none = TRY(parse_color_or_none()); color_or_none.has_value())
  3765. return *color_or_none;
  3766. if (auto url = TRY(parse_url_value(tokens.peek_token()))) {
  3767. (void)tokens.next_token();
  3768. tokens.skip_whitespace();
  3769. if (auto color_or_none = TRY(parse_color_or_none()); color_or_none == nullptr) {
  3770. // Fail to parse if the fallback is invalid, but otherwise ignore it.
  3771. // FIXME: Use fallback color
  3772. return nullptr;
  3773. }
  3774. return url;
  3775. }
  3776. return nullptr;
  3777. }
  3778. template<typename ParseFunction>
  3779. ErrorOr<RefPtr<StyleValue>> Parser::parse_comma_separated_value_list(Vector<ComponentValue> const& component_values, ParseFunction parse_one_value)
  3780. {
  3781. auto tokens = TokenStream { component_values };
  3782. auto first = TRY(parse_one_value(tokens));
  3783. if (!first || !tokens.has_next_token())
  3784. return first;
  3785. StyleValueVector values;
  3786. values.append(first.release_nonnull());
  3787. while (tokens.has_next_token()) {
  3788. if (!tokens.next_token().is(Token::Type::Comma))
  3789. return nullptr;
  3790. if (auto maybe_value = TRY(parse_one_value(tokens))) {
  3791. values.append(maybe_value.release_nonnull());
  3792. continue;
  3793. }
  3794. return nullptr;
  3795. }
  3796. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  3797. }
  3798. ErrorOr<RefPtr<StyleValue>> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, Vector<ComponentValue> const& component_values)
  3799. {
  3800. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> ErrorOr<RefPtr<StyleValue>> {
  3801. if (auto value = TRY(parse_css_value_for_property(property_id, tokens)))
  3802. return value;
  3803. tokens.reconsume_current_input_token();
  3804. return nullptr;
  3805. });
  3806. }
  3807. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  3808. {
  3809. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  3810. }
  3811. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  3812. ErrorOr<RefPtr<StyleValue>> Parser::parse_aspect_ratio_value(Vector<ComponentValue> const& component_values)
  3813. {
  3814. // `auto || <ratio>`
  3815. RefPtr<StyleValue> auto_value;
  3816. RefPtr<StyleValue> ratio_value;
  3817. auto tokens = TokenStream { component_values };
  3818. while (tokens.has_next_token()) {
  3819. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::AspectRatio, tokens));
  3820. if (!maybe_value)
  3821. return nullptr;
  3822. if (maybe_value->is_ratio()) {
  3823. if (ratio_value)
  3824. return nullptr;
  3825. ratio_value = maybe_value.release_nonnull();
  3826. continue;
  3827. }
  3828. if (maybe_value->is_identifier() && maybe_value->as_identifier().id() == ValueID::Auto) {
  3829. if (auto_value)
  3830. return nullptr;
  3831. auto_value = maybe_value.release_nonnull();
  3832. continue;
  3833. }
  3834. return nullptr;
  3835. }
  3836. if (auto_value && ratio_value) {
  3837. return TRY(StyleValueList::create(
  3838. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  3839. StyleValueList::Separator::Space));
  3840. }
  3841. if (ratio_value)
  3842. return ratio_value.release_nonnull();
  3843. if (auto_value)
  3844. return auto_value.release_nonnull();
  3845. return nullptr;
  3846. }
  3847. ErrorOr<RefPtr<StyleValue>> Parser::parse_background_value(Vector<ComponentValue> const& component_values)
  3848. {
  3849. StyleValueVector background_images;
  3850. StyleValueVector background_positions;
  3851. StyleValueVector background_sizes;
  3852. StyleValueVector background_repeats;
  3853. StyleValueVector background_attachments;
  3854. StyleValueVector background_clips;
  3855. StyleValueVector background_origins;
  3856. RefPtr<StyleValue> background_color;
  3857. auto initial_background_image = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundImage));
  3858. auto initial_background_position = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundPosition));
  3859. auto initial_background_size = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundSize));
  3860. auto initial_background_repeat = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat));
  3861. auto initial_background_attachment = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment));
  3862. auto initial_background_clip = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundClip));
  3863. auto initial_background_origin = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin));
  3864. auto initial_background_color = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundColor));
  3865. // Per-layer values
  3866. RefPtr<StyleValue> background_image;
  3867. RefPtr<StyleValue> background_position;
  3868. RefPtr<StyleValue> background_size;
  3869. RefPtr<StyleValue> background_repeat;
  3870. RefPtr<StyleValue> background_attachment;
  3871. RefPtr<StyleValue> background_clip;
  3872. RefPtr<StyleValue> background_origin;
  3873. bool has_multiple_layers = false;
  3874. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  3875. Vector<PropertyID> remaining_layer_properties {
  3876. PropertyID::BackgroundAttachment,
  3877. PropertyID::BackgroundClip,
  3878. PropertyID::BackgroundColor,
  3879. PropertyID::BackgroundImage,
  3880. PropertyID::BackgroundOrigin,
  3881. PropertyID::BackgroundPosition,
  3882. PropertyID::BackgroundRepeat,
  3883. };
  3884. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  3885. if (allow_background_color) {
  3886. if (background_color)
  3887. return true;
  3888. } else {
  3889. if (background_color)
  3890. return false;
  3891. }
  3892. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  3893. };
  3894. auto complete_background_layer = [&]() -> ErrorOr<void> {
  3895. TRY(background_images.try_append(background_image ? background_image.release_nonnull() : initial_background_image));
  3896. TRY(background_positions.try_append(background_position ? background_position.release_nonnull() : initial_background_position));
  3897. TRY(background_sizes.try_append(background_size ? background_size.release_nonnull() : initial_background_size));
  3898. TRY(background_repeats.try_append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat));
  3899. TRY(background_attachments.try_append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment));
  3900. if (!background_origin && !background_clip) {
  3901. background_origin = initial_background_origin;
  3902. background_clip = initial_background_clip;
  3903. } else if (!background_clip) {
  3904. background_clip = background_origin;
  3905. }
  3906. TRY(background_origins.try_append(background_origin.release_nonnull()));
  3907. TRY(background_clips.try_append(background_clip.release_nonnull()));
  3908. background_image = nullptr;
  3909. background_position = nullptr;
  3910. background_size = nullptr;
  3911. background_repeat = nullptr;
  3912. background_attachment = nullptr;
  3913. background_clip = nullptr;
  3914. background_origin = nullptr;
  3915. remaining_layer_properties.clear_with_capacity();
  3916. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  3917. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  3918. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  3919. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  3920. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  3921. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  3922. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  3923. return {};
  3924. };
  3925. auto tokens = TokenStream { component_values };
  3926. while (tokens.has_next_token()) {
  3927. if (tokens.peek_token().is(Token::Type::Comma)) {
  3928. has_multiple_layers = true;
  3929. if (!background_layer_is_valid(false))
  3930. return nullptr;
  3931. TRY(complete_background_layer());
  3932. (void)tokens.next_token();
  3933. continue;
  3934. }
  3935. auto value_and_property = TRY(parse_css_value_for_properties(remaining_layer_properties, tokens));
  3936. if (!value_and_property.style_value)
  3937. return nullptr;
  3938. auto& value = value_and_property.style_value;
  3939. remove_property(remaining_layer_properties, value_and_property.property);
  3940. switch (value_and_property.property) {
  3941. case PropertyID::BackgroundAttachment:
  3942. VERIFY(!background_attachment);
  3943. background_attachment = value.release_nonnull();
  3944. continue;
  3945. case PropertyID::BackgroundColor:
  3946. VERIFY(!background_color);
  3947. background_color = value.release_nonnull();
  3948. continue;
  3949. case PropertyID::BackgroundImage:
  3950. VERIFY(!background_image);
  3951. background_image = value.release_nonnull();
  3952. continue;
  3953. case PropertyID::BackgroundClip:
  3954. case PropertyID::BackgroundOrigin: {
  3955. // background-origin and background-clip accept the same values. From the spec:
  3956. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  3957. // If two values are present, then the first sets background-origin and the second background-clip."
  3958. // - https://www.w3.org/TR/css-backgrounds-3/#background
  3959. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  3960. // If we only get one, we copy the value before creating the BackgroundStyleValue.
  3961. if (!background_origin) {
  3962. background_origin = value.release_nonnull();
  3963. } else if (!background_clip) {
  3964. background_clip = value.release_nonnull();
  3965. } else {
  3966. VERIFY_NOT_REACHED();
  3967. }
  3968. continue;
  3969. }
  3970. case PropertyID::BackgroundPosition: {
  3971. VERIFY(!background_position);
  3972. tokens.reconsume_current_input_token();
  3973. if (auto maybe_background_position = TRY(parse_single_background_position_value(tokens))) {
  3974. background_position = maybe_background_position.release_nonnull();
  3975. // Attempt to parse `/ <background-size>`
  3976. auto transaction = tokens.begin_transaction();
  3977. auto& maybe_slash = tokens.next_token();
  3978. if (maybe_slash.is_delim('/')) {
  3979. if (auto maybe_background_size = TRY(parse_single_background_size_value(tokens))) {
  3980. transaction.commit();
  3981. background_size = maybe_background_size.release_nonnull();
  3982. continue;
  3983. }
  3984. return nullptr;
  3985. }
  3986. continue;
  3987. }
  3988. return nullptr;
  3989. }
  3990. case PropertyID::BackgroundRepeat: {
  3991. VERIFY(!background_repeat);
  3992. tokens.reconsume_current_input_token();
  3993. if (auto maybe_repeat = TRY(parse_single_background_repeat_value(tokens))) {
  3994. background_repeat = maybe_repeat.release_nonnull();
  3995. continue;
  3996. }
  3997. return nullptr;
  3998. }
  3999. default:
  4000. VERIFY_NOT_REACHED();
  4001. }
  4002. return nullptr;
  4003. }
  4004. if (!background_layer_is_valid(true))
  4005. return nullptr;
  4006. // We only need to create StyleValueLists if there are multiple layers.
  4007. // Otherwise, we can pass the single StyleValues directly.
  4008. if (has_multiple_layers) {
  4009. TRY(complete_background_layer());
  4010. if (!background_color)
  4011. background_color = initial_background_color;
  4012. return BackgroundStyleValue::create(
  4013. background_color.release_nonnull(),
  4014. TRY(StyleValueList::create(move(background_images), StyleValueList::Separator::Comma)),
  4015. TRY(StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma)),
  4016. TRY(StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma)),
  4017. TRY(StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma)),
  4018. TRY(StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma)),
  4019. TRY(StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma)),
  4020. TRY(StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma)));
  4021. }
  4022. if (!background_color)
  4023. background_color = initial_background_color;
  4024. if (!background_image)
  4025. background_image = initial_background_image;
  4026. if (!background_position)
  4027. background_position = initial_background_position;
  4028. if (!background_size)
  4029. background_size = initial_background_size;
  4030. if (!background_repeat)
  4031. background_repeat = initial_background_repeat;
  4032. if (!background_attachment)
  4033. background_attachment = initial_background_attachment;
  4034. if (!background_origin && !background_clip) {
  4035. background_origin = initial_background_origin;
  4036. background_clip = initial_background_clip;
  4037. } else if (!background_clip) {
  4038. background_clip = background_origin;
  4039. }
  4040. return BackgroundStyleValue::create(
  4041. background_color.release_nonnull(),
  4042. background_image.release_nonnull(),
  4043. background_position.release_nonnull(),
  4044. background_size.release_nonnull(),
  4045. background_repeat.release_nonnull(),
  4046. background_attachment.release_nonnull(),
  4047. background_origin.release_nonnull(),
  4048. background_clip.release_nonnull());
  4049. }
  4050. static Optional<PositionEdge> identifier_to_edge(ValueID identifier)
  4051. {
  4052. switch (identifier) {
  4053. case ValueID::Top:
  4054. return PositionEdge::Top;
  4055. case ValueID::Bottom:
  4056. return PositionEdge::Bottom;
  4057. case ValueID::Left:
  4058. return PositionEdge::Left;
  4059. case ValueID::Right:
  4060. return PositionEdge::Right;
  4061. default:
  4062. return {};
  4063. }
  4064. }
  4065. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  4066. {
  4067. if (value->is_percentage())
  4068. return LengthPercentage { value->as_percentage().percentage() };
  4069. if (value->is_length())
  4070. return LengthPercentage { value->as_length().length() };
  4071. if (value->is_calculated())
  4072. return LengthPercentage { value->as_calculated() };
  4073. return {};
  4074. }
  4075. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_position_value(TokenStream<ComponentValue>& tokens)
  4076. {
  4077. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  4078. // "Note: The background-position property also accepts a three-value syntax.
  4079. // This has been disallowed generically because it creates parsing ambiguities
  4080. // when combined with other length or percentage components in a property value."
  4081. // - https://www.w3.org/TR/css-values-4/#typedef-position
  4082. // So, we'll need a separate function to parse <position> later.
  4083. auto transaction = tokens.begin_transaction();
  4084. auto is_horizontal = [](ValueID identifier) -> bool {
  4085. switch (identifier) {
  4086. case ValueID::Left:
  4087. case ValueID::Right:
  4088. return true;
  4089. default:
  4090. return false;
  4091. }
  4092. };
  4093. auto is_vertical = [](ValueID identifier) -> bool {
  4094. switch (identifier) {
  4095. case ValueID::Top:
  4096. case ValueID::Bottom:
  4097. return true;
  4098. default:
  4099. return false;
  4100. }
  4101. };
  4102. struct EdgeOffset {
  4103. PositionEdge edge;
  4104. LengthPercentage offset;
  4105. bool edge_provided;
  4106. bool offset_provided;
  4107. };
  4108. Optional<EdgeOffset> horizontal;
  4109. Optional<EdgeOffset> vertical;
  4110. bool found_center = false;
  4111. auto const center_offset = Percentage { 50 };
  4112. auto const zero_offset = Length::make_px(0);
  4113. while (tokens.has_next_token()) {
  4114. // Check if we're done
  4115. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  4116. if (seen_items == 2)
  4117. break;
  4118. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::BackgroundPosition, tokens));
  4119. if (!maybe_value)
  4120. break;
  4121. auto value = maybe_value.release_nonnull();
  4122. if (auto offset = style_value_to_length_percentage(value); offset.has_value()) {
  4123. if (!horizontal.has_value()) {
  4124. horizontal = EdgeOffset { PositionEdge::Left, *offset, false, true };
  4125. } else if (!vertical.has_value()) {
  4126. vertical = EdgeOffset { PositionEdge::Top, *offset, false, true };
  4127. } else {
  4128. return nullptr;
  4129. }
  4130. continue;
  4131. }
  4132. auto try_parse_offset = [&](bool& offset_provided) -> ErrorOr<LengthPercentage> {
  4133. auto transaction = tokens.begin_transaction();
  4134. if (tokens.has_next_token()) {
  4135. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::BackgroundPosition, tokens));
  4136. if (!maybe_value)
  4137. return zero_offset;
  4138. auto offset = style_value_to_length_percentage(maybe_value.release_nonnull());
  4139. if (offset.has_value()) {
  4140. offset_provided = true;
  4141. transaction.commit();
  4142. return *offset;
  4143. }
  4144. }
  4145. return zero_offset;
  4146. };
  4147. if (value->is_identifier()) {
  4148. auto identifier = value->to_identifier();
  4149. if (is_horizontal(identifier)) {
  4150. bool offset_provided = false;
  4151. auto offset = TRY(try_parse_offset(offset_provided));
  4152. horizontal = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  4153. } else if (is_vertical(identifier)) {
  4154. bool offset_provided = false;
  4155. auto offset = TRY(try_parse_offset(offset_provided));
  4156. vertical = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  4157. } else if (identifier == ValueID::Center) {
  4158. found_center = true;
  4159. } else {
  4160. return nullptr;
  4161. }
  4162. continue;
  4163. }
  4164. tokens.reconsume_current_input_token();
  4165. break;
  4166. }
  4167. if (found_center) {
  4168. if (horizontal.has_value() && vertical.has_value())
  4169. return nullptr;
  4170. if (!horizontal.has_value())
  4171. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  4172. if (!vertical.has_value())
  4173. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  4174. }
  4175. if (!horizontal.has_value() && !vertical.has_value())
  4176. return nullptr;
  4177. // Unpack `<edge> <length>`:
  4178. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  4179. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  4180. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  4181. // Split into `x y`
  4182. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  4183. horizontal->offset = zero_offset;
  4184. horizontal->offset_provided = false;
  4185. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  4186. // `y`, reconsume
  4187. vertical->offset = zero_offset;
  4188. vertical->offset_provided = false;
  4189. tokens.reconsume_current_input_token();
  4190. }
  4191. // If only one value is specified, the second value is assumed to be center.
  4192. if (!horizontal.has_value())
  4193. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  4194. if (!vertical.has_value())
  4195. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  4196. transaction.commit();
  4197. return PositionStyleValue::create(
  4198. TRY(EdgeStyleValue::create(horizontal->edge, horizontal->offset)),
  4199. TRY(EdgeStyleValue::create(vertical->edge, vertical->offset)));
  4200. }
  4201. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  4202. {
  4203. PositionEdge relative_edge {};
  4204. if (property == PropertyID::BackgroundPositionX) {
  4205. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  4206. relative_edge = PositionEdge::Left;
  4207. } else if (property == PropertyID::BackgroundPositionY) {
  4208. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  4209. relative_edge = PositionEdge::Top;
  4210. } else {
  4211. VERIFY_NOT_REACHED();
  4212. }
  4213. auto transaction = tokens.begin_transaction();
  4214. if (!tokens.has_next_token())
  4215. return nullptr;
  4216. auto value = TRY(parse_css_value_for_property(property, tokens));
  4217. if (!value)
  4218. return nullptr;
  4219. if (value->is_identifier()) {
  4220. auto identifier = value->to_identifier();
  4221. if (identifier == ValueID::Center) {
  4222. transaction.commit();
  4223. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  4224. }
  4225. if (auto edge = identifier_to_edge(identifier); edge.has_value()) {
  4226. relative_edge = *edge;
  4227. } else {
  4228. return nullptr;
  4229. }
  4230. if (tokens.has_next_token()) {
  4231. value = TRY(parse_css_value_for_property(property, tokens));
  4232. if (!value) {
  4233. transaction.commit();
  4234. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  4235. }
  4236. }
  4237. }
  4238. auto offset = style_value_to_length_percentage(value);
  4239. if (offset.has_value()) {
  4240. transaction.commit();
  4241. return EdgeStyleValue::create(relative_edge, *offset);
  4242. }
  4243. // If no offset is provided create this element but with an offset of default value of zero
  4244. transaction.commit();
  4245. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  4246. }
  4247. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  4248. {
  4249. auto transaction = tokens.begin_transaction();
  4250. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  4251. auto value_id = value.to_identifier();
  4252. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  4253. };
  4254. auto as_repeat = [](ValueID identifier) -> Optional<Repeat> {
  4255. switch (identifier) {
  4256. case ValueID::NoRepeat:
  4257. return Repeat::NoRepeat;
  4258. case ValueID::Repeat:
  4259. return Repeat::Repeat;
  4260. case ValueID::Round:
  4261. return Repeat::Round;
  4262. case ValueID::Space:
  4263. return Repeat::Space;
  4264. default:
  4265. return {};
  4266. }
  4267. };
  4268. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens));
  4269. if (!maybe_x_value)
  4270. return nullptr;
  4271. auto x_value = maybe_x_value.release_nonnull();
  4272. if (is_directional_repeat(*x_value)) {
  4273. auto value_id = x_value->to_identifier();
  4274. transaction.commit();
  4275. return BackgroundRepeatStyleValue::create(
  4276. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  4277. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  4278. }
  4279. auto x_repeat = as_repeat(x_value->to_identifier());
  4280. if (!x_repeat.has_value())
  4281. return nullptr;
  4282. // See if we have a second value for Y
  4283. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens));
  4284. if (!maybe_y_value) {
  4285. // We don't have a second value, so use x for both
  4286. transaction.commit();
  4287. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  4288. }
  4289. auto y_value = maybe_y_value.release_nonnull();
  4290. if (is_directional_repeat(*y_value))
  4291. return nullptr;
  4292. auto y_repeat = as_repeat(y_value->to_identifier());
  4293. if (!y_repeat.has_value())
  4294. return nullptr;
  4295. transaction.commit();
  4296. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  4297. }
  4298. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  4299. {
  4300. auto transaction = tokens.begin_transaction();
  4301. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  4302. if (style_value.has_auto())
  4303. return LengthPercentage { Length::make_auto() };
  4304. if (style_value.is_percentage())
  4305. return LengthPercentage { style_value.as_percentage().percentage() };
  4306. if (style_value.is_length())
  4307. return LengthPercentage { style_value.as_length().length() };
  4308. return {};
  4309. };
  4310. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::BackgroundSize, tokens));
  4311. if (!maybe_x_value)
  4312. return nullptr;
  4313. auto x_value = maybe_x_value.release_nonnull();
  4314. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain) {
  4315. transaction.commit();
  4316. return x_value;
  4317. }
  4318. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::BackgroundSize, tokens));
  4319. if (!maybe_y_value) {
  4320. auto y_value = LengthPercentage { Length::make_auto() };
  4321. auto x_size = get_length_percentage(*x_value);
  4322. if (!x_size.has_value())
  4323. return nullptr;
  4324. transaction.commit();
  4325. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  4326. }
  4327. auto y_value = maybe_y_value.release_nonnull();
  4328. auto x_size = get_length_percentage(*x_value);
  4329. auto y_size = get_length_percentage(*y_value);
  4330. if (!x_size.has_value() || !y_size.has_value())
  4331. return nullptr;
  4332. transaction.commit();
  4333. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  4334. }
  4335. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_value(Vector<ComponentValue> const& component_values)
  4336. {
  4337. if (component_values.size() > 3)
  4338. return nullptr;
  4339. RefPtr<StyleValue> border_width;
  4340. RefPtr<StyleValue> border_color;
  4341. RefPtr<StyleValue> border_style;
  4342. auto remaining_longhands = Vector { PropertyID::BorderWidth, PropertyID::BorderColor, PropertyID::BorderStyle };
  4343. auto tokens = TokenStream { component_values };
  4344. while (tokens.has_next_token()) {
  4345. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  4346. if (!property_and_value.style_value)
  4347. return nullptr;
  4348. auto& value = property_and_value.style_value;
  4349. remove_property(remaining_longhands, property_and_value.property);
  4350. switch (property_and_value.property) {
  4351. case PropertyID::BorderWidth: {
  4352. VERIFY(!border_width);
  4353. border_width = value.release_nonnull();
  4354. continue;
  4355. }
  4356. case PropertyID::BorderColor: {
  4357. VERIFY(!border_color);
  4358. border_color = value.release_nonnull();
  4359. continue;
  4360. }
  4361. case PropertyID::BorderStyle: {
  4362. VERIFY(!border_style);
  4363. border_style = value.release_nonnull();
  4364. continue;
  4365. }
  4366. default:
  4367. VERIFY_NOT_REACHED();
  4368. }
  4369. }
  4370. if (!border_width)
  4371. border_width = TRY(property_initial_value(m_context.realm(), PropertyID::BorderWidth));
  4372. if (!border_style)
  4373. border_style = TRY(property_initial_value(m_context.realm(), PropertyID::BorderStyle));
  4374. if (!border_color)
  4375. border_color = TRY(property_initial_value(m_context.realm(), PropertyID::BorderColor));
  4376. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  4377. }
  4378. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_radius_value(Vector<ComponentValue> const& component_values)
  4379. {
  4380. if (component_values.size() == 2) {
  4381. auto horizontal = parse_dimension(component_values[0]);
  4382. auto vertical = parse_dimension(component_values[1]);
  4383. if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage())
  4384. return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());
  4385. return nullptr;
  4386. }
  4387. if (component_values.size() == 1) {
  4388. auto radius = parse_dimension(component_values[0]);
  4389. if (radius.has_value() && radius->is_length_percentage())
  4390. return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
  4391. return nullptr;
  4392. }
  4393. return nullptr;
  4394. }
  4395. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_radius_shorthand_value(Vector<ComponentValue> const& component_values)
  4396. {
  4397. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  4398. auto top_right = [&](Vector<LengthPercentage>& radii) {
  4399. switch (radii.size()) {
  4400. case 4:
  4401. case 3:
  4402. case 2:
  4403. return radii[1];
  4404. case 1:
  4405. return radii[0];
  4406. default:
  4407. VERIFY_NOT_REACHED();
  4408. }
  4409. };
  4410. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  4411. switch (radii.size()) {
  4412. case 4:
  4413. case 3:
  4414. return radii[2];
  4415. case 2:
  4416. case 1:
  4417. return radii[0];
  4418. default:
  4419. VERIFY_NOT_REACHED();
  4420. }
  4421. };
  4422. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  4423. switch (radii.size()) {
  4424. case 4:
  4425. return radii[3];
  4426. case 3:
  4427. case 2:
  4428. return radii[1];
  4429. case 1:
  4430. return radii[0];
  4431. default:
  4432. VERIFY_NOT_REACHED();
  4433. }
  4434. };
  4435. Vector<LengthPercentage> horizontal_radii;
  4436. Vector<LengthPercentage> vertical_radii;
  4437. bool reading_vertical = false;
  4438. for (auto const& value : component_values) {
  4439. if (value.is_delim('/')) {
  4440. if (reading_vertical || horizontal_radii.is_empty())
  4441. return nullptr;
  4442. reading_vertical = true;
  4443. continue;
  4444. }
  4445. auto maybe_dimension = parse_dimension(value);
  4446. if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
  4447. return nullptr;
  4448. if (reading_vertical) {
  4449. vertical_radii.append(maybe_dimension->length_percentage());
  4450. } else {
  4451. horizontal_radii.append(maybe_dimension->length_percentage());
  4452. }
  4453. }
  4454. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  4455. || horizontal_radii.is_empty()
  4456. || (reading_vertical && vertical_radii.is_empty()))
  4457. return nullptr;
  4458. auto top_left_radius = TRY(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  4459. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  4460. auto top_right_radius = TRY(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  4461. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  4462. auto bottom_right_radius = TRY(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  4463. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  4464. auto bottom_left_radius = TRY(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  4465. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  4466. return BorderRadiusShorthandStyleValue::create(move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius));
  4467. }
  4468. ErrorOr<RefPtr<StyleValue>> Parser::parse_shadow_value(Vector<ComponentValue> const& component_values, AllowInsetKeyword allow_inset_keyword)
  4469. {
  4470. // "none"
  4471. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  4472. auto ident = TRY(parse_identifier_value(component_values.first()));
  4473. if (ident && ident->to_identifier() == ValueID::None)
  4474. return ident;
  4475. }
  4476. return parse_comma_separated_value_list(component_values, [this, allow_inset_keyword](auto& tokens) {
  4477. return parse_single_shadow_value(tokens, allow_inset_keyword);
  4478. });
  4479. }
  4480. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  4481. {
  4482. auto transaction = tokens.begin_transaction();
  4483. Optional<Color> color;
  4484. RefPtr<StyleValue> offset_x;
  4485. RefPtr<StyleValue> offset_y;
  4486. RefPtr<StyleValue> blur_radius;
  4487. RefPtr<StyleValue> spread_distance;
  4488. Optional<ShadowPlacement> placement;
  4489. auto possibly_dynamic_length = [&](ComponentValue const& token) -> ErrorOr<RefPtr<StyleValue>> {
  4490. if (auto maybe_dynamic_value = TRY(parse_dynamic_value(token))) {
  4491. if (!maybe_dynamic_value->is_calculated())
  4492. return nullptr;
  4493. auto const& calculated_value = maybe_dynamic_value->as_calculated();
  4494. if (!calculated_value.resolves_to_length())
  4495. return nullptr;
  4496. return calculated_value;
  4497. }
  4498. auto maybe_length = parse_length(token);
  4499. if (!maybe_length.has_value())
  4500. return nullptr;
  4501. return LengthStyleValue::create(maybe_length.release_value());
  4502. };
  4503. while (tokens.has_next_token()) {
  4504. auto const& token = tokens.peek_token();
  4505. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  4506. if (color.has_value())
  4507. return nullptr;
  4508. color = maybe_color.release_value();
  4509. tokens.next_token();
  4510. continue;
  4511. }
  4512. if (auto maybe_offset_x = TRY(possibly_dynamic_length(token)); maybe_offset_x) {
  4513. // horizontal offset
  4514. if (offset_x)
  4515. return nullptr;
  4516. offset_x = maybe_offset_x;
  4517. tokens.next_token();
  4518. // vertical offset
  4519. if (!tokens.has_next_token())
  4520. return nullptr;
  4521. auto maybe_offset_y = TRY(possibly_dynamic_length(tokens.peek_token()));
  4522. if (!maybe_offset_y)
  4523. return nullptr;
  4524. offset_y = maybe_offset_y;
  4525. tokens.next_token();
  4526. // blur radius (optional)
  4527. if (!tokens.has_next_token())
  4528. break;
  4529. auto maybe_blur_radius = TRY(possibly_dynamic_length(tokens.peek_token()));
  4530. if (!maybe_blur_radius)
  4531. continue;
  4532. blur_radius = maybe_blur_radius;
  4533. tokens.next_token();
  4534. // spread distance (optional)
  4535. if (!tokens.has_next_token())
  4536. break;
  4537. auto maybe_spread_distance = TRY(possibly_dynamic_length(tokens.peek_token()));
  4538. if (!maybe_spread_distance)
  4539. continue;
  4540. spread_distance = maybe_spread_distance;
  4541. tokens.next_token();
  4542. continue;
  4543. }
  4544. if (allow_inset_keyword == AllowInsetKeyword::Yes
  4545. && token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("inset"sv)) {
  4546. if (placement.has_value())
  4547. return nullptr;
  4548. placement = ShadowPlacement::Inner;
  4549. tokens.next_token();
  4550. continue;
  4551. }
  4552. if (token.is(Token::Type::Comma))
  4553. break;
  4554. return nullptr;
  4555. }
  4556. // FIXME: If color is absent, default to `currentColor`
  4557. if (!color.has_value())
  4558. color = Color::NamedColor::Black;
  4559. // x/y offsets are required
  4560. if (!offset_x || !offset_y)
  4561. return nullptr;
  4562. // Other lengths default to 0
  4563. if (!blur_radius)
  4564. blur_radius = TRY(LengthStyleValue::create(Length::make_px(0)));
  4565. if (!spread_distance)
  4566. spread_distance = TRY(LengthStyleValue::create(Length::make_px(0)));
  4567. // Placement is outer by default
  4568. if (!placement.has_value())
  4569. placement = ShadowPlacement::Outer;
  4570. transaction.commit();
  4571. return ShadowStyleValue::create(color.release_value(), offset_x.release_nonnull(), offset_y.release_nonnull(), blur_radius.release_nonnull(), spread_distance.release_nonnull(), placement.release_value());
  4572. }
  4573. ErrorOr<RefPtr<StyleValue>> Parser::parse_content_value(Vector<ComponentValue> const& component_values)
  4574. {
  4575. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  4576. auto is_single_value_identifier = [](ValueID identifier) -> bool {
  4577. switch (identifier) {
  4578. case ValueID::None:
  4579. case ValueID::Normal:
  4580. return true;
  4581. default:
  4582. return false;
  4583. }
  4584. };
  4585. if (component_values.size() == 1) {
  4586. if (auto identifier = TRY(parse_identifier_value(component_values.first()))) {
  4587. if (is_single_value_identifier(identifier->to_identifier()))
  4588. return identifier;
  4589. }
  4590. }
  4591. StyleValueVector content_values;
  4592. StyleValueVector alt_text_values;
  4593. bool in_alt_text = false;
  4594. auto tokens = TokenStream { component_values };
  4595. while (tokens.has_next_token()) {
  4596. auto& next = tokens.peek_token();
  4597. if (next.is_delim('/')) {
  4598. if (in_alt_text || content_values.is_empty())
  4599. return nullptr;
  4600. in_alt_text = true;
  4601. (void)tokens.next_token();
  4602. continue;
  4603. }
  4604. if (auto style_value = TRY(parse_css_value_for_property(PropertyID::Content, tokens))) {
  4605. if (is_single_value_identifier(style_value->to_identifier()))
  4606. return nullptr;
  4607. if (in_alt_text) {
  4608. TRY(alt_text_values.try_append(style_value.release_nonnull()));
  4609. } else {
  4610. TRY(content_values.try_append(style_value.release_nonnull()));
  4611. }
  4612. continue;
  4613. }
  4614. return nullptr;
  4615. }
  4616. if (content_values.is_empty())
  4617. return nullptr;
  4618. if (in_alt_text && alt_text_values.is_empty())
  4619. return nullptr;
  4620. RefPtr<StyleValueList> alt_text;
  4621. if (!alt_text_values.is_empty())
  4622. alt_text = TRY(StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space));
  4623. return ContentStyleValue::create(TRY(StyleValueList::create(move(content_values), StyleValueList::Separator::Space)), move(alt_text));
  4624. }
  4625. // https://www.w3.org/TR/css-display-3/#the-display-properties
  4626. ErrorOr<RefPtr<StyleValue>> Parser::parse_display_value(Vector<ComponentValue> const& component_values)
  4627. {
  4628. auto parse_inside = [](ValueID identifier) -> Optional<Display::Inside> {
  4629. switch (identifier) {
  4630. case ValueID::Flow:
  4631. return Display::Inside::Flow;
  4632. case ValueID::FlowRoot:
  4633. return Display::Inside::FlowRoot;
  4634. case ValueID::Table:
  4635. return Display::Inside::Table;
  4636. case ValueID::Flex:
  4637. return Display::Inside::Flex;
  4638. case ValueID::Grid:
  4639. return Display::Inside::Grid;
  4640. case ValueID::Ruby:
  4641. return Display::Inside::Ruby;
  4642. default:
  4643. return {};
  4644. }
  4645. };
  4646. auto parse_outside = [](ValueID identifier) -> Optional<Display::Outside> {
  4647. switch (identifier) {
  4648. case ValueID::Block:
  4649. return Display::Outside::Block;
  4650. case ValueID::Inline:
  4651. return Display::Outside::Inline;
  4652. case ValueID::RunIn:
  4653. return Display::Outside::RunIn;
  4654. default:
  4655. return {};
  4656. }
  4657. };
  4658. auto parse_single_component_display = [&](Vector<ComponentValue> const& component_values) -> ErrorOr<Optional<Display>> {
  4659. if (auto identifier = TRY(parse_identifier_value(component_values.first()))) {
  4660. switch (identifier->to_identifier()) {
  4661. // display-outside
  4662. case ValueID::Block:
  4663. return Display::from_short(Display::Short::Block);
  4664. case ValueID::Inline:
  4665. return Display::from_short(Display::Short::Inline);
  4666. case ValueID::RunIn:
  4667. return Display::from_short(Display::Short::RunIn);
  4668. // display-inside
  4669. case ValueID::Flow:
  4670. return Display::from_short(Display::Short::Flow);
  4671. case ValueID::FlowRoot:
  4672. return Display::from_short(Display::Short::FlowRoot);
  4673. case ValueID::Table:
  4674. return Display::from_short(Display::Short::Table);
  4675. case ValueID::Flex:
  4676. return Display::from_short(Display::Short::Flex);
  4677. case ValueID::Grid:
  4678. return Display::from_short(Display::Short::Grid);
  4679. case ValueID::Ruby:
  4680. return Display::from_short(Display::Short::Ruby);
  4681. // display-listitem
  4682. case ValueID::ListItem:
  4683. return Display::from_short(Display::Short::ListItem);
  4684. // display-internal
  4685. case ValueID::TableRowGroup:
  4686. return Display { Display::Internal::TableRowGroup };
  4687. case ValueID::TableHeaderGroup:
  4688. return Display { Display::Internal::TableHeaderGroup };
  4689. case ValueID::TableFooterGroup:
  4690. return Display { Display::Internal::TableFooterGroup };
  4691. case ValueID::TableRow:
  4692. return Display { Display::Internal::TableRow };
  4693. case ValueID::TableCell:
  4694. return Display { Display::Internal::TableCell };
  4695. case ValueID::TableColumnGroup:
  4696. return Display { Display::Internal::TableColumnGroup };
  4697. case ValueID::TableColumn:
  4698. return Display { Display::Internal::TableColumn };
  4699. case ValueID::TableCaption:
  4700. return Display { Display::Internal::TableCaption };
  4701. case ValueID::RubyBase:
  4702. return Display { Display::Internal::RubyBase };
  4703. case ValueID::RubyText:
  4704. return Display { Display::Internal::RubyText };
  4705. case ValueID::RubyBaseContainer:
  4706. return Display { Display::Internal::RubyBaseContainer };
  4707. case ValueID::RubyTextContainer:
  4708. return Display { Display::Internal::RubyTextContainer };
  4709. // display-box
  4710. case ValueID::Contents:
  4711. return Display::from_short(Display::Short::Contents);
  4712. case ValueID::None:
  4713. return Display::from_short(Display::Short::None);
  4714. // display-legacy
  4715. case ValueID::InlineBlock:
  4716. return Display::from_short(Display::Short::InlineBlock);
  4717. case ValueID::InlineTable:
  4718. return Display::from_short(Display::Short::InlineTable);
  4719. case ValueID::InlineFlex:
  4720. return Display::from_short(Display::Short::InlineFlex);
  4721. case ValueID::InlineGrid:
  4722. return Display::from_short(Display::Short::InlineGrid);
  4723. default:
  4724. return OptionalNone {};
  4725. }
  4726. }
  4727. return OptionalNone {};
  4728. };
  4729. auto parse_multi_component_display = [&](Vector<ComponentValue> const& component_values) -> ErrorOr<Optional<Display>> {
  4730. auto list_item = Display::ListItem::No;
  4731. Display::Inside inside = Display::Inside::Flow;
  4732. Display::Outside outside = Display::Outside::Block;
  4733. for (size_t i = 0; i < component_values.size(); ++i) {
  4734. if (auto value = TRY(parse_identifier_value(component_values[i]))) {
  4735. auto identifier = value->to_identifier();
  4736. if (ValueID::ListItem == identifier) {
  4737. list_item = Display::ListItem::Yes;
  4738. continue;
  4739. }
  4740. auto inside_value = parse_inside(identifier);
  4741. if (inside_value.has_value()) {
  4742. inside = inside_value.value();
  4743. continue;
  4744. }
  4745. auto outside_value = parse_outside(identifier);
  4746. if (outside_value.has_value()) {
  4747. outside = outside_value.value();
  4748. }
  4749. }
  4750. }
  4751. // The spec does not allow any other inside values to be combined with list-item
  4752. // <display-outside>? && [ flow | flow-root ]? && list-item
  4753. if (list_item == Display::ListItem::Yes && inside != Display::Inside::Flow && inside != Display::Inside::FlowRoot)
  4754. return OptionalNone {};
  4755. return Display { outside, inside, list_item };
  4756. };
  4757. Optional<Display> display;
  4758. if (component_values.size() == 1)
  4759. display = TRY(parse_single_component_display(component_values));
  4760. else
  4761. display = TRY(parse_multi_component_display(component_values));
  4762. if (display.has_value())
  4763. return DisplayStyleValue::create(display.value());
  4764. return nullptr;
  4765. }
  4766. ErrorOr<RefPtr<StyleValue>> Parser::parse_filter_value_list_value(Vector<ComponentValue> const& component_values)
  4767. {
  4768. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  4769. auto ident = TRY(parse_identifier_value(component_values.first()));
  4770. if (ident && ident->to_identifier() == ValueID::None)
  4771. return ident;
  4772. }
  4773. TokenStream tokens { component_values };
  4774. // FIXME: <url>s are ignored for now
  4775. // <filter-value-list> = [ <filter-function> | <url> ]+
  4776. enum class FilterToken {
  4777. // Color filters:
  4778. Brightness,
  4779. Contrast,
  4780. Grayscale,
  4781. Invert,
  4782. Opacity,
  4783. Saturate,
  4784. Sepia,
  4785. // Special filters:
  4786. Blur,
  4787. DropShadow,
  4788. HueRotate
  4789. };
  4790. auto filter_token_to_operation = [&](auto filter) {
  4791. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  4792. return static_cast<Filter::Color::Operation>(filter);
  4793. };
  4794. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  4795. if (token.is(Token::Type::Percentage))
  4796. return NumberPercentage(Percentage(token.token().percentage()));
  4797. if (token.is(Token::Type::Number))
  4798. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  4799. return {};
  4800. };
  4801. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  4802. if (name.equals_ignoring_ascii_case("blur"sv))
  4803. return FilterToken::Blur;
  4804. if (name.equals_ignoring_ascii_case("brightness"sv))
  4805. return FilterToken::Brightness;
  4806. if (name.equals_ignoring_ascii_case("contrast"sv))
  4807. return FilterToken::Contrast;
  4808. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  4809. return FilterToken::DropShadow;
  4810. if (name.equals_ignoring_ascii_case("grayscale"sv))
  4811. return FilterToken::Grayscale;
  4812. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  4813. return FilterToken::HueRotate;
  4814. if (name.equals_ignoring_ascii_case("invert"sv))
  4815. return FilterToken::Invert;
  4816. if (name.equals_ignoring_ascii_case("opacity"sv))
  4817. return FilterToken::Opacity;
  4818. if (name.equals_ignoring_ascii_case("saturate"sv))
  4819. return FilterToken::Saturate;
  4820. if (name.equals_ignoring_ascii_case("sepia"sv))
  4821. return FilterToken::Sepia;
  4822. return {};
  4823. };
  4824. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  4825. TokenStream tokens { function_values };
  4826. tokens.skip_whitespace();
  4827. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  4828. tokens.skip_whitespace();
  4829. if (tokens.has_next_token())
  4830. return {};
  4831. return filter;
  4832. };
  4833. if (filter_token == FilterToken::Blur) {
  4834. // blur( <length>? )
  4835. if (!tokens.has_next_token())
  4836. return Filter::Blur {};
  4837. auto blur_radius = parse_length(tokens.next_token());
  4838. if (!blur_radius.has_value())
  4839. return {};
  4840. return if_no_more_tokens_return(Filter::Blur { *blur_radius });
  4841. } else if (filter_token == FilterToken::DropShadow) {
  4842. if (!tokens.has_next_token())
  4843. return {};
  4844. auto next_token = [&]() -> auto& {
  4845. auto& token = tokens.next_token();
  4846. tokens.skip_whitespace();
  4847. return token;
  4848. };
  4849. // drop-shadow( [ <color>? && <length>{2,3} ] )
  4850. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  4851. auto& first_param = next_token();
  4852. Optional<Length> maybe_radius = {};
  4853. auto maybe_color = parse_color(first_param);
  4854. auto x_offset = parse_length(maybe_color.has_value() ? next_token() : first_param);
  4855. if (!x_offset.has_value() || !tokens.has_next_token()) {
  4856. return {};
  4857. }
  4858. auto y_offset = parse_length(next_token());
  4859. if (!y_offset.has_value()) {
  4860. return {};
  4861. }
  4862. if (tokens.has_next_token()) {
  4863. auto& token = next_token();
  4864. maybe_radius = parse_length(token);
  4865. if (!maybe_color.has_value() && (!maybe_radius.has_value() || tokens.has_next_token())) {
  4866. maybe_color = parse_color(!maybe_radius.has_value() ? token : next_token());
  4867. if (!maybe_color.has_value()) {
  4868. return {};
  4869. }
  4870. } else if (!maybe_radius.has_value()) {
  4871. return {};
  4872. }
  4873. }
  4874. return if_no_more_tokens_return(Filter::DropShadow { *x_offset, *y_offset, maybe_radius, maybe_color });
  4875. } else if (filter_token == FilterToken::HueRotate) {
  4876. // hue-rotate( [ <angle> | <zero> ]? )
  4877. if (!tokens.has_next_token())
  4878. return Filter::HueRotate {};
  4879. auto& token = tokens.next_token();
  4880. if (token.is(Token::Type::Number)) {
  4881. // hue-rotate(0)
  4882. auto number = token.token().number();
  4883. if (number.is_integer() && number.integer_value() == 0)
  4884. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  4885. return {};
  4886. }
  4887. if (!token.is(Token::Type::Dimension))
  4888. return {};
  4889. float angle_value = token.token().dimension_value();
  4890. auto angle_unit_name = token.token().dimension_unit();
  4891. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  4892. if (!angle_unit.has_value())
  4893. return {};
  4894. Angle angle { angle_value, angle_unit.release_value() };
  4895. return if_no_more_tokens_return(Filter::HueRotate { angle });
  4896. } else {
  4897. // Simple filters:
  4898. // brightness( <number-percentage>? )
  4899. // contrast( <number-percentage>? )
  4900. // grayscale( <number-percentage>? )
  4901. // invert( <number-percentage>? )
  4902. // opacity( <number-percentage>? )
  4903. // sepia( <number-percentage>? )
  4904. // saturate( <number-percentage>? )
  4905. if (!tokens.has_next_token())
  4906. return Filter::Color { filter_token_to_operation(filter_token) };
  4907. auto amount = parse_number_percentage(tokens.next_token());
  4908. if (!amount.has_value())
  4909. return {};
  4910. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  4911. }
  4912. };
  4913. Vector<FilterFunction> filter_value_list {};
  4914. while (tokens.has_next_token()) {
  4915. tokens.skip_whitespace();
  4916. if (!tokens.has_next_token())
  4917. break;
  4918. auto& token = tokens.next_token();
  4919. if (!token.is_function())
  4920. return nullptr;
  4921. auto filter_token = parse_filter_function_name(token.function().name());
  4922. if (!filter_token.has_value())
  4923. return nullptr;
  4924. auto filter_function = parse_filter_function(*filter_token, token.function().values());
  4925. if (!filter_function.has_value())
  4926. return nullptr;
  4927. filter_value_list.append(*filter_function);
  4928. }
  4929. if (filter_value_list.is_empty())
  4930. return nullptr;
  4931. return FilterValueListStyleValue::create(move(filter_value_list));
  4932. }
  4933. ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_value(Vector<ComponentValue> const& component_values)
  4934. {
  4935. auto tokens = TokenStream { component_values };
  4936. if (component_values.size() == 1) {
  4937. // One-value syntax: <flex-grow> | <flex-basis> | none
  4938. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  4939. auto property_and_value = TRY(parse_css_value_for_properties(properties, tokens));
  4940. if (!property_and_value.style_value)
  4941. return nullptr;
  4942. auto& value = property_and_value.style_value;
  4943. switch (property_and_value.property) {
  4944. case PropertyID::FlexGrow: {
  4945. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4946. // https://github.com/w3c/csswg-drafts/issues/5742
  4947. auto flex_basis = TRY(PercentageStyleValue::create(Percentage(0)));
  4948. auto one = TRY(NumberStyleValue::create(1));
  4949. return FlexStyleValue::create(*value, one, flex_basis);
  4950. }
  4951. case PropertyID::FlexBasis: {
  4952. auto one = TRY(NumberStyleValue::create(1));
  4953. return FlexStyleValue::create(one, one, *value);
  4954. }
  4955. case PropertyID::Flex: {
  4956. if (value->is_identifier() && value->to_identifier() == ValueID::None) {
  4957. auto zero = TRY(NumberStyleValue::create(0));
  4958. return FlexStyleValue::create(zero, zero, TRY(IdentifierStyleValue::create(ValueID::Auto)));
  4959. }
  4960. break;
  4961. }
  4962. default:
  4963. VERIFY_NOT_REACHED();
  4964. }
  4965. return nullptr;
  4966. }
  4967. RefPtr<StyleValue> flex_grow;
  4968. RefPtr<StyleValue> flex_shrink;
  4969. RefPtr<StyleValue> flex_basis;
  4970. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  4971. // if FlexGrow (along with optional FlexShrink) have already been specified.
  4972. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  4973. while (tokens.has_next_token()) {
  4974. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  4975. if (!property_and_value.style_value)
  4976. return nullptr;
  4977. auto& value = property_and_value.style_value;
  4978. remove_property(remaining_longhands, property_and_value.property);
  4979. switch (property_and_value.property) {
  4980. case PropertyID::FlexGrow: {
  4981. VERIFY(!flex_grow);
  4982. flex_grow = value.release_nonnull();
  4983. // Flex-shrink may optionally follow directly after.
  4984. auto maybe_flex_shrink = TRY(parse_css_value_for_property(PropertyID::FlexShrink, tokens));
  4985. if (maybe_flex_shrink)
  4986. flex_shrink = maybe_flex_shrink.release_nonnull();
  4987. continue;
  4988. }
  4989. case PropertyID::FlexBasis: {
  4990. VERIFY(!flex_basis);
  4991. flex_basis = value.release_nonnull();
  4992. continue;
  4993. }
  4994. default:
  4995. VERIFY_NOT_REACHED();
  4996. }
  4997. }
  4998. if (!flex_grow)
  4999. flex_grow = TRY(property_initial_value(m_context.realm(), PropertyID::FlexGrow));
  5000. if (!flex_shrink)
  5001. flex_shrink = TRY(property_initial_value(m_context.realm(), PropertyID::FlexShrink));
  5002. if (!flex_basis) {
  5003. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  5004. // https://github.com/w3c/csswg-drafts/issues/5742
  5005. flex_basis = TRY(PercentageStyleValue::create(Percentage(0)));
  5006. }
  5007. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  5008. }
  5009. ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_flow_value(Vector<ComponentValue> const& component_values)
  5010. {
  5011. if (component_values.size() > 2)
  5012. return nullptr;
  5013. RefPtr<StyleValue> flex_direction;
  5014. RefPtr<StyleValue> flex_wrap;
  5015. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  5016. auto tokens = TokenStream { component_values };
  5017. while (tokens.has_next_token()) {
  5018. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5019. if (!property_and_value.style_value)
  5020. return nullptr;
  5021. auto& value = property_and_value.style_value;
  5022. remove_property(remaining_longhands, property_and_value.property);
  5023. switch (property_and_value.property) {
  5024. case PropertyID::FlexDirection:
  5025. VERIFY(!flex_direction);
  5026. flex_direction = value.release_nonnull();
  5027. continue;
  5028. case PropertyID::FlexWrap:
  5029. VERIFY(!flex_wrap);
  5030. flex_wrap = value.release_nonnull();
  5031. continue;
  5032. default:
  5033. VERIFY_NOT_REACHED();
  5034. }
  5035. }
  5036. if (!flex_direction)
  5037. flex_direction = TRY(property_initial_value(m_context.realm(), PropertyID::FlexDirection));
  5038. if (!flex_wrap)
  5039. flex_wrap = TRY(property_initial_value(m_context.realm(), PropertyID::FlexWrap));
  5040. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  5041. }
  5042. static bool is_generic_font_family(ValueID identifier)
  5043. {
  5044. switch (identifier) {
  5045. case ValueID::Cursive:
  5046. case ValueID::Fantasy:
  5047. case ValueID::Monospace:
  5048. case ValueID::Serif:
  5049. case ValueID::SansSerif:
  5050. case ValueID::UiMonospace:
  5051. case ValueID::UiRounded:
  5052. case ValueID::UiSerif:
  5053. case ValueID::UiSansSerif:
  5054. return true;
  5055. default:
  5056. return false;
  5057. }
  5058. }
  5059. ErrorOr<RefPtr<StyleValue>> Parser::parse_font_value(Vector<ComponentValue> const& component_values)
  5060. {
  5061. RefPtr<StyleValue> font_stretch;
  5062. RefPtr<StyleValue> font_style;
  5063. RefPtr<StyleValue> font_weight;
  5064. RefPtr<StyleValue> font_size;
  5065. RefPtr<StyleValue> line_height;
  5066. RefPtr<StyleValue> font_families;
  5067. RefPtr<StyleValue> font_variant;
  5068. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  5069. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  5070. // So, we have to handle that separately.
  5071. int normal_count = 0;
  5072. auto tokens = TokenStream { component_values };
  5073. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStretch, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight };
  5074. while (tokens.has_next_token()) {
  5075. auto& peek_token = tokens.peek_token();
  5076. if (peek_token.is(Token::Type::Ident) && value_id_from_string(peek_token.token().ident()) == ValueID::Normal) {
  5077. normal_count++;
  5078. (void)tokens.next_token();
  5079. continue;
  5080. }
  5081. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5082. if (!property_and_value.style_value)
  5083. return nullptr;
  5084. auto& value = property_and_value.style_value;
  5085. remove_property(remaining_longhands, property_and_value.property);
  5086. switch (property_and_value.property) {
  5087. case PropertyID::FontSize: {
  5088. VERIFY(!font_size);
  5089. font_size = value.release_nonnull();
  5090. // Consume `/ line-height` if present
  5091. if (tokens.peek_token().is_delim('/')) {
  5092. (void)tokens.next_token();
  5093. auto maybe_line_height = TRY(parse_css_value_for_property(PropertyID::LineHeight, tokens));
  5094. if (!maybe_line_height)
  5095. return nullptr;
  5096. line_height = maybe_line_height.release_nonnull();
  5097. }
  5098. // Consume font-families
  5099. auto maybe_font_families = TRY(parse_font_family_value(tokens));
  5100. // font-family comes last, so we must not have any tokens left over.
  5101. if (!maybe_font_families || tokens.has_next_token())
  5102. return nullptr;
  5103. font_families = maybe_font_families.release_nonnull();
  5104. continue;
  5105. }
  5106. case PropertyID::FontStretch: {
  5107. VERIFY(!font_stretch);
  5108. font_stretch = value.release_nonnull();
  5109. continue;
  5110. }
  5111. case PropertyID::FontStyle: {
  5112. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  5113. VERIFY(!font_style);
  5114. font_style = value.release_nonnull();
  5115. continue;
  5116. }
  5117. case PropertyID::FontVariant: {
  5118. VERIFY(!font_variant);
  5119. font_variant = value.release_nonnull();
  5120. continue;
  5121. }
  5122. case PropertyID::FontWeight: {
  5123. VERIFY(!font_weight);
  5124. font_weight = value.release_nonnull();
  5125. continue;
  5126. }
  5127. default:
  5128. VERIFY_NOT_REACHED();
  5129. }
  5130. return nullptr;
  5131. }
  5132. // Since normal is the default value for all the properties that can have it, we don't have to actually
  5133. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  5134. // We just need to make sure we were not given more normals than will fit.
  5135. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1) + (font_variant ? 0 : 1) + (font_stretch ? 0 : 1);
  5136. if (unset_value_count < normal_count)
  5137. return nullptr;
  5138. if (!font_size || !font_families)
  5139. return nullptr;
  5140. if (!font_stretch)
  5141. font_stretch = TRY(property_initial_value(m_context.realm(), PropertyID::FontStretch));
  5142. if (!font_style)
  5143. font_style = TRY(property_initial_value(m_context.realm(), PropertyID::FontStyle));
  5144. if (!font_weight)
  5145. font_weight = TRY(property_initial_value(m_context.realm(), PropertyID::FontWeight));
  5146. if (!line_height)
  5147. line_height = TRY(property_initial_value(m_context.realm(), PropertyID::LineHeight));
  5148. return FontStyleValue::create(font_stretch.release_nonnull(), font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  5149. }
  5150. ErrorOr<RefPtr<StyleValue>> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  5151. {
  5152. auto next_is_comma_or_eof = [&]() -> bool {
  5153. return !tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma);
  5154. };
  5155. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  5156. // eg, these are equivalent:
  5157. // font-family: my cool font\!, serif;
  5158. // font-family: "my cool font!", serif;
  5159. StyleValueVector font_families;
  5160. Vector<DeprecatedString> current_name_parts;
  5161. while (tokens.has_next_token()) {
  5162. auto const& peek = tokens.peek_token();
  5163. if (peek.is(Token::Type::String)) {
  5164. // `font-family: my cool "font";` is invalid.
  5165. if (!current_name_parts.is_empty())
  5166. return nullptr;
  5167. (void)tokens.next_token(); // String
  5168. if (!next_is_comma_or_eof())
  5169. return nullptr;
  5170. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::from_utf8(peek.token().string()))))));
  5171. (void)tokens.next_token(); // Comma
  5172. continue;
  5173. }
  5174. if (peek.is(Token::Type::Ident)) {
  5175. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  5176. // CSS-wide keywords are not allowed
  5177. if (auto builtin = TRY(parse_builtin_value(peek)))
  5178. return nullptr;
  5179. auto maybe_ident = value_id_from_string(peek.token().ident());
  5180. // Can't have a generic-font-name as a token in an unquoted font name.
  5181. if (maybe_ident.has_value() && is_generic_font_family(maybe_ident.value())) {
  5182. if (!current_name_parts.is_empty())
  5183. return nullptr;
  5184. (void)tokens.next_token(); // Ident
  5185. if (!next_is_comma_or_eof())
  5186. return nullptr;
  5187. TRY(font_families.try_append(TRY(IdentifierStyleValue::create(maybe_ident.value()))));
  5188. (void)tokens.next_token(); // Comma
  5189. continue;
  5190. }
  5191. TRY(current_name_parts.try_append(tokens.next_token().token().ident()));
  5192. continue;
  5193. }
  5194. if (peek.is(Token::Type::Comma)) {
  5195. if (current_name_parts.is_empty())
  5196. return nullptr;
  5197. (void)tokens.next_token(); // Comma
  5198. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::join(' ', current_name_parts))))));
  5199. current_name_parts.clear();
  5200. // Can't have a trailing comma
  5201. if (!tokens.has_next_token())
  5202. return nullptr;
  5203. continue;
  5204. }
  5205. return nullptr;
  5206. }
  5207. if (!current_name_parts.is_empty()) {
  5208. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::join(' ', current_name_parts))))));
  5209. current_name_parts.clear();
  5210. }
  5211. if (font_families.is_empty())
  5212. return nullptr;
  5213. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  5214. }
  5215. CSSRule* Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
  5216. {
  5217. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  5218. Optional<FlyString> font_family;
  5219. Vector<FontFace::Source> src;
  5220. Vector<UnicodeRange> unicode_range;
  5221. Optional<int> weight;
  5222. Optional<int> slope;
  5223. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  5224. if (declaration_or_at_rule.is_at_rule()) {
  5225. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-face; discarding.");
  5226. continue;
  5227. }
  5228. auto const& declaration = declaration_or_at_rule.declaration();
  5229. if (declaration.name().equals_ignoring_ascii_case("font-weight"sv)) {
  5230. TokenStream token_stream { declaration.values() };
  5231. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  5232. weight = value.value()->to_font_weight();
  5233. }
  5234. continue;
  5235. }
  5236. if (declaration.name().equals_ignoring_ascii_case("font-style"sv)) {
  5237. TokenStream token_stream { declaration.values() };
  5238. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  5239. slope = value.value()->to_font_slope();
  5240. }
  5241. continue;
  5242. }
  5243. if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
  5244. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  5245. // Ideally they could share code.
  5246. Vector<DeprecatedString> font_family_parts;
  5247. bool had_syntax_error = false;
  5248. for (size_t i = 0; i < declaration.values().size(); ++i) {
  5249. auto const& part = declaration.values()[i];
  5250. if (part.is(Token::Type::Whitespace))
  5251. continue;
  5252. if (part.is(Token::Type::String)) {
  5253. if (!font_family_parts.is_empty()) {
  5254. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5255. had_syntax_error = true;
  5256. break;
  5257. }
  5258. font_family_parts.append(part.token().string());
  5259. continue;
  5260. }
  5261. if (part.is(Token::Type::Ident)) {
  5262. if (is_builtin(part.token().ident())) {
  5263. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5264. had_syntax_error = true;
  5265. break;
  5266. }
  5267. auto value_id = value_id_from_string(part.token().ident());
  5268. if (value_id.has_value() && is_generic_font_family(value_id.value())) {
  5269. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5270. had_syntax_error = true;
  5271. break;
  5272. }
  5273. font_family_parts.append(part.token().ident());
  5274. continue;
  5275. }
  5276. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5277. had_syntax_error = true;
  5278. break;
  5279. }
  5280. if (had_syntax_error || font_family_parts.is_empty())
  5281. continue;
  5282. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  5283. continue;
  5284. }
  5285. if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
  5286. TokenStream token_stream { declaration.values() };
  5287. Vector<FontFace::Source> supported_sources = parse_font_face_src(token_stream);
  5288. if (!supported_sources.is_empty())
  5289. src = move(supported_sources);
  5290. continue;
  5291. }
  5292. if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
  5293. Vector<UnicodeRange> unicode_ranges;
  5294. bool unicode_range_invalid = false;
  5295. TokenStream all_tokens { declaration.values() };
  5296. auto range_token_lists = parse_a_comma_separated_list_of_component_values(all_tokens);
  5297. for (auto& range_tokens : range_token_lists) {
  5298. TokenStream range_token_stream { range_tokens };
  5299. auto maybe_unicode_range = parse_unicode_range(range_token_stream);
  5300. if (!maybe_unicode_range.has_value()) {
  5301. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face unicode-range format invalid; discarding.");
  5302. unicode_range_invalid = true;
  5303. break;
  5304. }
  5305. unicode_ranges.append(maybe_unicode_range.release_value());
  5306. }
  5307. if (unicode_range_invalid || unicode_ranges.is_empty())
  5308. continue;
  5309. unicode_range = move(unicode_ranges);
  5310. continue;
  5311. }
  5312. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-face; discarding.", declaration.name());
  5313. }
  5314. if (!font_family.has_value()) {
  5315. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  5316. return {};
  5317. }
  5318. if (unicode_range.is_empty()) {
  5319. unicode_range.empend(0x0u, 0x10FFFFu);
  5320. }
  5321. return CSSFontFaceRule::create(m_context.realm(), FontFace { font_family.release_value(), weight, slope, move(src), move(unicode_range) }).release_value_but_fixme_should_propagate_errors();
  5322. }
  5323. Vector<FontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values)
  5324. {
  5325. // FIXME: Get this information from the system somehow?
  5326. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  5327. auto font_format_is_supported = [](StringView name) {
  5328. // The spec requires us to treat opentype and truetype as synonymous.
  5329. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv))
  5330. return true;
  5331. return false;
  5332. };
  5333. Vector<FontFace::Source> supported_sources;
  5334. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  5335. for (auto const& source_token_list : list_of_source_token_lists) {
  5336. TokenStream source_tokens { source_token_list };
  5337. source_tokens.skip_whitespace();
  5338. auto const& first = source_tokens.next_token();
  5339. // <url> [ format(<font-format>)]?
  5340. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  5341. if (auto maybe_url = parse_url_function(first); maybe_url.has_value()) {
  5342. auto url = maybe_url.release_value();
  5343. if (!url.is_valid()) {
  5344. continue;
  5345. }
  5346. Optional<FlyString> format;
  5347. source_tokens.skip_whitespace();
  5348. if (!source_tokens.has_next_token()) {
  5349. supported_sources.empend(move(url), format);
  5350. continue;
  5351. }
  5352. auto maybe_function = source_tokens.next_token();
  5353. if (!maybe_function.is_function()) {
  5354. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  5355. return {};
  5356. }
  5357. auto const& function = maybe_function.function();
  5358. if (function.name().equals_ignoring_ascii_case("format"sv)) {
  5359. TokenStream format_tokens { function.values() };
  5360. format_tokens.skip_whitespace();
  5361. auto const& format_name_token = format_tokens.next_token();
  5362. StringView format_name;
  5363. if (format_name_token.is(Token::Type::Ident)) {
  5364. format_name = format_name_token.token().ident();
  5365. } else if (format_name_token.is(Token::Type::String)) {
  5366. format_name = format_name_token.token().string();
  5367. } else {
  5368. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (`format()` parameter not an ident or string; is: {}); discarding.", format_name_token.to_debug_string());
  5369. return {};
  5370. }
  5371. if (!font_format_is_supported(format_name)) {
  5372. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  5373. continue;
  5374. }
  5375. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  5376. } else {
  5377. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
  5378. return {};
  5379. }
  5380. source_tokens.skip_whitespace();
  5381. if (source_tokens.has_next_token()) {
  5382. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
  5383. return {};
  5384. }
  5385. supported_sources.empend(move(url), format);
  5386. continue;
  5387. }
  5388. // FIXME: Implement `local()`.
  5389. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  5390. return {};
  5391. }
  5392. return supported_sources;
  5393. }
  5394. ErrorOr<RefPtr<StyleValue>> Parser::parse_list_style_value(Vector<ComponentValue> const& component_values)
  5395. {
  5396. if (component_values.size() > 3)
  5397. return nullptr;
  5398. RefPtr<StyleValue> list_position;
  5399. RefPtr<StyleValue> list_image;
  5400. RefPtr<StyleValue> list_type;
  5401. int found_nones = 0;
  5402. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  5403. auto tokens = TokenStream { component_values };
  5404. while (tokens.has_next_token()) {
  5405. if (auto peek = tokens.peek_token(); peek.is(Token::Type::Ident) && peek.token().ident().equals_ignoring_ascii_case("none"sv)) {
  5406. (void)tokens.next_token();
  5407. found_nones++;
  5408. continue;
  5409. }
  5410. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5411. if (!property_and_value.style_value)
  5412. return nullptr;
  5413. auto& value = property_and_value.style_value;
  5414. remove_property(remaining_longhands, property_and_value.property);
  5415. switch (property_and_value.property) {
  5416. case PropertyID::ListStylePosition: {
  5417. VERIFY(!list_position);
  5418. list_position = value.release_nonnull();
  5419. continue;
  5420. }
  5421. case PropertyID::ListStyleImage: {
  5422. VERIFY(!list_image);
  5423. list_image = value.release_nonnull();
  5424. continue;
  5425. }
  5426. case PropertyID::ListStyleType: {
  5427. VERIFY(!list_type);
  5428. list_type = value.release_nonnull();
  5429. continue;
  5430. }
  5431. default:
  5432. VERIFY_NOT_REACHED();
  5433. }
  5434. }
  5435. if (found_nones > 2)
  5436. return nullptr;
  5437. if (found_nones == 2) {
  5438. if (list_image || list_type)
  5439. return nullptr;
  5440. auto none = TRY(IdentifierStyleValue::create(ValueID::None));
  5441. list_image = none;
  5442. list_type = none;
  5443. } else if (found_nones == 1) {
  5444. if (list_image && list_type)
  5445. return nullptr;
  5446. auto none = TRY(IdentifierStyleValue::create(ValueID::None));
  5447. if (!list_image)
  5448. list_image = none;
  5449. if (!list_type)
  5450. list_type = none;
  5451. }
  5452. if (!list_position)
  5453. list_position = TRY(property_initial_value(m_context.realm(), PropertyID::ListStylePosition));
  5454. if (!list_image)
  5455. list_image = TRY(property_initial_value(m_context.realm(), PropertyID::ListStyleImage));
  5456. if (!list_type)
  5457. list_type = TRY(property_initial_value(m_context.realm(), PropertyID::ListStyleType));
  5458. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  5459. }
  5460. ErrorOr<RefPtr<StyleValue>> Parser::parse_overflow_value(Vector<ComponentValue> const& component_values)
  5461. {
  5462. auto tokens = TokenStream { component_values };
  5463. if (component_values.size() == 1) {
  5464. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::Overflow, tokens));
  5465. if (!maybe_value)
  5466. return nullptr;
  5467. return OverflowStyleValue::create(*maybe_value, *maybe_value);
  5468. }
  5469. if (component_values.size() == 2) {
  5470. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::OverflowX, tokens));
  5471. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::OverflowY, tokens));
  5472. if (!maybe_x_value || !maybe_y_value)
  5473. return nullptr;
  5474. return OverflowStyleValue::create(maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull());
  5475. }
  5476. return nullptr;
  5477. }
  5478. ErrorOr<RefPtr<StyleValue>> Parser::parse_place_content_value(Vector<ComponentValue> const& component_values)
  5479. {
  5480. if (component_values.size() > 2)
  5481. return nullptr;
  5482. auto tokens = TokenStream { component_values };
  5483. auto maybe_align_content_value = TRY(parse_css_value_for_property(PropertyID::AlignContent, tokens));
  5484. if (!maybe_align_content_value)
  5485. return nullptr;
  5486. if (component_values.size() == 1) {
  5487. if (!property_accepts_identifier(PropertyID::JustifyContent, maybe_align_content_value->to_identifier()))
  5488. return nullptr;
  5489. return PlaceContentStyleValue::create(*maybe_align_content_value, *maybe_align_content_value);
  5490. }
  5491. auto maybe_justify_content_value = TRY(parse_css_value_for_property(PropertyID::JustifyContent, tokens));
  5492. if (!maybe_justify_content_value)
  5493. return nullptr;
  5494. return PlaceContentStyleValue::create(maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull());
  5495. }
  5496. ErrorOr<RefPtr<StyleValue>> Parser::parse_place_items_value(Vector<ComponentValue> const& component_values)
  5497. {
  5498. auto tokens = TokenStream { component_values };
  5499. auto maybe_align_items_value = TRY(parse_css_value_for_property(PropertyID::AlignItems, tokens));
  5500. if (!maybe_align_items_value)
  5501. return nullptr;
  5502. if (component_values.size() == 1) {
  5503. if (!property_accepts_identifier(PropertyID::JustifyItems, maybe_align_items_value->to_identifier()))
  5504. return nullptr;
  5505. return PlaceItemsStyleValue::create(*maybe_align_items_value, *maybe_align_items_value);
  5506. }
  5507. auto maybe_justify_items_value = TRY(parse_css_value_for_property(PropertyID::JustifyItems, tokens));
  5508. if (!maybe_justify_items_value)
  5509. return nullptr;
  5510. return PlaceItemsStyleValue::create(*maybe_align_items_value, *maybe_justify_items_value);
  5511. }
  5512. ErrorOr<RefPtr<StyleValue>> Parser::parse_place_self_value(Vector<ComponentValue> const& component_values)
  5513. {
  5514. auto tokens = TokenStream { component_values };
  5515. auto maybe_align_self_value = TRY(parse_css_value_for_property(PropertyID::AlignSelf, tokens));
  5516. if (!maybe_align_self_value)
  5517. return nullptr;
  5518. if (component_values.size() == 1) {
  5519. if (!property_accepts_identifier(PropertyID::JustifySelf, maybe_align_self_value->to_identifier()))
  5520. return nullptr;
  5521. return PlaceSelfStyleValue::create(*maybe_align_self_value, *maybe_align_self_value);
  5522. }
  5523. auto maybe_justify_self_value = TRY(parse_css_value_for_property(PropertyID::JustifySelf, tokens));
  5524. if (!maybe_justify_self_value)
  5525. return nullptr;
  5526. return PlaceItemsStyleValue::create(*maybe_align_self_value, *maybe_justify_self_value);
  5527. }
  5528. ErrorOr<RefPtr<StyleValue>> Parser::parse_text_decoration_value(Vector<ComponentValue> const& component_values)
  5529. {
  5530. RefPtr<StyleValue> decoration_line;
  5531. RefPtr<StyleValue> decoration_thickness;
  5532. RefPtr<StyleValue> decoration_style;
  5533. RefPtr<StyleValue> decoration_color;
  5534. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  5535. auto tokens = TokenStream { component_values };
  5536. while (tokens.has_next_token()) {
  5537. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5538. if (!property_and_value.style_value)
  5539. return nullptr;
  5540. auto& value = property_and_value.style_value;
  5541. remove_property(remaining_longhands, property_and_value.property);
  5542. switch (property_and_value.property) {
  5543. case PropertyID::TextDecorationColor: {
  5544. VERIFY(!decoration_color);
  5545. decoration_color = value.release_nonnull();
  5546. continue;
  5547. }
  5548. case PropertyID::TextDecorationLine: {
  5549. VERIFY(!decoration_line);
  5550. tokens.reconsume_current_input_token();
  5551. auto parsed_decoration_line = TRY(parse_text_decoration_line_value(tokens));
  5552. if (!parsed_decoration_line)
  5553. return nullptr;
  5554. decoration_line = parsed_decoration_line.release_nonnull();
  5555. continue;
  5556. }
  5557. case PropertyID::TextDecorationThickness: {
  5558. VERIFY(!decoration_thickness);
  5559. decoration_thickness = value.release_nonnull();
  5560. continue;
  5561. }
  5562. case PropertyID::TextDecorationStyle: {
  5563. VERIFY(!decoration_style);
  5564. decoration_style = value.release_nonnull();
  5565. continue;
  5566. }
  5567. default:
  5568. VERIFY_NOT_REACHED();
  5569. }
  5570. }
  5571. if (!decoration_line)
  5572. decoration_line = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationLine));
  5573. if (!decoration_thickness)
  5574. decoration_thickness = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness));
  5575. if (!decoration_style)
  5576. decoration_style = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle));
  5577. if (!decoration_color)
  5578. decoration_color = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationColor));
  5579. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  5580. }
  5581. ErrorOr<RefPtr<StyleValue>> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  5582. {
  5583. StyleValueVector style_values;
  5584. while (tokens.has_next_token()) {
  5585. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::TextDecorationLine, tokens));
  5586. if (!maybe_value)
  5587. break;
  5588. auto value = maybe_value.release_nonnull();
  5589. if (auto maybe_line = value_id_to_text_decoration_line(value->to_identifier()); maybe_line.has_value()) {
  5590. if (maybe_line == TextDecorationLine::None) {
  5591. if (!style_values.is_empty())
  5592. break;
  5593. return value;
  5594. }
  5595. if (style_values.contains_slow(value))
  5596. break;
  5597. TRY(style_values.try_append(move(value)));
  5598. continue;
  5599. }
  5600. break;
  5601. }
  5602. if (style_values.is_empty())
  5603. return nullptr;
  5604. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  5605. }
  5606. ErrorOr<RefPtr<StyleValue>> Parser::parse_easing_value(TokenStream<ComponentValue>& tokens)
  5607. {
  5608. auto transaction = tokens.begin_transaction();
  5609. tokens.skip_whitespace();
  5610. auto const& part = tokens.next_token();
  5611. StringView name;
  5612. Optional<Vector<ComponentValue> const&> arguments;
  5613. if (part.is(Token::Type::Ident)) {
  5614. name = part.token().ident();
  5615. } else if (part.is_function()) {
  5616. name = part.function().name();
  5617. arguments = part.function().values();
  5618. } else {
  5619. return nullptr;
  5620. }
  5621. auto maybe_function = easing_function_from_string(name);
  5622. if (!maybe_function.has_value())
  5623. return nullptr;
  5624. auto function = maybe_function.release_value();
  5625. auto function_metadata = easing_function_metadata(function);
  5626. if (function_metadata.parameters.is_empty() && arguments.has_value()) {
  5627. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: 0", name);
  5628. return nullptr;
  5629. }
  5630. StyleValueVector values;
  5631. size_t argument_index = 0;
  5632. if (arguments.has_value()) {
  5633. auto argument_tokens = TokenStream { *arguments };
  5634. auto arguments_values = parse_a_comma_separated_list_of_component_values(argument_tokens);
  5635. if (arguments_values.size() > function_metadata.parameters.size()) {
  5636. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", name, function_metadata.parameters.size());
  5637. return nullptr;
  5638. }
  5639. for (auto& argument_values : arguments_values) {
  5640. // Prune any whitespace before and after the actual argument values.
  5641. argument_values.remove_all_matching([](auto& value) { return value.is(Token::Type::Whitespace); });
  5642. if (argument_values.size() != 1) {
  5643. dbgln_if(CSS_PARSER_DEBUG, "Too many values in argument to {}. max: 1", name);
  5644. return nullptr;
  5645. }
  5646. auto& value = argument_values[0];
  5647. switch (function_metadata.parameters[argument_index].type) {
  5648. case EasingFunctionParameterType::Number: {
  5649. if (value.is(Token::Type::Number))
  5650. values.append(TRY(NumberStyleValue::create(value.token().number().value())));
  5651. else
  5652. return nullptr;
  5653. break;
  5654. }
  5655. case EasingFunctionParameterType::NumberZeroToOne: {
  5656. if (value.is(Token::Type::Number) && value.token().number_value() >= 0 && value.token().number_value() <= 1)
  5657. values.append(TRY(NumberStyleValue::create(value.token().number().value())));
  5658. else
  5659. return nullptr;
  5660. break;
  5661. }
  5662. case EasingFunctionParameterType::Integer: {
  5663. if (value.is(Token::Type::Number) && value.token().number().is_integer())
  5664. values.append(TRY(IntegerStyleValue::create(value.token().number().integer_value())));
  5665. else
  5666. return nullptr;
  5667. break;
  5668. }
  5669. case EasingFunctionParameterType::StepPosition: {
  5670. if (!value.is(Token::Type::Ident))
  5671. return nullptr;
  5672. auto ident = TRY(parse_identifier_value(value));
  5673. if (!ident)
  5674. return nullptr;
  5675. switch (ident->to_identifier()) {
  5676. case ValueID::JumpStart:
  5677. case ValueID::JumpEnd:
  5678. case ValueID::JumpNone:
  5679. case ValueID::Start:
  5680. case ValueID::End:
  5681. TRY(values.try_append(*ident));
  5682. break;
  5683. default:
  5684. return nullptr;
  5685. }
  5686. }
  5687. }
  5688. ++argument_index;
  5689. }
  5690. }
  5691. if (argument_index < function_metadata.parameters.size() && !function_metadata.parameters[argument_index].is_optional) {
  5692. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  5693. return nullptr;
  5694. }
  5695. transaction.commit();
  5696. return EasingStyleValue::create(function, move(values));
  5697. }
  5698. ErrorOr<RefPtr<StyleValue>> Parser::parse_transform_value(Vector<ComponentValue> const& component_values)
  5699. {
  5700. StyleValueVector transformations;
  5701. auto tokens = TokenStream { component_values };
  5702. tokens.skip_whitespace();
  5703. while (tokens.has_next_token()) {
  5704. tokens.skip_whitespace();
  5705. auto const& part = tokens.next_token();
  5706. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_ascii_case("none"sv)) {
  5707. if (!transformations.is_empty())
  5708. return nullptr;
  5709. tokens.skip_whitespace();
  5710. if (tokens.has_next_token())
  5711. return nullptr;
  5712. return IdentifierStyleValue::create(ValueID::None);
  5713. }
  5714. if (!part.is_function())
  5715. return nullptr;
  5716. auto maybe_function = transform_function_from_string(part.function().name());
  5717. if (!maybe_function.has_value())
  5718. return nullptr;
  5719. auto function = maybe_function.release_value();
  5720. auto function_metadata = transform_function_metadata(function);
  5721. StyleValueVector values;
  5722. auto argument_tokens = TokenStream { part.function().values() };
  5723. argument_tokens.skip_whitespace();
  5724. size_t argument_index = 0;
  5725. while (argument_tokens.has_next_token()) {
  5726. if (argument_index == function_metadata.parameters.size()) {
  5727. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
  5728. return nullptr;
  5729. }
  5730. auto const& value = argument_tokens.next_token();
  5731. RefPtr<CalculatedStyleValue> maybe_calc_value;
  5732. if (auto maybe_dynamic_value = TRY(parse_dynamic_value(value))) {
  5733. // TODO: calc() is the only dynamic value we support for now, but more will come later.
  5734. // FIXME: Actually, calc() should probably be parsed inside parse_dimension_value() etc,
  5735. // so that it affects every use instead of us having to manually implement it.
  5736. VERIFY(maybe_dynamic_value->is_calculated());
  5737. maybe_calc_value = maybe_dynamic_value->as_calculated();
  5738. }
  5739. switch (function_metadata.parameters[argument_index].type) {
  5740. case TransformFunctionParameterType::Angle: {
  5741. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  5742. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  5743. values.append(maybe_calc_value.release_nonnull());
  5744. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  5745. values.append(TRY(AngleStyleValue::create(Angle::make_degrees(0))));
  5746. } else {
  5747. auto dimension_value = TRY(parse_dimension_value(value));
  5748. if (!dimension_value || !dimension_value->is_angle())
  5749. return nullptr;
  5750. values.append(dimension_value.release_nonnull());
  5751. }
  5752. break;
  5753. }
  5754. case TransformFunctionParameterType::Length: {
  5755. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  5756. values.append(maybe_calc_value.release_nonnull());
  5757. } else {
  5758. auto dimension_value = TRY(parse_dimension_value(value));
  5759. if (!dimension_value)
  5760. return nullptr;
  5761. if (dimension_value->is_length())
  5762. values.append(dimension_value.release_nonnull());
  5763. else
  5764. return nullptr;
  5765. }
  5766. break;
  5767. }
  5768. case TransformFunctionParameterType::LengthPercentage: {
  5769. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  5770. values.append(maybe_calc_value.release_nonnull());
  5771. } else {
  5772. auto dimension_value = TRY(parse_dimension_value(value));
  5773. if (!dimension_value)
  5774. return nullptr;
  5775. if (dimension_value->is_percentage() || dimension_value->is_length())
  5776. values.append(dimension_value.release_nonnull());
  5777. else
  5778. return nullptr;
  5779. }
  5780. break;
  5781. }
  5782. case TransformFunctionParameterType::Number: {
  5783. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5784. values.append(maybe_calc_value.release_nonnull());
  5785. } else {
  5786. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5787. argument_tokens.reconsume_current_input_token();
  5788. auto number = TRY(parse_number_value(argument_tokens));
  5789. if (!number)
  5790. return nullptr;
  5791. values.append(number.release_nonnull());
  5792. }
  5793. break;
  5794. }
  5795. }
  5796. argument_tokens.skip_whitespace();
  5797. if (argument_tokens.has_next_token()) {
  5798. // Arguments must be separated by commas.
  5799. if (!argument_tokens.next_token().is(Token::Type::Comma))
  5800. return nullptr;
  5801. argument_tokens.skip_whitespace();
  5802. // If there are no more parameters after the comma, this is invalid.
  5803. if (!argument_tokens.has_next_token())
  5804. return nullptr;
  5805. }
  5806. argument_index++;
  5807. }
  5808. if (argument_index < function_metadata.parameters.size() && function_metadata.parameters[argument_index].required) {
  5809. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  5810. return nullptr;
  5811. }
  5812. transformations.append(TRY(TransformationStyleValue::create(function, move(values))));
  5813. }
  5814. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  5815. }
  5816. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  5817. // FIXME: This only supports a 2D position
  5818. ErrorOr<RefPtr<StyleValue>> Parser::parse_transform_origin_value(Vector<ComponentValue> const& component_values)
  5819. {
  5820. enum class Axis {
  5821. None,
  5822. X,
  5823. Y,
  5824. };
  5825. struct AxisOffset {
  5826. Axis axis;
  5827. NonnullRefPtr<StyleValue> offset;
  5828. };
  5829. auto to_axis_offset = [](RefPtr<StyleValue> value) -> ErrorOr<Optional<AxisOffset>> {
  5830. if (value->is_percentage())
  5831. return AxisOffset { Axis::None, value->as_percentage() };
  5832. if (value->is_length())
  5833. return AxisOffset { Axis::None, value->as_length() };
  5834. if (value->is_identifier()) {
  5835. switch (value->to_identifier()) {
  5836. case ValueID::Top:
  5837. return AxisOffset { Axis::Y, TRY(PercentageStyleValue::create(Percentage(0))) };
  5838. case ValueID::Left:
  5839. return AxisOffset { Axis::X, TRY(PercentageStyleValue::create(Percentage(0))) };
  5840. case ValueID::Center:
  5841. return AxisOffset { Axis::None, TRY(PercentageStyleValue::create(Percentage(50))) };
  5842. case ValueID::Bottom:
  5843. return AxisOffset { Axis::Y, TRY(PercentageStyleValue::create(Percentage(100))) };
  5844. case ValueID::Right:
  5845. return AxisOffset { Axis::X, TRY(PercentageStyleValue::create(Percentage(100))) };
  5846. default:
  5847. return OptionalNone {};
  5848. }
  5849. }
  5850. return OptionalNone {};
  5851. };
  5852. auto make_list = [](NonnullRefPtr<StyleValue> const& x_value, NonnullRefPtr<StyleValue> const& y_value) -> ErrorOr<NonnullRefPtr<StyleValueList>> {
  5853. StyleValueVector values;
  5854. values.append(x_value);
  5855. values.append(y_value);
  5856. return StyleValueList::create(move(values), StyleValueList::Separator::Space);
  5857. };
  5858. auto tokens = TokenStream { component_values };
  5859. switch (component_values.size()) {
  5860. case 1: {
  5861. auto single_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  5862. if (!single_value.has_value())
  5863. return nullptr;
  5864. // If only one value is specified, the second value is assumed to be center.
  5865. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  5866. switch (single_value->axis) {
  5867. case Axis::None:
  5868. case Axis::X:
  5869. return make_list(single_value->offset, TRY(PercentageStyleValue::create(Percentage(50))));
  5870. case Axis::Y:
  5871. return make_list(TRY(PercentageStyleValue::create(Percentage(50))), single_value->offset);
  5872. }
  5873. VERIFY_NOT_REACHED();
  5874. }
  5875. case 2: {
  5876. auto first_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  5877. auto second_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  5878. if (!first_value.has_value() || !second_value.has_value())
  5879. return nullptr;
  5880. RefPtr<StyleValue> x_value;
  5881. RefPtr<StyleValue> y_value;
  5882. if (first_value->axis == Axis::X) {
  5883. x_value = first_value->offset;
  5884. } else if (first_value->axis == Axis::Y) {
  5885. y_value = first_value->offset;
  5886. }
  5887. if (second_value->axis == Axis::X) {
  5888. if (x_value)
  5889. return nullptr;
  5890. x_value = second_value->offset;
  5891. // Put the other in Y since its axis can't have been X
  5892. y_value = first_value->offset;
  5893. } else if (second_value->axis == Axis::Y) {
  5894. if (y_value)
  5895. return nullptr;
  5896. y_value = second_value->offset;
  5897. // Put the other in X since its axis can't have been Y
  5898. x_value = first_value->offset;
  5899. } else {
  5900. if (x_value) {
  5901. VERIFY(!y_value);
  5902. y_value = second_value->offset;
  5903. } else {
  5904. VERIFY(!x_value);
  5905. x_value = second_value->offset;
  5906. }
  5907. }
  5908. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  5909. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  5910. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  5911. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  5912. x_value = first_value->offset;
  5913. y_value = second_value->offset;
  5914. }
  5915. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  5916. }
  5917. }
  5918. return nullptr;
  5919. }
  5920. ErrorOr<RefPtr<StyleValue>> Parser::parse_as_css_value(PropertyID property_id)
  5921. {
  5922. auto component_values = parse_a_list_of_component_values(m_token_stream);
  5923. auto tokens = TokenStream(component_values);
  5924. auto parsed_value = parse_css_value(property_id, tokens);
  5925. if (parsed_value.is_error())
  5926. return nullptr;
  5927. return parsed_value.release_value();
  5928. }
  5929. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  5930. {
  5931. if (component_value.is_function()) {
  5932. if (auto maybe_dynamic = parse_dynamic_value(component_value); !maybe_dynamic.is_error() && maybe_dynamic.value())
  5933. return GridSize(LengthPercentage(maybe_dynamic.release_value()->as_calculated()));
  5934. return {};
  5935. }
  5936. auto token = component_value.token();
  5937. if (token.is(Token::Type::Dimension) && token.dimension_unit().equals_ignoring_ascii_case("fr"sv)) {
  5938. float numeric_value = token.dimension_value();
  5939. if (numeric_value)
  5940. return GridSize(numeric_value);
  5941. }
  5942. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  5943. return GridSize::make_auto();
  5944. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("max-content"sv))
  5945. return GridSize(GridSize::Type::MaxContent);
  5946. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("min-content"sv))
  5947. return GridSize(GridSize::Type::MinContent);
  5948. auto dimension = parse_dimension(token);
  5949. if (!dimension.has_value())
  5950. return {};
  5951. if (dimension->is_length())
  5952. return GridSize(dimension->length());
  5953. else if (dimension->is_percentage())
  5954. return GridSize(dimension->percentage());
  5955. return {};
  5956. }
  5957. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  5958. {
  5959. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5960. // 'minmax(min, max)'
  5961. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  5962. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  5963. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5964. auto function_tokens = TokenStream(component_values);
  5965. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5966. if (comma_separated_list.size() != 2)
  5967. return {};
  5968. TokenStream part_one_tokens { comma_separated_list[0] };
  5969. part_one_tokens.skip_whitespace();
  5970. if (!part_one_tokens.has_next_token())
  5971. return {};
  5972. auto current_token = part_one_tokens.next_token();
  5973. auto min_grid_size = parse_grid_size(current_token);
  5974. TokenStream part_two_tokens { comma_separated_list[1] };
  5975. part_two_tokens.skip_whitespace();
  5976. if (!part_two_tokens.has_next_token())
  5977. return {};
  5978. current_token = part_two_tokens.next_token();
  5979. auto max_grid_size = parse_grid_size(current_token);
  5980. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  5981. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5982. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5983. if (min_grid_size.value().is_flexible_length())
  5984. return {};
  5985. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  5986. }
  5987. return {};
  5988. }
  5989. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  5990. {
  5991. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  5992. // 7.2.3.1. Syntax of repeat()
  5993. // The generic form of the repeat() syntax is, approximately,
  5994. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  5995. auto is_auto_fill = false;
  5996. auto is_auto_fit = false;
  5997. auto function_tokens = TokenStream(component_values);
  5998. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5999. if (comma_separated_list.size() != 2)
  6000. return {};
  6001. // The first argument specifies the number of repetitions.
  6002. TokenStream part_one_tokens { comma_separated_list[0] };
  6003. part_one_tokens.skip_whitespace();
  6004. if (!part_one_tokens.has_next_token())
  6005. return {};
  6006. auto current_token = part_one_tokens.next_token().token();
  6007. auto repeat_count = 0;
  6008. if (current_token.is(Token::Type::Number) && current_token.number().is_integer() && current_token.number_value() > 0)
  6009. repeat_count = current_token.number_value();
  6010. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fill"sv))
  6011. is_auto_fill = true;
  6012. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fit"sv))
  6013. is_auto_fit = true;
  6014. // The second argument is a track list, which is repeated that number of times.
  6015. TokenStream part_two_tokens { comma_separated_list[1] };
  6016. part_two_tokens.skip_whitespace();
  6017. if (!part_two_tokens.has_next_token())
  6018. return {};
  6019. Vector<CSS::ExplicitGridTrack> repeat_params;
  6020. Vector<Vector<String>> line_names_list;
  6021. auto last_object_was_line_names = false;
  6022. while (part_two_tokens.has_next_token()) {
  6023. auto token = part_two_tokens.next_token();
  6024. Vector<String> line_names;
  6025. if (token.is_block()) {
  6026. if (last_object_was_line_names)
  6027. return {};
  6028. last_object_was_line_names = true;
  6029. if (!token.block().is_square())
  6030. return {};
  6031. TokenStream block_tokens { token.block().values() };
  6032. while (block_tokens.has_next_token()) {
  6033. auto current_block_token = block_tokens.next_token();
  6034. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  6035. if (maybe_string.is_error())
  6036. return {};
  6037. line_names.append(maybe_string.value());
  6038. block_tokens.skip_whitespace();
  6039. }
  6040. line_names_list.append(line_names);
  6041. part_two_tokens.skip_whitespace();
  6042. } else {
  6043. last_object_was_line_names = false;
  6044. auto track_sizing_function = parse_track_sizing_function(token);
  6045. if (!track_sizing_function.has_value())
  6046. return {};
  6047. // However, there are some restrictions:
  6048. // The repeat() notation can’t be nested.
  6049. if (track_sizing_function.value().is_repeat())
  6050. return {};
  6051. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  6052. if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit))
  6053. return {};
  6054. repeat_params.append(track_sizing_function.value());
  6055. part_two_tokens.skip_whitespace();
  6056. }
  6057. }
  6058. while (line_names_list.size() <= repeat_params.size())
  6059. line_names_list.append({});
  6060. // Thus the precise syntax of the repeat() notation has several forms:
  6061. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  6062. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  6063. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  6064. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  6065. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  6066. // fixed number of repetitions.
  6067. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  6068. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  6069. // list, but the same track list can also contain <fixed-repeat>s.
  6070. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  6071. // subgrid keyword and cannot specify track sizes, only line names.
  6072. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  6073. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  6074. // 1fr [b a] 1fr [b].
  6075. if (is_auto_fill)
  6076. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFill);
  6077. else if (is_auto_fit)
  6078. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFit);
  6079. else
  6080. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), repeat_count);
  6081. }
  6082. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  6083. {
  6084. if (token.is_function()) {
  6085. auto const& function_token = token.function();
  6086. if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
  6087. auto maybe_repeat = parse_repeat(function_token.values());
  6088. if (maybe_repeat.has_value())
  6089. return CSS::ExplicitGridTrack(maybe_repeat.value());
  6090. else
  6091. return {};
  6092. } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
  6093. auto maybe_min_max_value = parse_min_max(function_token.values());
  6094. if (maybe_min_max_value.has_value())
  6095. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  6096. else
  6097. return {};
  6098. } else if (auto maybe_dynamic = parse_dynamic_value(token); !maybe_dynamic.is_error() && maybe_dynamic.value()) {
  6099. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_dynamic.release_value()->as_calculated())));
  6100. }
  6101. return {};
  6102. } else if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("auto"sv)) {
  6103. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  6104. } else if (token.is_block()) {
  6105. return {};
  6106. } else {
  6107. auto grid_size = parse_grid_size(token);
  6108. if (!grid_size.has_value())
  6109. return {};
  6110. return CSS::ExplicitGridTrack(grid_size.value());
  6111. }
  6112. }
  6113. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_size_list(Vector<ComponentValue> const& component_values, bool allow_separate_line_name_blocks)
  6114. {
  6115. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  6116. auto ident = TRY(parse_identifier_value(component_values.first()));
  6117. if (ident && ident->to_identifier() == ValueID::None) {
  6118. return GridTrackSizeListStyleValue::make_none();
  6119. }
  6120. }
  6121. Vector<CSS::ExplicitGridTrack> track_list;
  6122. Vector<Vector<String>> line_names_list;
  6123. auto last_object_was_line_names = false;
  6124. TokenStream tokens { component_values };
  6125. while (tokens.has_next_token()) {
  6126. auto token = tokens.next_token();
  6127. if (token.is_block()) {
  6128. if (last_object_was_line_names && !allow_separate_line_name_blocks)
  6129. return GridTrackSizeListStyleValue::make_auto();
  6130. last_object_was_line_names = true;
  6131. Vector<String> line_names;
  6132. if (!token.block().is_square())
  6133. return GridTrackSizeListStyleValue::make_auto();
  6134. TokenStream block_tokens { token.block().values() };
  6135. block_tokens.skip_whitespace();
  6136. while (block_tokens.has_next_token()) {
  6137. auto current_block_token = block_tokens.next_token();
  6138. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  6139. if (maybe_string.is_error())
  6140. return nullptr;
  6141. line_names.append(maybe_string.value());
  6142. block_tokens.skip_whitespace();
  6143. }
  6144. line_names_list.append(line_names);
  6145. } else {
  6146. last_object_was_line_names = false;
  6147. auto track_sizing_function = parse_track_sizing_function(token);
  6148. if (!track_sizing_function.has_value())
  6149. return GridTrackSizeListStyleValue::make_auto();
  6150. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6151. // any other ones if the first one is auto-fill, etc.)
  6152. track_list.append(track_sizing_function.value());
  6153. }
  6154. }
  6155. while (line_names_list.size() <= track_list.size())
  6156. line_names_list.append({});
  6157. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
  6158. }
  6159. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_auto_track_sizes(Vector<ComponentValue> const& component_values)
  6160. {
  6161. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  6162. // <track-size>+
  6163. Vector<CSS::ExplicitGridTrack> track_list;
  6164. TokenStream tokens { component_values };
  6165. while (tokens.has_next_token()) {
  6166. auto token = tokens.next_token();
  6167. auto track_sizing_function = parse_track_sizing_function(token);
  6168. if (!track_sizing_function.has_value())
  6169. return GridTrackSizeListStyleValue::make_auto();
  6170. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6171. // any other ones if the first one is auto-fill, etc.)
  6172. track_list.append(track_sizing_function.value());
  6173. }
  6174. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, {}));
  6175. }
  6176. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_placement(Vector<ComponentValue> const& component_values)
  6177. {
  6178. // https://www.w3.org/TR/css-grid-2/#line-placement
  6179. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  6180. // <grid-line> =
  6181. // auto |
  6182. // <custom-ident> |
  6183. // [ <integer> && <custom-ident>? ] |
  6184. // [ span && [ <integer> || <custom-ident> ] ]
  6185. auto is_auto = [](Token token) -> bool {
  6186. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  6187. return true;
  6188. return false;
  6189. };
  6190. auto is_span = [](Token token) -> bool {
  6191. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("span"sv))
  6192. return true;
  6193. return false;
  6194. };
  6195. auto is_valid_integer = [](Token token) -> bool {
  6196. // An <integer> value of zero makes the declaration invalid.
  6197. if (token.is(Token::Type::Number) && token.number().is_integer() && token.number_value() != 0)
  6198. return true;
  6199. return false;
  6200. };
  6201. auto is_line_name = [](Token token) -> bool {
  6202. // The <custom-ident> additionally excludes the keywords span and auto.
  6203. if (token.is(Token::Type::Ident) && !token.ident().equals_ignoring_ascii_case("span"sv) && !token.ident().equals_ignoring_ascii_case("auto"sv))
  6204. return true;
  6205. return false;
  6206. };
  6207. auto tokens = TokenStream { component_values };
  6208. tokens.skip_whitespace();
  6209. auto current_token = tokens.next_token().token();
  6210. if (!tokens.has_next_token()) {
  6211. if (is_auto(current_token))
  6212. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement());
  6213. if (is_span(current_token))
  6214. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(1, true));
  6215. if (is_valid_integer(current_token))
  6216. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(static_cast<int>(current_token.number_value())));
  6217. if (is_line_name(current_token)) {
  6218. auto maybe_string = String::from_utf8(current_token.ident());
  6219. if (!maybe_string.is_error())
  6220. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(maybe_string.value()));
  6221. }
  6222. return nullptr;
  6223. }
  6224. auto span_value = false;
  6225. auto span_or_position_value = 0;
  6226. String line_name_value;
  6227. while (true) {
  6228. if (is_auto(current_token))
  6229. return nullptr;
  6230. if (is_span(current_token)) {
  6231. if (span_value == false)
  6232. span_value = true;
  6233. else
  6234. return nullptr;
  6235. }
  6236. if (is_valid_integer(current_token)) {
  6237. if (span_or_position_value == 0)
  6238. span_or_position_value = static_cast<int>(current_token.number_value());
  6239. else
  6240. return nullptr;
  6241. }
  6242. if (is_line_name(current_token)) {
  6243. if (line_name_value.is_empty()) {
  6244. auto maybe_string = String::from_utf8(current_token.ident());
  6245. if (maybe_string.is_error())
  6246. return nullptr;
  6247. line_name_value = maybe_string.release_value();
  6248. } else {
  6249. return nullptr;
  6250. }
  6251. }
  6252. tokens.skip_whitespace();
  6253. if (tokens.has_next_token())
  6254. current_token = tokens.next_token().token();
  6255. else
  6256. break;
  6257. }
  6258. // Negative integers or zero are invalid.
  6259. if (span_value && span_or_position_value < 1)
  6260. return nullptr;
  6261. // If the <integer> is omitted, it defaults to 1.
  6262. if (span_or_position_value == 0)
  6263. span_or_position_value = 1;
  6264. if (!line_name_value.is_empty())
  6265. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(line_name_value, span_or_position_value, span_value));
  6266. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(span_or_position_value, span_value));
  6267. }
  6268. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_placement_shorthand_value(Vector<ComponentValue> const& component_values)
  6269. {
  6270. auto tokens = TokenStream { component_values };
  6271. auto current_token = tokens.next_token().token();
  6272. Vector<ComponentValue> track_start_placement_tokens;
  6273. while (true) {
  6274. if (current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  6275. break;
  6276. track_start_placement_tokens.append(current_token);
  6277. if (!tokens.has_next_token())
  6278. break;
  6279. current_token = tokens.next_token().token();
  6280. }
  6281. Vector<ComponentValue> track_end_placement_tokens;
  6282. if (tokens.has_next_token()) {
  6283. current_token = tokens.next_token().token();
  6284. while (true) {
  6285. track_end_placement_tokens.append(current_token);
  6286. if (!tokens.has_next_token())
  6287. break;
  6288. current_token = tokens.next_token().token();
  6289. }
  6290. }
  6291. auto parsed_start_value = TRY(parse_grid_track_placement(track_start_placement_tokens));
  6292. if (parsed_start_value && track_end_placement_tokens.is_empty())
  6293. return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement().grid_track_placement());
  6294. auto parsed_end_value = TRY(parse_grid_track_placement(track_end_placement_tokens));
  6295. if (parsed_start_value && parsed_end_value)
  6296. return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement(), parsed_end_value.release_nonnull()->as_grid_track_placement());
  6297. return nullptr;
  6298. }
  6299. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  6300. // 7.4. Explicit Grid Shorthand: the grid-template property
  6301. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_size_list_shorthand_value(Vector<ComponentValue> const& component_values)
  6302. {
  6303. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  6304. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  6305. // none
  6306. // - Sets all three properties to their initial values (none).
  6307. // <'grid-template-rows'> / <'grid-template-columns'>
  6308. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  6309. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  6310. // - Sets grid-template-areas to the strings listed.
  6311. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  6312. // and splicing in the named lines defined before/after each size.
  6313. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  6314. Vector<ComponentValue> template_rows_tokens;
  6315. Vector<ComponentValue> template_columns_tokens;
  6316. Vector<ComponentValue> template_area_tokens;
  6317. int forward_slash_index = -1;
  6318. for (size_t x = 0; x < component_values.size(); x++) {
  6319. if (component_values[x].is_delim('/')) {
  6320. forward_slash_index = x;
  6321. break;
  6322. }
  6323. }
  6324. for (size_t x = 0; x < (forward_slash_index > -1 ? forward_slash_index : component_values.size()); x++) {
  6325. if (component_values[x].is_token() && component_values[x].token().is(Token::Type::String))
  6326. template_area_tokens.append(component_values[x]);
  6327. else
  6328. template_rows_tokens.append(component_values[x]);
  6329. }
  6330. if (forward_slash_index > -1) {
  6331. for (size_t x = forward_slash_index + 1; x < component_values.size(); x++)
  6332. template_columns_tokens.append(component_values[x]);
  6333. }
  6334. auto parsed_template_areas_values = TRY(parse_grid_template_areas_value(template_area_tokens));
  6335. auto parsed_template_rows_values = TRY(parse_grid_track_size_list(template_rows_tokens, true));
  6336. auto parsed_template_columns_values = TRY(parse_grid_track_size_list(template_columns_tokens));
  6337. return GridTrackSizeListShorthandStyleValue::create(
  6338. parsed_template_areas_values.release_nonnull()->as_grid_template_area(),
  6339. parsed_template_rows_values.release_nonnull()->as_grid_track_size_list(),
  6340. parsed_template_columns_values.release_nonnull()->as_grid_track_size_list());
  6341. }
  6342. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_area_shorthand_value(Vector<ComponentValue> const& component_values)
  6343. {
  6344. auto tokens = TokenStream { component_values };
  6345. Token current_token;
  6346. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  6347. current_token = tokens.next_token().token();
  6348. while (true) {
  6349. if (check_for_delimiter && current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  6350. break;
  6351. placement_tokens.append(current_token);
  6352. tokens.skip_whitespace();
  6353. if (!tokens.has_next_token())
  6354. break;
  6355. current_token = tokens.next_token().token();
  6356. }
  6357. };
  6358. Vector<ComponentValue> row_start_placement_tokens;
  6359. parse_placement_tokens(row_start_placement_tokens);
  6360. Vector<ComponentValue> column_start_placement_tokens;
  6361. if (tokens.has_next_token())
  6362. parse_placement_tokens(column_start_placement_tokens);
  6363. Vector<ComponentValue> row_end_placement_tokens;
  6364. if (tokens.has_next_token())
  6365. parse_placement_tokens(row_end_placement_tokens);
  6366. Vector<ComponentValue> column_end_placement_tokens;
  6367. if (tokens.has_next_token())
  6368. parse_placement_tokens(column_end_placement_tokens, false);
  6369. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  6370. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  6371. // grid-column-end.
  6372. auto row_start_style_value = TRY(parse_grid_track_placement(row_start_placement_tokens));
  6373. auto column_start_style_value = TRY(parse_grid_track_placement(column_start_placement_tokens));
  6374. auto row_end_style_value = TRY(parse_grid_track_placement(row_end_placement_tokens));
  6375. auto column_end_style_value = TRY(parse_grid_track_placement(column_end_placement_tokens));
  6376. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  6377. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  6378. // fourth value.
  6379. auto row_start = GridTrackPlacement::make_auto();
  6380. auto column_start = GridTrackPlacement::make_auto();
  6381. auto row_end = GridTrackPlacement::make_auto();
  6382. auto column_end = GridTrackPlacement::make_auto();
  6383. if (row_start_style_value)
  6384. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6385. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  6386. // that value. Otherwise, it is set to auto.
  6387. if (column_start_style_value)
  6388. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6389. else
  6390. column_start = row_start;
  6391. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  6392. // <custom-ident>; otherwise, it is set to auto.
  6393. if (row_end_style_value)
  6394. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6395. else
  6396. row_end = column_start;
  6397. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  6398. // that <custom-ident>; otherwise, it is set to auto.
  6399. if (column_end_style_value)
  6400. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6401. else
  6402. column_end = row_end;
  6403. return GridAreaShorthandStyleValue::create(row_start, column_start, row_end, column_end);
  6404. }
  6405. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_shorthand_value(Vector<ComponentValue> const& component_value)
  6406. {
  6407. // <'grid-template'> |
  6408. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  6409. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  6410. return parse_grid_track_size_list_shorthand_value(component_value);
  6411. }
  6412. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_template_areas_value(Vector<ComponentValue> const& component_values)
  6413. {
  6414. Vector<Vector<String>> grid_area_rows;
  6415. for (auto& component_value : component_values) {
  6416. Vector<String> grid_area_columns;
  6417. if (component_value.is(Token::Type::String)) {
  6418. auto const parts = TRY(TRY(String::from_utf8(component_value.token().string())).split(' '));
  6419. for (auto& part : parts) {
  6420. grid_area_columns.append(part);
  6421. }
  6422. }
  6423. grid_area_rows.append(move(grid_area_columns));
  6424. }
  6425. return GridTemplateAreaStyleValue::create(grid_area_rows);
  6426. }
  6427. static bool block_contains_var_or_attr(Block const& block);
  6428. static bool function_contains_var_or_attr(Function const& function)
  6429. {
  6430. if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
  6431. return true;
  6432. for (auto const& token : function.values()) {
  6433. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6434. return true;
  6435. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6436. return true;
  6437. }
  6438. return false;
  6439. }
  6440. bool block_contains_var_or_attr(Block const& block)
  6441. {
  6442. for (auto const& token : block.values()) {
  6443. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6444. return true;
  6445. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6446. return true;
  6447. }
  6448. return false;
  6449. }
  6450. Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6451. {
  6452. // FIXME: This is a hack. Until we can reasonably combine the error types, just log the error
  6453. // and return ParseError::InternalError if we get an AK::Error result.
  6454. #define FIXME_TRY(expression) \
  6455. ({ \
  6456. /* Ignore -Wshadow to allow nesting the macro. */ \
  6457. AK_IGNORE_DIAGNOSTIC("-Wshadow", \
  6458. auto&& _temporary_result = (expression)); \
  6459. if (_temporary_result.is_error()) [[unlikely]] { \
  6460. dbgln("System error when parsing style value: {}", _temporary_result.release_error()); \
  6461. return ParseError::InternalError; \
  6462. } \
  6463. _temporary_result.release_value(); \
  6464. })
  6465. m_context.set_current_property_id(property_id);
  6466. Vector<ComponentValue> component_values;
  6467. bool contains_var_or_attr = false;
  6468. bool const property_accepts_custom_ident = property_accepts_type(property_id, ValueType::CustomIdent);
  6469. while (tokens.has_next_token()) {
  6470. auto const& token = tokens.next_token();
  6471. if (token.is(Token::Type::Semicolon)) {
  6472. tokens.reconsume_current_input_token();
  6473. break;
  6474. }
  6475. if (property_id != PropertyID::Custom) {
  6476. if (token.is(Token::Type::Whitespace))
  6477. continue;
  6478. if (!property_accepts_custom_ident && token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  6479. return ParseError::IncludesIgnoredVendorPrefix;
  6480. }
  6481. if (!contains_var_or_attr) {
  6482. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6483. contains_var_or_attr = true;
  6484. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  6485. contains_var_or_attr = true;
  6486. }
  6487. component_values.append(token);
  6488. }
  6489. if (property_id == PropertyID::Custom || contains_var_or_attr)
  6490. return FIXME_TRY(UnresolvedStyleValue::create(move(component_values), contains_var_or_attr));
  6491. if (component_values.is_empty())
  6492. return ParseError::SyntaxError;
  6493. if (component_values.size() == 1) {
  6494. if (auto parsed_value = FIXME_TRY(parse_builtin_value(component_values.first())))
  6495. return parsed_value.release_nonnull();
  6496. }
  6497. // Special-case property handling
  6498. switch (property_id) {
  6499. case PropertyID::AspectRatio:
  6500. if (auto parsed_value = FIXME_TRY(parse_aspect_ratio_value(component_values)))
  6501. return parsed_value.release_nonnull();
  6502. return ParseError::SyntaxError;
  6503. case PropertyID::BackdropFilter:
  6504. if (auto parsed_value = FIXME_TRY(parse_filter_value_list_value(component_values)))
  6505. return parsed_value.release_nonnull();
  6506. return ParseError::SyntaxError;
  6507. case PropertyID::Background:
  6508. if (auto parsed_value = FIXME_TRY(parse_background_value(component_values)))
  6509. return parsed_value.release_nonnull();
  6510. return ParseError::SyntaxError;
  6511. case PropertyID::BackgroundAttachment:
  6512. case PropertyID::BackgroundClip:
  6513. case PropertyID::BackgroundImage:
  6514. case PropertyID::BackgroundOrigin:
  6515. if (auto parsed_value = FIXME_TRY(parse_simple_comma_separated_value_list(property_id, component_values)))
  6516. return parsed_value.release_nonnull();
  6517. return ParseError::SyntaxError;
  6518. case PropertyID::BackgroundPosition:
  6519. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); })))
  6520. return parsed_value.release_nonnull();
  6521. return ParseError::SyntaxError;
  6522. case PropertyID::BackgroundPositionX:
  6523. case PropertyID::BackgroundPositionY:
  6524. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this, property_id](auto& tokens) { return parse_single_background_position_x_or_y_value(tokens, property_id); })))
  6525. return parsed_value.release_nonnull();
  6526. return ParseError::SyntaxError;
  6527. case PropertyID::BackgroundRepeat:
  6528. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); })))
  6529. return parsed_value.release_nonnull();
  6530. return ParseError::SyntaxError;
  6531. case PropertyID::BackgroundSize:
  6532. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); })))
  6533. return parsed_value.release_nonnull();
  6534. return ParseError::SyntaxError;
  6535. case PropertyID::Border:
  6536. case PropertyID::BorderBottom:
  6537. case PropertyID::BorderLeft:
  6538. case PropertyID::BorderRight:
  6539. case PropertyID::BorderTop:
  6540. if (auto parsed_value = FIXME_TRY(parse_border_value(component_values)))
  6541. return parsed_value.release_nonnull();
  6542. return ParseError::SyntaxError;
  6543. case PropertyID::BorderTopLeftRadius:
  6544. case PropertyID::BorderTopRightRadius:
  6545. case PropertyID::BorderBottomRightRadius:
  6546. case PropertyID::BorderBottomLeftRadius:
  6547. if (auto parsed_value = FIXME_TRY(parse_border_radius_value(component_values)))
  6548. return parsed_value.release_nonnull();
  6549. return ParseError::SyntaxError;
  6550. case PropertyID::BorderRadius:
  6551. if (auto parsed_value = FIXME_TRY(parse_border_radius_shorthand_value(component_values)))
  6552. return parsed_value.release_nonnull();
  6553. return ParseError::SyntaxError;
  6554. case PropertyID::BoxShadow:
  6555. if (auto parsed_value = FIXME_TRY(parse_shadow_value(component_values, AllowInsetKeyword::Yes)))
  6556. return parsed_value.release_nonnull();
  6557. return ParseError::SyntaxError;
  6558. case PropertyID::Content:
  6559. if (auto parsed_value = FIXME_TRY(parse_content_value(component_values)))
  6560. return parsed_value.release_nonnull();
  6561. return ParseError::SyntaxError;
  6562. case PropertyID::Display:
  6563. if (auto parsed_value = FIXME_TRY(parse_display_value(component_values)))
  6564. return parsed_value.release_nonnull();
  6565. return ParseError::SyntaxError;
  6566. case PropertyID::Flex:
  6567. if (auto parsed_value = FIXME_TRY(parse_flex_value(component_values)))
  6568. return parsed_value.release_nonnull();
  6569. return ParseError::SyntaxError;
  6570. case PropertyID::FlexFlow:
  6571. if (auto parsed_value = FIXME_TRY(parse_flex_flow_value(component_values)))
  6572. return parsed_value.release_nonnull();
  6573. return ParseError::SyntaxError;
  6574. case PropertyID::Font:
  6575. if (auto parsed_value = FIXME_TRY(parse_font_value(component_values)))
  6576. return parsed_value.release_nonnull();
  6577. return ParseError::SyntaxError;
  6578. case PropertyID::FontFamily: {
  6579. auto tokens_without_whitespace = TokenStream { component_values };
  6580. if (auto parsed_value = FIXME_TRY(parse_font_family_value(tokens_without_whitespace)))
  6581. return parsed_value.release_nonnull();
  6582. return ParseError::SyntaxError;
  6583. }
  6584. case PropertyID::GridColumn:
  6585. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement_shorthand_value(component_values)))
  6586. return parsed_value.release_nonnull();
  6587. return ParseError::SyntaxError;
  6588. case PropertyID::GridArea:
  6589. if (auto parsed_value = FIXME_TRY(parse_grid_area_shorthand_value(component_values)))
  6590. return parsed_value.release_nonnull();
  6591. return ParseError::SyntaxError;
  6592. case PropertyID::GridTemplateAreas:
  6593. if (auto parsed_value = FIXME_TRY(parse_grid_template_areas_value(component_values)))
  6594. return parsed_value.release_nonnull();
  6595. return ParseError::SyntaxError;
  6596. case PropertyID::GridColumnEnd:
  6597. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6598. return parsed_value.release_nonnull();
  6599. return ParseError::SyntaxError;
  6600. case PropertyID::GridColumnStart:
  6601. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6602. return parsed_value.release_nonnull();
  6603. return ParseError::SyntaxError;
  6604. case PropertyID::GridRow:
  6605. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement_shorthand_value(component_values)))
  6606. return parsed_value.release_nonnull();
  6607. return ParseError::SyntaxError;
  6608. case PropertyID::GridRowEnd:
  6609. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6610. return parsed_value.release_nonnull();
  6611. return ParseError::SyntaxError;
  6612. case PropertyID::GridRowStart:
  6613. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6614. return parsed_value.release_nonnull();
  6615. return ParseError::SyntaxError;
  6616. case PropertyID::Grid:
  6617. if (auto parsed_value = FIXME_TRY(parse_grid_shorthand_value(component_values)))
  6618. return parsed_value.release_nonnull();
  6619. return ParseError::SyntaxError;
  6620. case PropertyID::GridTemplate:
  6621. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list_shorthand_value(component_values)))
  6622. return parsed_value.release_nonnull();
  6623. return ParseError::SyntaxError;
  6624. case PropertyID::GridTemplateColumns:
  6625. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list(component_values)))
  6626. return parsed_value.release_nonnull();
  6627. return ParseError::SyntaxError;
  6628. case PropertyID::GridTemplateRows:
  6629. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list(component_values)))
  6630. return parsed_value.release_nonnull();
  6631. return ParseError::SyntaxError;
  6632. case PropertyID::GridAutoColumns:
  6633. if (auto parsed_value = FIXME_TRY(parse_grid_auto_track_sizes(component_values)))
  6634. return parsed_value.release_nonnull();
  6635. return ParseError::SyntaxError;
  6636. case PropertyID::GridAutoRows:
  6637. if (auto parsed_value = FIXME_TRY(parse_grid_auto_track_sizes(component_values)))
  6638. return parsed_value.release_nonnull();
  6639. return ParseError::SyntaxError;
  6640. case PropertyID::ListStyle:
  6641. if (auto parsed_value = FIXME_TRY(parse_list_style_value(component_values)))
  6642. return parsed_value.release_nonnull();
  6643. return ParseError::SyntaxError;
  6644. case PropertyID::Overflow:
  6645. if (auto parsed_value = FIXME_TRY(parse_overflow_value(component_values)))
  6646. return parsed_value.release_nonnull();
  6647. return ParseError::SyntaxError;
  6648. case PropertyID::PlaceContent:
  6649. if (auto parsed_value = FIXME_TRY(parse_place_content_value(component_values)))
  6650. return parsed_value.release_nonnull();
  6651. return ParseError::SyntaxError;
  6652. case PropertyID::PlaceItems:
  6653. if (auto parsed_value = FIXME_TRY(parse_place_items_value(component_values)))
  6654. return parsed_value.release_nonnull();
  6655. return ParseError::SyntaxError;
  6656. case PropertyID::PlaceSelf:
  6657. if (auto parsed_value = FIXME_TRY(parse_place_self_value(component_values)))
  6658. return parsed_value.release_nonnull();
  6659. return ParseError::SyntaxError;
  6660. case PropertyID::TextDecoration:
  6661. if (auto parsed_value = FIXME_TRY(parse_text_decoration_value(component_values)))
  6662. return parsed_value.release_nonnull();
  6663. return ParseError::SyntaxError;
  6664. case PropertyID::TextDecorationLine: {
  6665. TokenStream value_tokens { component_values };
  6666. auto parsed_value = FIXME_TRY(parse_text_decoration_line_value(value_tokens));
  6667. if (parsed_value && !value_tokens.has_next_token())
  6668. return parsed_value.release_nonnull();
  6669. return ParseError::SyntaxError;
  6670. }
  6671. case PropertyID::TextShadow:
  6672. if (auto parsed_value = FIXME_TRY(parse_shadow_value(component_values, AllowInsetKeyword::No)))
  6673. return parsed_value.release_nonnull();
  6674. return ParseError::SyntaxError;
  6675. case PropertyID::Transform:
  6676. if (auto parsed_value = FIXME_TRY(parse_transform_value(component_values)))
  6677. return parsed_value.release_nonnull();
  6678. return ParseError::SyntaxError;
  6679. case PropertyID::TransformOrigin:
  6680. if (auto parsed_value = FIXME_TRY(parse_transform_origin_value(component_values)))
  6681. return parsed_value.release_nonnull();
  6682. return ParseError ::SyntaxError;
  6683. default:
  6684. break;
  6685. }
  6686. // If there's only 1 ComponentValue, we can only produce a single StyleValue.
  6687. if (component_values.size() == 1) {
  6688. auto stream = TokenStream { component_values };
  6689. if (auto parsed_value = FIXME_TRY(parse_css_value_for_property(property_id, stream)))
  6690. return parsed_value.release_nonnull();
  6691. } else {
  6692. StyleValueVector parsed_values;
  6693. auto stream = TokenStream { component_values };
  6694. while (auto parsed_value = FIXME_TRY(parse_css_value_for_property(property_id, stream))) {
  6695. FIXME_TRY(parsed_values.try_append(parsed_value.release_nonnull()));
  6696. if (!stream.has_next_token())
  6697. break;
  6698. }
  6699. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 StyleValue, return it directly.
  6700. if (parsed_values.size() == 1)
  6701. return *parsed_values.take_first();
  6702. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  6703. return FIXME_TRY(StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space));
  6704. }
  6705. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  6706. auto unassigned_properties = longhands_for_shorthand(property_id);
  6707. if (unassigned_properties.is_empty())
  6708. return ParseError::SyntaxError;
  6709. auto stream = TokenStream { component_values };
  6710. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<StyleValue const>>> assigned_values;
  6711. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  6712. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  6713. if (!property_and_value.is_error() && property_and_value.value().style_value) {
  6714. auto property = property_and_value.value().property;
  6715. auto value = property_and_value.release_value().style_value;
  6716. auto& values = assigned_values.ensure(to_underlying(property));
  6717. if (values.size() + 1 == property_maximum_value_count(property)) {
  6718. // We're done with this property, move on to the next one.
  6719. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  6720. }
  6721. values.append(value.release_nonnull());
  6722. continue;
  6723. }
  6724. // No property matched, so we're done.
  6725. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.peek_token().to_debug_string());
  6726. for (auto id : unassigned_properties)
  6727. dbgln(" {}", string_from_property_id(id));
  6728. break;
  6729. }
  6730. for (auto& property : unassigned_properties)
  6731. assigned_values.ensure(to_underlying(property)).append(FIXME_TRY(property_initial_value(m_context.realm(), property)));
  6732. stream.skip_whitespace();
  6733. if (stream.has_next_token())
  6734. return ParseError::SyntaxError;
  6735. Vector<PropertyID> longhand_properties;
  6736. longhand_properties.ensure_capacity(assigned_values.size());
  6737. for (auto& it : assigned_values)
  6738. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  6739. StyleValueVector longhand_values;
  6740. longhand_values.ensure_capacity(assigned_values.size());
  6741. for (auto& it : assigned_values) {
  6742. if (it.value.size() == 1)
  6743. longhand_values.unchecked_append(it.value.take_first());
  6744. else
  6745. longhand_values.unchecked_append(FIXME_TRY(StyleValueList::create(move(it.value), StyleValueList::Separator::Space)));
  6746. }
  6747. return { FIXME_TRY(CompositeStyleValue::create(move(longhand_properties), move(longhand_values))) };
  6748. #undef FIXME_TRY
  6749. }
  6750. ErrorOr<RefPtr<StyleValue>> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6751. {
  6752. auto result = parse_css_value_for_properties({ &property_id, 1 }, tokens);
  6753. if (result.is_error())
  6754. return result.release_error();
  6755. return result.value().style_value;
  6756. }
  6757. ErrorOr<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  6758. {
  6759. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  6760. for (auto const& property : property_ids) {
  6761. if (property_accepts_type(property, value_type))
  6762. return property;
  6763. }
  6764. return {};
  6765. };
  6766. auto any_property_accepts_type_percentage = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  6767. for (auto const& property : property_ids) {
  6768. if (property_accepts_type(property, value_type) && property_accepts_type(property, ValueType::Percentage))
  6769. return property;
  6770. }
  6771. return {};
  6772. };
  6773. auto any_property_accepts_identifier = [](ReadonlySpan<PropertyID> property_ids, ValueID identifier) -> Optional<PropertyID> {
  6774. for (auto const& property : property_ids) {
  6775. if (property_accepts_identifier(property, identifier))
  6776. return property;
  6777. }
  6778. return {};
  6779. };
  6780. auto& peek_token = tokens.peek_token();
  6781. if (auto property = any_property_accepts_type(property_ids, ValueType::EasingFunction); property.has_value()) {
  6782. if (auto maybe_easing_function = TRY(parse_easing_value(tokens)))
  6783. return PropertyAndValue { *property, maybe_easing_function };
  6784. }
  6785. if (peek_token.is(Token::Type::Ident)) {
  6786. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  6787. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  6788. auto ident = value_id_from_string(peek_token.token().ident());
  6789. if (ident.has_value()) {
  6790. if (auto property = any_property_accepts_identifier(property_ids, ident.value()); property.has_value()) {
  6791. (void)tokens.next_token();
  6792. return PropertyAndValue { *property, TRY(IdentifierStyleValue::create(ident.value())) };
  6793. }
  6794. }
  6795. // Custom idents
  6796. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  6797. (void)tokens.next_token();
  6798. return PropertyAndValue { *property, TRY(CustomIdentStyleValue::create(TRY(FlyString::from_utf8(peek_token.token().ident())))) };
  6799. }
  6800. }
  6801. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  6802. if (auto maybe_color = TRY(parse_color_value(peek_token))) {
  6803. (void)tokens.next_token();
  6804. return PropertyAndValue { *property, maybe_color };
  6805. }
  6806. }
  6807. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  6808. if (auto maybe_image = TRY(parse_image_value(peek_token))) {
  6809. (void)tokens.next_token();
  6810. return PropertyAndValue { *property, maybe_image };
  6811. }
  6812. }
  6813. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  6814. if (auto maybe_ratio = TRY(parse_ratio_value(tokens)))
  6815. return PropertyAndValue { *property, maybe_ratio };
  6816. }
  6817. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  6818. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  6819. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  6820. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  6821. if (property_accepting_integer.has_value()) {
  6822. auto transaction = tokens.begin_transaction();
  6823. if (auto integer = TRY(parse_integer_value(tokens)); integer && property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  6824. transaction.commit();
  6825. return PropertyAndValue { *property_accepting_integer, integer };
  6826. }
  6827. }
  6828. if (property_accepting_number.has_value()) {
  6829. auto transaction = tokens.begin_transaction();
  6830. if (auto number = TRY(parse_number_value(tokens)); number && property_accepts_number(*property_accepting_number, number->as_number().number())) {
  6831. transaction.commit();
  6832. return PropertyAndValue { *property_accepting_number, number };
  6833. }
  6834. }
  6835. }
  6836. if (peek_token.is(Token::Type::Percentage)) {
  6837. auto percentage = Percentage(peek_token.token().percentage());
  6838. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  6839. (void)tokens.next_token();
  6840. return PropertyAndValue { *property, TRY(PercentageStyleValue::create(percentage)) };
  6841. }
  6842. }
  6843. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  6844. if (auto maybe_rect = TRY(parse_rect_value(peek_token))) {
  6845. (void)tokens.next_token();
  6846. return PropertyAndValue { *property, maybe_rect };
  6847. }
  6848. }
  6849. if (peek_token.is(Token::Type::String)) {
  6850. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  6851. return PropertyAndValue { *property, TRY(StringStyleValue::create(TRY(String::from_utf8(tokens.next_token().token().string())))) };
  6852. }
  6853. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  6854. if (auto url = TRY(parse_url_value(peek_token))) {
  6855. (void)tokens.next_token();
  6856. return PropertyAndValue { *property, url };
  6857. }
  6858. }
  6859. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  6860. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  6861. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  6862. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  6863. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  6864. if (property_accepts_dimension) {
  6865. auto transaction = tokens.begin_transaction();
  6866. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  6867. (void)tokens.next_token();
  6868. auto dimension = maybe_dimension.release_value();
  6869. if (dimension.is_angle()) {
  6870. auto angle = dimension.angle();
  6871. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  6872. transaction.commit();
  6873. return PropertyAndValue { *property, TRY(AngleStyleValue::create(angle)) };
  6874. }
  6875. }
  6876. if (dimension.is_frequency()) {
  6877. auto frequency = dimension.frequency();
  6878. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  6879. transaction.commit();
  6880. return PropertyAndValue { *property, TRY(FrequencyStyleValue::create(frequency)) };
  6881. }
  6882. }
  6883. if (dimension.is_length()) {
  6884. auto length = dimension.length();
  6885. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  6886. transaction.commit();
  6887. return PropertyAndValue { *property, TRY(LengthStyleValue::create(length)) };
  6888. }
  6889. }
  6890. if (dimension.is_resolution()) {
  6891. auto resolution = dimension.resolution();
  6892. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  6893. transaction.commit();
  6894. return PropertyAndValue { *property, TRY(ResolutionStyleValue::create(resolution)) };
  6895. }
  6896. }
  6897. if (dimension.is_time()) {
  6898. auto time = dimension.time();
  6899. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  6900. transaction.commit();
  6901. return PropertyAndValue { *property, TRY(TimeStyleValue::create(time)) };
  6902. }
  6903. }
  6904. }
  6905. }
  6906. // In order to not end up parsing `calc()` and other math expressions multiple times,
  6907. // we parse it once, and then see if its resolved type matches what the property accepts.
  6908. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  6909. if (auto maybe_dynamic = TRY(parse_dynamic_value(peek_token)); maybe_dynamic && maybe_dynamic->is_calculated()) {
  6910. (void)tokens.next_token();
  6911. auto& calculated = maybe_dynamic->as_calculated();
  6912. // This is a bit sensitive to ordering: `<foo>` and `<percentage>` have to be checked before `<foo-percentage>`.
  6913. if (calculated.resolves_to_percentage()) {
  6914. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  6915. return PropertyAndValue { *property, calculated };
  6916. } else if (calculated.resolves_to_angle()) {
  6917. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  6918. return PropertyAndValue { *property, calculated };
  6919. } else if (calculated.resolves_to_angle_percentage()) {
  6920. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Angle); property.has_value())
  6921. return PropertyAndValue { *property, calculated };
  6922. } else if (calculated.resolves_to_frequency()) {
  6923. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  6924. return PropertyAndValue { *property, calculated };
  6925. } else if (calculated.resolves_to_frequency_percentage()) {
  6926. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Frequency); property.has_value())
  6927. return PropertyAndValue { *property, calculated };
  6928. } else if (calculated.resolves_to_number()) {
  6929. if (property_accepts_numeric) {
  6930. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  6931. return PropertyAndValue { property_or_resolved, calculated };
  6932. }
  6933. } else if (calculated.resolves_to_number_percentage()) {
  6934. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Number); property.has_value())
  6935. return PropertyAndValue { *property, calculated };
  6936. } else if (calculated.resolves_to_length()) {
  6937. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  6938. return PropertyAndValue { *property, calculated };
  6939. } else if (calculated.resolves_to_length_percentage()) {
  6940. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Length); property.has_value())
  6941. return PropertyAndValue { *property, calculated };
  6942. } else if (calculated.resolves_to_time()) {
  6943. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  6944. return PropertyAndValue { *property, calculated };
  6945. } else if (calculated.resolves_to_time_percentage()) {
  6946. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Time); property.has_value())
  6947. return PropertyAndValue { *property, calculated };
  6948. }
  6949. }
  6950. }
  6951. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  6952. if (auto value = TRY(parse_paint_value(tokens)))
  6953. return PropertyAndValue { *property, value.release_nonnull() };
  6954. }
  6955. return PropertyAndValue { property_ids.first(), nullptr };
  6956. }
  6957. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<ComponentValue>& values)
  6958. {
  6959. auto transaction = values.begin_transaction();
  6960. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  6961. if constexpr (CSS_PARSER_DEBUG) {
  6962. dbgln_if(CSS_PARSER_DEBUG, "Invalid An+B value:");
  6963. values.dump_all_tokens();
  6964. }
  6965. return {};
  6966. };
  6967. auto is_n = [](ComponentValue const& value) -> bool {
  6968. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n"sv);
  6969. };
  6970. auto is_ndash = [](ComponentValue const& value) -> bool {
  6971. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n-"sv);
  6972. };
  6973. auto is_dashn = [](ComponentValue const& value) -> bool {
  6974. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n"sv);
  6975. };
  6976. auto is_dashndash = [](ComponentValue const& value) -> bool {
  6977. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n-"sv);
  6978. };
  6979. auto is_sign = [](ComponentValue const& value) -> bool {
  6980. return value.is(Token::Type::Delim) && (value.token().delim() == '+' || value.token().delim() == '-');
  6981. };
  6982. auto is_n_dimension = [](ComponentValue const& value) -> bool {
  6983. if (!value.is(Token::Type::Dimension))
  6984. return false;
  6985. if (!value.token().number().is_integer())
  6986. return false;
  6987. if (!value.token().dimension_unit().equals_ignoring_ascii_case("n"sv))
  6988. return false;
  6989. return true;
  6990. };
  6991. auto is_ndash_dimension = [](ComponentValue const& value) -> bool {
  6992. if (!value.is(Token::Type::Dimension))
  6993. return false;
  6994. if (!value.token().number().is_integer())
  6995. return false;
  6996. if (!value.token().dimension_unit().equals_ignoring_ascii_case("n-"sv))
  6997. return false;
  6998. return true;
  6999. };
  7000. auto is_ndashdigit_dimension = [](ComponentValue const& value) -> bool {
  7001. if (!value.is(Token::Type::Dimension))
  7002. return false;
  7003. if (!value.token().number().is_integer())
  7004. return false;
  7005. auto dimension_unit = value.token().dimension_unit();
  7006. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  7007. return false;
  7008. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  7009. if (!is_ascii_digit(dimension_unit[i]))
  7010. return false;
  7011. }
  7012. return true;
  7013. };
  7014. auto is_ndashdigit_ident = [](ComponentValue const& value) -> bool {
  7015. if (!value.is(Token::Type::Ident))
  7016. return false;
  7017. auto ident = value.token().ident();
  7018. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  7019. return false;
  7020. for (size_t i = 2; i < ident.length(); ++i) {
  7021. if (!is_ascii_digit(ident[i]))
  7022. return false;
  7023. }
  7024. return true;
  7025. };
  7026. auto is_dashndashdigit_ident = [](ComponentValue const& value) -> bool {
  7027. if (!value.is(Token::Type::Ident))
  7028. return false;
  7029. auto ident = value.token().ident();
  7030. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  7031. return false;
  7032. if (ident.length() == 3)
  7033. return false;
  7034. for (size_t i = 3; i < ident.length(); ++i) {
  7035. if (!is_ascii_digit(ident[i]))
  7036. return false;
  7037. }
  7038. return true;
  7039. };
  7040. auto is_integer = [](ComponentValue const& value) -> bool {
  7041. return value.is(Token::Type::Number) && value.token().number().is_integer();
  7042. };
  7043. auto is_signed_integer = [](ComponentValue const& value) -> bool {
  7044. return value.is(Token::Type::Number) && value.token().number().is_integer_with_explicit_sign();
  7045. };
  7046. auto is_signless_integer = [](ComponentValue const& value) -> bool {
  7047. return value.is(Token::Type::Number) && !value.token().number().is_integer_with_explicit_sign();
  7048. };
  7049. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  7050. // Unfortunately these can't be in the same order as in the spec.
  7051. values.skip_whitespace();
  7052. auto const& first_value = values.next_token();
  7053. // odd | even
  7054. if (first_value.is(Token::Type::Ident)) {
  7055. auto ident = first_value.token().ident();
  7056. if (ident.equals_ignoring_ascii_case("odd"sv)) {
  7057. transaction.commit();
  7058. return Selector::SimpleSelector::ANPlusBPattern { 2, 1 };
  7059. }
  7060. if (ident.equals_ignoring_ascii_case("even"sv)) {
  7061. transaction.commit();
  7062. return Selector::SimpleSelector::ANPlusBPattern { 2, 0 };
  7063. }
  7064. }
  7065. // <integer>
  7066. if (is_integer(first_value)) {
  7067. int b = first_value.token().to_integer();
  7068. transaction.commit();
  7069. return Selector::SimpleSelector::ANPlusBPattern { 0, b };
  7070. }
  7071. // <n-dimension>
  7072. // <n-dimension> <signed-integer>
  7073. // <n-dimension> ['+' | '-'] <signless-integer>
  7074. if (is_n_dimension(first_value)) {
  7075. int a = first_value.token().dimension_value_int();
  7076. values.skip_whitespace();
  7077. // <n-dimension> <signed-integer>
  7078. if (is_signed_integer(values.peek_token())) {
  7079. int b = values.next_token().token().to_integer();
  7080. transaction.commit();
  7081. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  7082. }
  7083. // <n-dimension> ['+' | '-'] <signless-integer>
  7084. {
  7085. auto child_transaction = transaction.create_child();
  7086. auto const& second_value = values.next_token();
  7087. values.skip_whitespace();
  7088. auto const& third_value = values.next_token();
  7089. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7090. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7091. child_transaction.commit();
  7092. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  7093. }
  7094. }
  7095. // <n-dimension>
  7096. transaction.commit();
  7097. return Selector::SimpleSelector::ANPlusBPattern { a, 0 };
  7098. }
  7099. // <ndash-dimension> <signless-integer>
  7100. if (is_ndash_dimension(first_value)) {
  7101. values.skip_whitespace();
  7102. auto const& second_value = values.next_token();
  7103. if (is_signless_integer(second_value)) {
  7104. int a = first_value.token().dimension_value_int();
  7105. int b = -second_value.token().to_integer();
  7106. transaction.commit();
  7107. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  7108. }
  7109. return syntax_error();
  7110. }
  7111. // <ndashdigit-dimension>
  7112. if (is_ndashdigit_dimension(first_value)) {
  7113. auto const& dimension = first_value.token();
  7114. int a = dimension.dimension_value_int();
  7115. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  7116. if (maybe_b.has_value()) {
  7117. transaction.commit();
  7118. return Selector::SimpleSelector::ANPlusBPattern { a, maybe_b.value() };
  7119. }
  7120. return syntax_error();
  7121. }
  7122. // <dashndashdigit-ident>
  7123. if (is_dashndashdigit_ident(first_value)) {
  7124. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  7125. if (maybe_b.has_value()) {
  7126. transaction.commit();
  7127. return Selector::SimpleSelector::ANPlusBPattern { -1, maybe_b.value() };
  7128. }
  7129. return syntax_error();
  7130. }
  7131. // -n
  7132. // -n <signed-integer>
  7133. // -n ['+' | '-'] <signless-integer>
  7134. if (is_dashn(first_value)) {
  7135. values.skip_whitespace();
  7136. // -n <signed-integer>
  7137. if (is_signed_integer(values.peek_token())) {
  7138. int b = values.next_token().token().to_integer();
  7139. transaction.commit();
  7140. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7141. }
  7142. // -n ['+' | '-'] <signless-integer>
  7143. {
  7144. auto child_transaction = transaction.create_child();
  7145. auto const& second_value = values.next_token();
  7146. values.skip_whitespace();
  7147. auto const& third_value = values.next_token();
  7148. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7149. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7150. child_transaction.commit();
  7151. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7152. }
  7153. }
  7154. // -n
  7155. transaction.commit();
  7156. return Selector::SimpleSelector::ANPlusBPattern { -1, 0 };
  7157. }
  7158. // -n- <signless-integer>
  7159. if (is_dashndash(first_value)) {
  7160. values.skip_whitespace();
  7161. auto const& second_value = values.next_token();
  7162. if (is_signless_integer(second_value)) {
  7163. int b = -second_value.token().to_integer();
  7164. transaction.commit();
  7165. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7166. }
  7167. return syntax_error();
  7168. }
  7169. // All that's left now are these:
  7170. // '+'?† n
  7171. // '+'?† n <signed-integer>
  7172. // '+'?† n ['+' | '-'] <signless-integer>
  7173. // '+'?† n- <signless-integer>
  7174. // '+'?† <ndashdigit-ident>
  7175. // In all of these cases, the + is optional, and has no effect.
  7176. // So, we just skip the +, and carry on.
  7177. if (!first_value.is_delim('+')) {
  7178. values.reconsume_current_input_token();
  7179. // We do *not* skip whitespace here.
  7180. }
  7181. auto const& first_after_plus = values.next_token();
  7182. // '+'?† n
  7183. // '+'?† n <signed-integer>
  7184. // '+'?† n ['+' | '-'] <signless-integer>
  7185. if (is_n(first_after_plus)) {
  7186. values.skip_whitespace();
  7187. // '+'?† n <signed-integer>
  7188. if (is_signed_integer(values.peek_token())) {
  7189. int b = values.next_token().token().to_integer();
  7190. transaction.commit();
  7191. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7192. }
  7193. // '+'?† n ['+' | '-'] <signless-integer>
  7194. {
  7195. auto child_transaction = transaction.create_child();
  7196. auto const& second_value = values.next_token();
  7197. values.skip_whitespace();
  7198. auto const& third_value = values.next_token();
  7199. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7200. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7201. child_transaction.commit();
  7202. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7203. }
  7204. }
  7205. // '+'?† n
  7206. transaction.commit();
  7207. return Selector::SimpleSelector::ANPlusBPattern { 1, 0 };
  7208. }
  7209. // '+'?† n- <signless-integer>
  7210. if (is_ndash(first_after_plus)) {
  7211. values.skip_whitespace();
  7212. auto const& second_value = values.next_token();
  7213. if (is_signless_integer(second_value)) {
  7214. int b = -second_value.token().to_integer();
  7215. transaction.commit();
  7216. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7217. }
  7218. return syntax_error();
  7219. }
  7220. // '+'?† <ndashdigit-ident>
  7221. if (is_ndashdigit_ident(first_after_plus)) {
  7222. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  7223. if (maybe_b.has_value()) {
  7224. transaction.commit();
  7225. return Selector::SimpleSelector::ANPlusBPattern { 1, maybe_b.value() };
  7226. }
  7227. return syntax_error();
  7228. }
  7229. return syntax_error();
  7230. }
  7231. class UnparsedCalculationNode final : public CalculationNode {
  7232. public:
  7233. static ErrorOr<NonnullOwnPtr<UnparsedCalculationNode>> create(ComponentValue component_value)
  7234. {
  7235. return adopt_nonnull_own_or_enomem(new (nothrow) UnparsedCalculationNode(move(component_value)));
  7236. }
  7237. virtual ~UnparsedCalculationNode() = default;
  7238. ComponentValue& component_value() { return m_component_value; }
  7239. virtual ErrorOr<String> to_string() const override { VERIFY_NOT_REACHED(); }
  7240. virtual Optional<CalculatedStyleValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  7241. virtual Optional<CSSNumericType> determine_type(Web::CSS::PropertyID) const override { VERIFY_NOT_REACHED(); }
  7242. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  7243. virtual CalculatedStyleValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  7244. virtual ErrorOr<void> dump(StringBuilder& builder, int indent) const override
  7245. {
  7246. return builder.try_appendff("{: >{}}UNPARSED({})\n", "", indent, TRY(m_component_value.to_debug_string()));
  7247. }
  7248. private:
  7249. UnparsedCalculationNode(ComponentValue component_value)
  7250. : CalculationNode(Type::Unparsed)
  7251. , m_component_value(move(component_value))
  7252. {
  7253. }
  7254. ComponentValue m_component_value;
  7255. };
  7256. // https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
  7257. LengthOrCalculated Parser::Parser::parse_as_sizes_attribute()
  7258. {
  7259. // 1. Let unparsed sizes list be the result of parsing a comma-separated list of component values
  7260. // from the value of element's sizes attribute (or the empty string, if the attribute is absent).
  7261. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  7262. // 2. Let size be null.
  7263. Optional<LengthOrCalculated> size;
  7264. // 3. For each unparsed size in unparsed sizes list:
  7265. for (auto& unparsed_size : unparsed_sizes_list) {
  7266. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7267. // If unparsed size is now empty, that is a parse error; continue.
  7268. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  7269. unparsed_size.take_last();
  7270. if (unparsed_size.is_empty()) {
  7271. log_parse_error();
  7272. continue;
  7273. }
  7274. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  7275. // let size be its value and remove the component value from unparsed size.
  7276. // FIXME: Any CSS function other than the math functions is invalid.
  7277. // Otherwise, there is a parse error; continue.
  7278. if (auto source_size_value = parse_source_size_value(unparsed_size.last()); source_size_value.has_value()) {
  7279. size = source_size_value.value();
  7280. unparsed_size.take_last();
  7281. } else {
  7282. log_parse_error();
  7283. continue;
  7284. }
  7285. // 3. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7286. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  7287. unparsed_size.take_last();
  7288. // If unparsed size is now empty, then return size.
  7289. if (unparsed_size.is_empty())
  7290. return size.value();
  7291. // FIXME: If this was not the keyword auto and it was not the last item in unparsed sizes list, that is a parse error.
  7292. // 4. Parse the remaining component values in unparsed size as a <media-condition>.
  7293. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  7294. TokenStream<ComponentValue> token_stream { unparsed_size };
  7295. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  7296. if (media_condition && media_condition->evaluate(*m_context.window()) == MatchResult::True) {
  7297. return size.value();
  7298. } else {
  7299. continue;
  7300. }
  7301. // 5. If size is not auto, then return size.
  7302. if (size.value().is_calculated() || !size.value().value().is_auto())
  7303. return size.value();
  7304. }
  7305. return Length(100, Length::Type::Vw);
  7306. }
  7307. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  7308. ErrorOr<OwnPtr<CalculationNode>> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  7309. {
  7310. // 1. Discard any <whitespace-token>s from values.
  7311. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  7312. struct Operator {
  7313. char delim;
  7314. };
  7315. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  7316. Vector<Value> values;
  7317. for (auto& value : original_values) {
  7318. if (value.is(Token::Type::Whitespace))
  7319. continue;
  7320. if (value.is(Token::Type::Delim)) {
  7321. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  7322. // NOTE: Sequential operators are invalid syntax.
  7323. if (!values.is_empty() && values.last().has<Operator>())
  7324. return nullptr;
  7325. TRY(values.try_append(Operator { static_cast<char>(value.token().delim()) }));
  7326. continue;
  7327. }
  7328. }
  7329. if (value.is(Token::Type::Ident)) {
  7330. auto maybe_constant = CalculationNode::constant_type_from_string(value.token().ident());
  7331. if (maybe_constant.has_value()) {
  7332. TRY(values.try_append({ TRY(ConstantCalculationNode::create(maybe_constant.value())) }));
  7333. continue;
  7334. }
  7335. }
  7336. if (value.is(Token::Type::Number)) {
  7337. TRY(values.try_append({ TRY(NumericCalculationNode::create(value.token().number())) }));
  7338. continue;
  7339. }
  7340. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  7341. if (dimension->is_angle())
  7342. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->angle())) }));
  7343. else if (dimension->is_frequency())
  7344. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->frequency())) }));
  7345. else if (dimension->is_length())
  7346. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->length())) }));
  7347. else if (dimension->is_percentage())
  7348. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->percentage())) }));
  7349. // FIXME: Resolutions, once calc() supports them.
  7350. else if (dimension->is_time())
  7351. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->time())) }));
  7352. else
  7353. VERIFY_NOT_REACHED();
  7354. continue;
  7355. }
  7356. TRY(values.try_append({ TRY(UnparsedCalculationNode::create(value)) }));
  7357. }
  7358. // If we have no values, the syntax is invalid.
  7359. if (values.is_empty())
  7360. return nullptr;
  7361. // NOTE: If the first or last value is an operator, the syntax is invalid.
  7362. if (values.first().has<Operator>() || values.last().has<Operator>())
  7363. return nullptr;
  7364. // 3. Collect children into Product and Invert nodes.
  7365. // For every consecutive run of value items in values separated by "*" or "/" operators:
  7366. while (true) {
  7367. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  7368. return item.template has<Operator>()
  7369. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  7370. });
  7371. if (!first_product_operator.has_value())
  7372. break;
  7373. auto start_of_run = first_product_operator.value() - 1;
  7374. auto end_of_run = first_product_operator.value() + 1;
  7375. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  7376. auto& item = values[i];
  7377. if (!item.has<Operator>()) {
  7378. end_of_run = i - 1;
  7379. break;
  7380. }
  7381. auto delim = item.get<Operator>().delim;
  7382. if (!first_is_one_of(delim, '*', '/')) {
  7383. end_of_run = i - 1;
  7384. break;
  7385. }
  7386. }
  7387. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  7388. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  7389. TRY(run_values.try_append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>())));
  7390. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  7391. auto& operator_ = values[i].get<Operator>().delim;
  7392. auto& rhs = values[i + 1];
  7393. if (operator_ == '/') {
  7394. TRY(run_values.try_append(TRY(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())))));
  7395. continue;
  7396. }
  7397. VERIFY(operator_ == '*');
  7398. TRY(run_values.try_append(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7399. }
  7400. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  7401. auto product_node = TRY(ProductCalculationNode::create(move(run_values)));
  7402. values.remove(start_of_run, end_of_run - start_of_run + 1);
  7403. TRY(values.try_insert(start_of_run, { move(product_node) }));
  7404. }
  7405. // 4. Collect children into Sum and Negate nodes.
  7406. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  7407. {
  7408. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  7409. for (auto i = 0u; i < values.size(); ++i) {
  7410. auto& maybe_minus_operator = values[i];
  7411. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  7412. continue;
  7413. auto rhs_index = ++i;
  7414. auto& rhs = values[rhs_index];
  7415. NonnullOwnPtr<CalculationNode> negate_node = TRY(NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7416. values.remove(rhs_index);
  7417. values.insert(rhs_index, move(negate_node));
  7418. }
  7419. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  7420. if (values.size() == 1) {
  7421. TRY(values.first().visit(
  7422. [&](ComponentValue& component_value) -> ErrorOr<void> {
  7423. if (component_value.is_block() && component_value.block().is_paren())
  7424. single_value = TRY(UnparsedCalculationNode::create(component_value));
  7425. return {};
  7426. },
  7427. [&](NonnullOwnPtr<CalculationNode>& node) -> ErrorOr<void> {
  7428. if (node->type() == CalculationNode::Type::Product)
  7429. single_value = move(node);
  7430. return {};
  7431. },
  7432. [](auto&) -> ErrorOr<void> { return {}; }));
  7433. }
  7434. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  7435. if (!single_value.has_value()) {
  7436. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  7437. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  7438. TRY(value_items.try_ensure_capacity(values.size()));
  7439. for (auto& value : values) {
  7440. if (value.has<Operator>())
  7441. continue;
  7442. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  7443. }
  7444. single_value = TRY(SumCalculationNode::create(move(value_items)));
  7445. }
  7446. }
  7447. // 5. At this point values is a tree of Sum, Product, Negate, and Invert nodes, with other types of values at the leaf nodes. Process the leaf nodes.
  7448. // For every leaf node leaf in values:
  7449. bool parsing_failed_for_child_node = false;
  7450. TRY(single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) -> ErrorOr<void> {
  7451. if (node->type() != CalculationNode::Type::Unparsed)
  7452. return {};
  7453. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  7454. auto& component_value = unparsed_node.component_value();
  7455. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  7456. if (component_value.is_block() && component_value.block().is_paren()) {
  7457. auto leaf_calculation = TRY(parse_a_calculation(component_value.block().values()));
  7458. if (!leaf_calculation) {
  7459. parsing_failed_for_child_node = true;
  7460. return {};
  7461. }
  7462. node = leaf_calculation.release_nonnull();
  7463. return {};
  7464. }
  7465. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  7466. // NOTE: All function tokens at this point should be math functions.
  7467. else if (component_value.is_function()) {
  7468. auto& function = component_value.function();
  7469. auto leaf_calculation = TRY(parse_a_calc_function_node(function));
  7470. if (!leaf_calculation) {
  7471. parsing_failed_for_child_node = true;
  7472. return {};
  7473. }
  7474. node = leaf_calculation.release_nonnull();
  7475. return {};
  7476. }
  7477. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  7478. // So, the calc() is invalid.
  7479. dbgln_if(CSS_PARSER_DEBUG, "Leftover UnparsedCalculationNode in calc tree! That probably means the syntax is invalid, but maybe we just didn't implement `{}` yet.", component_value.to_debug_string());
  7480. parsing_failed_for_child_node = true;
  7481. return {};
  7482. }));
  7483. if (parsing_failed_for_child_node)
  7484. return nullptr;
  7485. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  7486. return single_value.release_value();
  7487. }
  7488. bool Parser::has_ignored_vendor_prefix(StringView string)
  7489. {
  7490. if (!string.starts_with('-'))
  7491. return false;
  7492. if (string.starts_with("--"sv))
  7493. return false;
  7494. if (string.starts_with("-libweb-"sv))
  7495. return false;
  7496. return true;
  7497. }
  7498. bool Parser::is_builtin(StringView name)
  7499. {
  7500. return name.equals_ignoring_ascii_case("inherit"sv)
  7501. || name.equals_ignoring_ascii_case("initial"sv)
  7502. || name.equals_ignoring_ascii_case("unset"sv);
  7503. }
  7504. ErrorOr<RefPtr<CalculatedStyleValue>> Parser::parse_calculated_value(Badge<StyleComputer>, ParsingContext const& context, Vector<ComponentValue> const& tokens)
  7505. {
  7506. if (tokens.is_empty())
  7507. return nullptr;
  7508. auto parser = TRY(Parser::create(context, ""sv));
  7509. return parser.parse_calculated_value(tokens);
  7510. }
  7511. ErrorOr<RefPtr<StyleValue>> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext const& context, PropertyID property_id, Vector<ComponentValue> const& tokens)
  7512. {
  7513. if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
  7514. return nullptr;
  7515. auto parser = TRY(Parser::create(context, ""sv));
  7516. TokenStream<ComponentValue> token_stream { tokens };
  7517. auto result = parser.parse_css_value(property_id, token_stream);
  7518. if (result.is_error())
  7519. return nullptr;
  7520. return result.release_value();
  7521. }
  7522. bool Parser::Dimension::is_angle() const
  7523. {
  7524. return m_value.has<Angle>();
  7525. }
  7526. Angle Parser::Dimension::angle() const
  7527. {
  7528. return m_value.get<Angle>();
  7529. }
  7530. bool Parser::Dimension::is_angle_percentage() const
  7531. {
  7532. return is_angle() || is_percentage();
  7533. }
  7534. AnglePercentage Parser::Dimension::angle_percentage() const
  7535. {
  7536. if (is_angle())
  7537. return angle();
  7538. if (is_percentage())
  7539. return percentage();
  7540. VERIFY_NOT_REACHED();
  7541. }
  7542. bool Parser::Dimension::is_frequency() const
  7543. {
  7544. return m_value.has<Frequency>();
  7545. }
  7546. Frequency Parser::Dimension::frequency() const
  7547. {
  7548. return m_value.get<Frequency>();
  7549. }
  7550. bool Parser::Dimension::is_frequency_percentage() const
  7551. {
  7552. return is_frequency() || is_percentage();
  7553. }
  7554. FrequencyPercentage Parser::Dimension::frequency_percentage() const
  7555. {
  7556. if (is_frequency())
  7557. return frequency();
  7558. if (is_percentage())
  7559. return percentage();
  7560. VERIFY_NOT_REACHED();
  7561. }
  7562. bool Parser::Dimension::is_length() const
  7563. {
  7564. return m_value.has<Length>();
  7565. }
  7566. Length Parser::Dimension::length() const
  7567. {
  7568. return m_value.get<Length>();
  7569. }
  7570. bool Parser::Dimension::is_length_percentage() const
  7571. {
  7572. return is_length() || is_percentage();
  7573. }
  7574. LengthPercentage Parser::Dimension::length_percentage() const
  7575. {
  7576. if (is_length())
  7577. return length();
  7578. if (is_percentage())
  7579. return percentage();
  7580. VERIFY_NOT_REACHED();
  7581. }
  7582. bool Parser::Dimension::is_percentage() const
  7583. {
  7584. return m_value.has<Percentage>();
  7585. }
  7586. Percentage Parser::Dimension::percentage() const
  7587. {
  7588. return m_value.get<Percentage>();
  7589. }
  7590. bool Parser::Dimension::is_resolution() const
  7591. {
  7592. return m_value.has<Resolution>();
  7593. }
  7594. Resolution Parser::Dimension::resolution() const
  7595. {
  7596. return m_value.get<Resolution>();
  7597. }
  7598. bool Parser::Dimension::is_time() const
  7599. {
  7600. return m_value.has<Time>();
  7601. }
  7602. Time Parser::Dimension::time() const
  7603. {
  7604. return m_value.get<Time>();
  7605. }
  7606. bool Parser::Dimension::is_time_percentage() const
  7607. {
  7608. return is_time() || is_percentage();
  7609. }
  7610. TimePercentage Parser::Dimension::time_percentage() const
  7611. {
  7612. if (is_time())
  7613. return time();
  7614. if (is_percentage())
  7615. return percentage();
  7616. VERIFY_NOT_REACHED();
  7617. }
  7618. }