Parser.cpp 359 KB

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