Parser.cpp 365 KB

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