Parser.cpp 355 KB

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