Parser.cpp 360 KB

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