Parser.cpp 356 KB

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