Parser.cpp 355 KB

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