Parser.cpp 358 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665
  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<RefPtr<StyleValue>> Parser::parse_dynamic_value(ComponentValue const& component_value)
  3085. {
  3086. if (component_value.is_function()) {
  3087. auto const& function = component_value.function();
  3088. if (function.name().equals_ignoring_ascii_case("var"sv)) {
  3089. // Declarations using `var()` should already be parsed as an UnresolvedStyleValue before this point.
  3090. VERIFY_NOT_REACHED();
  3091. }
  3092. auto function_node = TRY(parse_a_calc_function_node(function));
  3093. if (!function_node)
  3094. return nullptr;
  3095. auto function_type = function_node->resolved_type();
  3096. if (!function_type.has_value())
  3097. return nullptr;
  3098. return CalculatedStyleValue::create(function_node.release_nonnull(), function_type.release_value());
  3099. }
  3100. return nullptr;
  3101. }
  3102. ErrorOr<OwnPtr<CalculationNode>> Parser::parse_a_calc_function_node(Function const& function)
  3103. {
  3104. if (function.name().equals_ignoring_ascii_case("calc"sv))
  3105. return TRY(parse_a_calculation(function.values()));
  3106. if (function.name().equals_ignoring_ascii_case("min"sv))
  3107. return TRY(parse_min_function(function));
  3108. if (function.name().equals_ignoring_ascii_case("max"sv))
  3109. return TRY(parse_max_function(function));
  3110. if (function.name().equals_ignoring_ascii_case("clamp"sv))
  3111. return TRY(parse_clamp_function(function));
  3112. if (function.name().equals_ignoring_ascii_case("abs"sv))
  3113. return TRY(parse_abs_function(function));
  3114. if (function.name().equals_ignoring_ascii_case("sign"sv))
  3115. return TRY(parse_sign_function(function));
  3116. dbgln_if(CSS_PARSER_DEBUG, "We didn't implement `{}` function yet", function.name());
  3117. return nullptr;
  3118. }
  3119. Optional<Parser::Dimension> Parser::parse_dimension(ComponentValue const& component_value)
  3120. {
  3121. if (component_value.is(Token::Type::Dimension)) {
  3122. float numeric_value = component_value.token().dimension_value();
  3123. auto unit_string = component_value.token().dimension_unit();
  3124. if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
  3125. return Length { numeric_value, length_type.release_value() };
  3126. if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
  3127. return Angle { numeric_value, angle_type.release_value() };
  3128. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  3129. return Frequency { numeric_value, frequency_type.release_value() };
  3130. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  3131. return Resolution { numeric_value, resolution_type.release_value() };
  3132. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  3133. return Time { numeric_value, time_type.release_value() };
  3134. }
  3135. if (component_value.is(Token::Type::Percentage))
  3136. return Percentage { static_cast<float>(component_value.token().percentage()) };
  3137. if (component_value.is(Token::Type::Number)) {
  3138. float numeric_value = component_value.token().number_value();
  3139. if (numeric_value == 0)
  3140. return Length::make_px(0);
  3141. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  3142. // https://quirks.spec.whatwg.org/#quirky-length-value
  3143. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  3144. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  3145. // expression, and must not be supported in the supports() static method of the CSS interface."
  3146. return Length::make_px(numeric_value);
  3147. }
  3148. }
  3149. return {};
  3150. }
  3151. Optional<Length> Parser::parse_length(ComponentValue const& component_value)
  3152. {
  3153. auto dimension = parse_dimension(component_value);
  3154. if (!dimension.has_value())
  3155. return {};
  3156. if (dimension->is_length())
  3157. return dimension->length();
  3158. return {};
  3159. }
  3160. Optional<Ratio> Parser::parse_ratio(TokenStream<ComponentValue>& tokens)
  3161. {
  3162. auto transaction = tokens.begin_transaction();
  3163. tokens.skip_whitespace();
  3164. auto read_number_value = [this](ComponentValue const& component_value) -> Optional<float> {
  3165. if (component_value.is(Token::Type::Number)) {
  3166. return component_value.token().number_value();
  3167. } else if (component_value.is_function()) {
  3168. auto maybe_calc = parse_dynamic_value(component_value).release_value_but_fixme_should_propagate_errors();
  3169. if (!maybe_calc || !maybe_calc->is_calculated() || !maybe_calc->as_calculated().resolves_to_number())
  3170. return {};
  3171. if (auto resolved_number = maybe_calc->as_calculated().resolve_number(); resolved_number.has_value() && resolved_number.value() >= 0) {
  3172. return resolved_number.value();
  3173. }
  3174. }
  3175. return {};
  3176. };
  3177. // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
  3178. auto maybe_numerator = read_number_value(tokens.next_token());
  3179. if (!maybe_numerator.has_value() || maybe_numerator.value() < 0)
  3180. return {};
  3181. auto numerator = maybe_numerator.value();
  3182. {
  3183. auto two_value_transaction = tokens.begin_transaction();
  3184. tokens.skip_whitespace();
  3185. auto solidus = tokens.next_token();
  3186. tokens.skip_whitespace();
  3187. auto maybe_denominator = read_number_value(tokens.next_token());
  3188. if (solidus.is_delim('/') && maybe_denominator.has_value() && maybe_denominator.value() >= 0) {
  3189. auto denominator = maybe_denominator.value();
  3190. // Two-value ratio
  3191. two_value_transaction.commit();
  3192. transaction.commit();
  3193. return Ratio { numerator, denominator };
  3194. }
  3195. }
  3196. // Single-value ratio
  3197. transaction.commit();
  3198. return Ratio { numerator };
  3199. }
  3200. // https://www.w3.org/TR/css-syntax-3/#urange-syntax
  3201. Optional<UnicodeRange> Parser::parse_unicode_range(TokenStream<ComponentValue>& tokens)
  3202. {
  3203. auto transaction = tokens.begin_transaction();
  3204. tokens.skip_whitespace();
  3205. // <urange> =
  3206. // u '+' <ident-token> '?'* |
  3207. // u <dimension-token> '?'* |
  3208. // u <number-token> '?'* |
  3209. // u <number-token> <dimension-token> |
  3210. // u <number-token> <number-token> |
  3211. // u '+' '?'+
  3212. // (All with no whitespace in between tokens.)
  3213. // NOTE: Parsing this is different from usual. We take these steps:
  3214. // 1. Match the grammar above against the tokens, concatenating them into a string using their original representation.
  3215. // 2. Then, parse that string according to the spec algorithm.
  3216. // Step 2 is performed by calling the other parse_unicode_range() overload.
  3217. auto is_ending_token = [](ComponentValue const& component_value) {
  3218. return component_value.is(Token::Type::EndOfFile)
  3219. || component_value.is(Token::Type::Comma)
  3220. || component_value.is(Token::Type::Semicolon)
  3221. || component_value.is(Token::Type::Whitespace);
  3222. };
  3223. auto create_unicode_range = [&](StringView text, auto& local_transaction) -> Optional<UnicodeRange> {
  3224. auto maybe_unicode_range = parse_unicode_range(text);
  3225. if (maybe_unicode_range.has_value()) {
  3226. local_transaction.commit();
  3227. transaction.commit();
  3228. }
  3229. return maybe_unicode_range;
  3230. };
  3231. // All options start with 'u'/'U'.
  3232. auto const& u = tokens.next_token();
  3233. if (!(u.is(Token::Type::Ident) && u.token().ident().equals_ignoring_ascii_case("u"sv))) {
  3234. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> does not start with 'u'");
  3235. return {};
  3236. }
  3237. auto const& second_token = tokens.next_token();
  3238. // u '+' <ident-token> '?'* |
  3239. // u '+' '?'+
  3240. if (second_token.is_delim('+')) {
  3241. auto local_transaction = tokens.begin_transaction();
  3242. StringBuilder string_builder;
  3243. string_builder.append(second_token.token().representation());
  3244. auto const& third_token = tokens.next_token();
  3245. if (third_token.is(Token::Type::Ident) || third_token.is_delim('?')) {
  3246. string_builder.append(third_token.token().representation());
  3247. while (tokens.peek_token().is_delim('?'))
  3248. string_builder.append(tokens.next_token().token().representation());
  3249. if (is_ending_token(tokens.peek_token()))
  3250. return create_unicode_range(string_builder.string_view(), local_transaction);
  3251. }
  3252. }
  3253. // u <dimension-token> '?'*
  3254. if (second_token.is(Token::Type::Dimension)) {
  3255. auto local_transaction = tokens.begin_transaction();
  3256. StringBuilder string_builder;
  3257. string_builder.append(second_token.token().representation());
  3258. while (tokens.peek_token().is_delim('?'))
  3259. string_builder.append(tokens.next_token().token().representation());
  3260. if (is_ending_token(tokens.peek_token()))
  3261. return create_unicode_range(string_builder.string_view(), local_transaction);
  3262. }
  3263. // u <number-token> '?'* |
  3264. // u <number-token> <dimension-token> |
  3265. // u <number-token> <number-token>
  3266. if (second_token.is(Token::Type::Number)) {
  3267. auto local_transaction = tokens.begin_transaction();
  3268. StringBuilder string_builder;
  3269. string_builder.append(second_token.token().representation());
  3270. if (is_ending_token(tokens.peek_token()))
  3271. return create_unicode_range(string_builder.string_view(), local_transaction);
  3272. auto const& third_token = tokens.next_token();
  3273. if (third_token.is_delim('?')) {
  3274. string_builder.append(third_token.token().representation());
  3275. while (tokens.peek_token().is_delim('?'))
  3276. string_builder.append(tokens.next_token().token().representation());
  3277. if (is_ending_token(tokens.peek_token()))
  3278. return create_unicode_range(string_builder.string_view(), local_transaction);
  3279. } else if (third_token.is(Token::Type::Dimension)) {
  3280. string_builder.append(third_token.token().representation());
  3281. if (is_ending_token(tokens.peek_token()))
  3282. return create_unicode_range(string_builder.string_view(), local_transaction);
  3283. } else if (third_token.is(Token::Type::Number)) {
  3284. string_builder.append(third_token.token().representation());
  3285. if (is_ending_token(tokens.peek_token()))
  3286. return create_unicode_range(string_builder.string_view(), local_transaction);
  3287. }
  3288. }
  3289. if constexpr (CSS_PARSER_DEBUG) {
  3290. dbgln("CSSParser: Tokens did not match <urange> grammar.");
  3291. tokens.dump_all_tokens();
  3292. }
  3293. return {};
  3294. }
  3295. Optional<UnicodeRange> Parser::parse_unicode_range(StringView text)
  3296. {
  3297. auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<UnicodeRange> {
  3298. // https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point
  3299. constexpr u32 maximum_allowed_code_point = 0x10FFFF;
  3300. // To determine what codepoints the <urange> represents:
  3301. // 1. If end value is greater than the maximum allowed code point,
  3302. // the <urange> is invalid and a syntax error.
  3303. if (end_value > maximum_allowed_code_point) {
  3304. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: end_value ({}) > maximum ({})", end_value, maximum_allowed_code_point);
  3305. return {};
  3306. }
  3307. // 2. If start value is greater than end value, the <urange> is invalid and a syntax error.
  3308. if (start_value > end_value) {
  3309. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: start_value ({}) > end_value ({})", start_value, end_value);
  3310. return {};
  3311. }
  3312. // 3. Otherwise, the <urange> represents a contiguous range of codepoints from start value to end value, inclusive.
  3313. return UnicodeRange { start_value, end_value };
  3314. };
  3315. // 1. Skipping the first u token, concatenate the representations of all the tokens in the production together.
  3316. // Let this be text.
  3317. // NOTE: The concatenation is already done by the caller.
  3318. GenericLexer lexer { text };
  3319. // 2. If the first character of text is U+002B PLUS SIGN, consume it.
  3320. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  3321. if (lexer.next_is('+')) {
  3322. lexer.consume();
  3323. } else {
  3324. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Second character of <urange> was not '+'; got: '{}'", lexer.consume());
  3325. return {};
  3326. }
  3327. // 3. Consume as many hex digits from text as possible.
  3328. // then consume as many U+003F QUESTION MARK (?) code points as possible.
  3329. auto hex_digits = lexer.consume_while(is_ascii_hex_digit);
  3330. auto question_marks = lexer.consume_while([](auto it) { return it == '?'; });
  3331. // If zero code points were consumed, or more than six code points were consumed,
  3332. // this is an invalid <urange>, and this algorithm must exit.
  3333. size_t consumed_code_points = hex_digits.length() + question_marks.length();
  3334. if (consumed_code_points == 0 || consumed_code_points > 6) {
  3335. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value had {} digits/?s, expected between 1 and 6.", consumed_code_points);
  3336. return {};
  3337. }
  3338. StringView start_value_code_points { hex_digits.characters_without_null_termination(), consumed_code_points };
  3339. // If any U+003F QUESTION MARK (?) code points were consumed, then:
  3340. if (question_marks.length() > 0) {
  3341. // 1. If there are any code points left in text, this is an invalid <urange>,
  3342. // and this algorithm must exit.
  3343. if (lexer.tell_remaining() != 0) {
  3344. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  3345. return {};
  3346. }
  3347. // 2. Interpret the consumed code points as a hexadecimal number,
  3348. // with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
  3349. // This is the start value.
  3350. auto start_value_string = start_value_code_points.replace("?"sv, "0"sv, ReplaceMode::All);
  3351. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
  3352. if (!maybe_start_value.has_value()) {
  3353. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
  3354. return {};
  3355. }
  3356. u32 start_value = maybe_start_value.release_value();
  3357. // 3. Interpret the consumed code points as a hexadecimal number again,
  3358. // with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
  3359. // This is the end value.
  3360. auto end_value_string = start_value_code_points.replace("?"sv, "F"sv, ReplaceMode::All);
  3361. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
  3362. if (!maybe_end_value.has_value()) {
  3363. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");
  3364. return {};
  3365. }
  3366. u32 end_value = maybe_end_value.release_value();
  3367. // 4. Exit this algorithm.
  3368. return make_valid_unicode_range(start_value, end_value);
  3369. }
  3370. // Otherwise, interpret the consumed code points as a hexadecimal number. This is the start value.
  3371. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_code_points);
  3372. if (!maybe_start_value.has_value()) {
  3373. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value did not parse as hex number.");
  3374. return {};
  3375. }
  3376. u32 start_value = maybe_start_value.release_value();
  3377. // 4. If there are no code points left in text, The end value is the same as the start value.
  3378. // Exit this algorithm.
  3379. if (lexer.tell_remaining() == 0)
  3380. return make_valid_unicode_range(start_value, start_value);
  3381. // 5. If the next code point in text is U+002D HYPHEN-MINUS (-), consume it.
  3382. if (lexer.next_is('-')) {
  3383. lexer.consume();
  3384. }
  3385. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  3386. else {
  3387. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start and end values not separated by '-'.");
  3388. return {};
  3389. }
  3390. // 6. Consume as many hex digits as possible from text.
  3391. auto end_hex_digits = lexer.consume_while(is_ascii_hex_digit);
  3392. // If zero hex digits were consumed, or more than 6 hex digits were consumed,
  3393. // this is an invalid <urange>, and this algorithm must exit.
  3394. if (end_hex_digits.length() == 0 || end_hex_digits.length() > 6) {
  3395. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value had {} digits, expected between 1 and 6.", end_hex_digits.length());
  3396. return {};
  3397. }
  3398. // If there are any code points left in text, this is an invalid <urange>, and this algorithm must exit.
  3399. if (lexer.tell_remaining() != 0) {
  3400. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  3401. return {};
  3402. }
  3403. // 7. Interpret the consumed code points as a hexadecimal number. This is the end value.
  3404. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_hex_digits);
  3405. if (!maybe_end_value.has_value()) {
  3406. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value did not parse as hex number.");
  3407. return {};
  3408. }
  3409. u32 end_value = maybe_end_value.release_value();
  3410. return make_valid_unicode_range(start_value, end_value);
  3411. }
  3412. ErrorOr<RefPtr<StyleValue>> Parser::parse_dimension_value(ComponentValue const& component_value)
  3413. {
  3414. // Numbers with no units can be lengths, in two situations:
  3415. // 1) We're in quirks mode, and it's an integer.
  3416. // 2) It's a 0.
  3417. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  3418. 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)))
  3419. return nullptr;
  3420. auto dimension = parse_dimension(component_value);
  3421. if (!dimension.has_value())
  3422. return nullptr;
  3423. if (dimension->is_angle())
  3424. return AngleStyleValue::create(dimension->angle());
  3425. if (dimension->is_frequency())
  3426. return FrequencyStyleValue::create(dimension->frequency());
  3427. if (dimension->is_length())
  3428. return LengthStyleValue::create(dimension->length());
  3429. if (dimension->is_percentage())
  3430. return PercentageStyleValue::create(dimension->percentage());
  3431. if (dimension->is_resolution())
  3432. return ResolutionStyleValue::create(dimension->resolution());
  3433. if (dimension->is_time())
  3434. return TimeStyleValue::create(dimension->time());
  3435. VERIFY_NOT_REACHED();
  3436. }
  3437. ErrorOr<RefPtr<StyleValue>> Parser::parse_integer_value(TokenStream<ComponentValue>& tokens)
  3438. {
  3439. auto peek_token = tokens.peek_token();
  3440. if (peek_token.is(Token::Type::Number) && peek_token.token().number().is_integer()) {
  3441. (void)tokens.next_token();
  3442. return IntegerStyleValue::create(peek_token.token().number().integer_value());
  3443. }
  3444. return nullptr;
  3445. }
  3446. ErrorOr<RefPtr<StyleValue>> Parser::parse_number_value(TokenStream<ComponentValue>& tokens)
  3447. {
  3448. auto peek_token = tokens.peek_token();
  3449. if (peek_token.is(Token::Type::Number)) {
  3450. (void)tokens.next_token();
  3451. return NumberStyleValue::create(peek_token.token().number().value());
  3452. }
  3453. return nullptr;
  3454. }
  3455. ErrorOr<RefPtr<StyleValue>> Parser::parse_identifier_value(ComponentValue const& component_value)
  3456. {
  3457. if (component_value.is(Token::Type::Ident)) {
  3458. auto value_id = value_id_from_string(component_value.token().ident());
  3459. if (value_id.has_value())
  3460. return IdentifierStyleValue::create(value_id.value());
  3461. }
  3462. return nullptr;
  3463. }
  3464. Optional<Color> Parser::parse_rgb_or_hsl_color(StringView function_name, Vector<ComponentValue> const& component_values)
  3465. {
  3466. Token params[4];
  3467. bool legacy_syntax = false;
  3468. auto tokens = TokenStream { component_values };
  3469. tokens.skip_whitespace();
  3470. auto const& component1 = tokens.next_token();
  3471. if (!component1.is(Token::Type::Number)
  3472. && !component1.is(Token::Type::Percentage)
  3473. && !component1.is(Token::Type::Dimension))
  3474. return {};
  3475. params[0] = component1.token();
  3476. tokens.skip_whitespace();
  3477. if (tokens.peek_token().is(Token::Type::Comma)) {
  3478. legacy_syntax = true;
  3479. tokens.next_token();
  3480. }
  3481. tokens.skip_whitespace();
  3482. auto const& component2 = tokens.next_token();
  3483. if (!component2.is(Token::Type::Number) && !component2.is(Token::Type::Percentage))
  3484. return {};
  3485. params[1] = component2.token();
  3486. tokens.skip_whitespace();
  3487. if (legacy_syntax && !tokens.next_token().is(Token::Type::Comma))
  3488. return {};
  3489. tokens.skip_whitespace();
  3490. auto const& component3 = tokens.next_token();
  3491. if (!component3.is(Token::Type::Number) && !component3.is(Token::Type::Percentage))
  3492. return {};
  3493. params[2] = component3.token();
  3494. tokens.skip_whitespace();
  3495. auto const& alpha_separator = tokens.peek_token();
  3496. bool has_comma = alpha_separator.is(Token::Type::Comma);
  3497. bool has_slash = alpha_separator.is_delim('/');
  3498. if (legacy_syntax ? has_comma : has_slash) {
  3499. tokens.next_token();
  3500. tokens.skip_whitespace();
  3501. auto const& component4 = tokens.next_token();
  3502. if (!component4.is(Token::Type::Number) && !component4.is(Token::Type::Percentage))
  3503. return {};
  3504. params[3] = component4.token();
  3505. }
  3506. tokens.skip_whitespace();
  3507. if (tokens.has_next_token())
  3508. return {};
  3509. if (function_name.equals_ignoring_ascii_case("rgb"sv)
  3510. || function_name.equals_ignoring_ascii_case("rgba"sv)) {
  3511. // https://www.w3.org/TR/css-color-4/#rgb-functions
  3512. u8 a_val = 255;
  3513. if (params[3].is(Token::Type::Number))
  3514. a_val = clamp(lroundf(params[3].number_value() * 255.0f), 0, 255);
  3515. else if (params[3].is(Token::Type::Percentage))
  3516. a_val = clamp(lroundf(params[3].percentage() * 2.55f), 0, 255);
  3517. if (params[0].is(Token::Type::Number)
  3518. && params[1].is(Token::Type::Number)
  3519. && params[2].is(Token::Type::Number)) {
  3520. u8 r_val = clamp(llroundf(params[0].number_value()), 0, 255);
  3521. u8 g_val = clamp(llroundf(params[1].number_value()), 0, 255);
  3522. u8 b_val = clamp(llroundf(params[2].number_value()), 0, 255);
  3523. return Color(r_val, g_val, b_val, a_val);
  3524. }
  3525. if (params[0].is(Token::Type::Percentage)
  3526. && params[1].is(Token::Type::Percentage)
  3527. && params[2].is(Token::Type::Percentage)) {
  3528. u8 r_val = lroundf(clamp(params[0].percentage() * 2.55f, 0, 255));
  3529. u8 g_val = lroundf(clamp(params[1].percentage() * 2.55f, 0, 255));
  3530. u8 b_val = lroundf(clamp(params[2].percentage() * 2.55f, 0, 255));
  3531. return Color(r_val, g_val, b_val, a_val);
  3532. }
  3533. } else if (function_name.equals_ignoring_ascii_case("hsl"sv)
  3534. || function_name.equals_ignoring_ascii_case("hsla"sv)) {
  3535. // https://www.w3.org/TR/css-color-4/#the-hsl-notation
  3536. float a_val = 1.0f;
  3537. if (params[3].is(Token::Type::Number))
  3538. a_val = params[3].number_value();
  3539. else if (params[3].is(Token::Type::Percentage))
  3540. a_val = params[3].percentage() / 100.0f;
  3541. if (params[0].is(Token::Type::Dimension)
  3542. && params[1].is(Token::Type::Percentage)
  3543. && params[2].is(Token::Type::Percentage)) {
  3544. float numeric_value = params[0].dimension_value();
  3545. auto unit_string = params[0].dimension_unit();
  3546. auto angle_type = Angle::unit_from_name(unit_string);
  3547. if (!angle_type.has_value())
  3548. return {};
  3549. auto angle = Angle { numeric_value, angle_type.release_value() };
  3550. float h_val = fmodf(angle.to_degrees(), 360.0f);
  3551. float s_val = params[1].percentage() / 100.0f;
  3552. float l_val = params[2].percentage() / 100.0f;
  3553. return Color::from_hsla(h_val, s_val, l_val, a_val);
  3554. }
  3555. if (params[0].is(Token::Type::Number)
  3556. && params[1].is(Token::Type::Percentage)
  3557. && params[2].is(Token::Type::Percentage)) {
  3558. float h_val = fmodf(params[0].number_value(), 360.0f);
  3559. float s_val = params[1].percentage() / 100.0f;
  3560. float l_val = params[2].percentage() / 100.0f;
  3561. return Color::from_hsla(h_val, s_val, l_val, a_val);
  3562. }
  3563. }
  3564. return {};
  3565. }
  3566. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  3567. ErrorOr<RefPtr<StyleValue>> Parser::parse_rect_value(ComponentValue const& component_value)
  3568. {
  3569. if (!component_value.is_function())
  3570. return nullptr;
  3571. auto const& function = component_value.function();
  3572. if (!function.name().equals_ignoring_ascii_case("rect"sv))
  3573. return nullptr;
  3574. Vector<Length, 4> params;
  3575. auto tokens = TokenStream { function.values() };
  3576. enum class CommaRequirement {
  3577. Unknown,
  3578. RequiresCommas,
  3579. RequiresNoCommas
  3580. };
  3581. enum class Side {
  3582. Top = 0,
  3583. Right = 1,
  3584. Bottom = 2,
  3585. Left = 3
  3586. };
  3587. auto comma_requirement = CommaRequirement::Unknown;
  3588. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  3589. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  3590. // <left> specify offsets from the left border edge of the box.
  3591. for (size_t side = 0; side < 4; side++) {
  3592. tokens.skip_whitespace();
  3593. // <top>, <right>, <bottom>, and <left> may either have a <length> value or 'auto'.
  3594. // Negative lengths are permitted.
  3595. auto current_token = tokens.next_token().token();
  3596. if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto"sv)) {
  3597. params.append(Length::make_auto());
  3598. } else {
  3599. auto maybe_length = parse_length(current_token);
  3600. if (!maybe_length.has_value())
  3601. return nullptr;
  3602. params.append(maybe_length.value());
  3603. }
  3604. tokens.skip_whitespace();
  3605. // The last side, should be no more tokens following it.
  3606. if (static_cast<Side>(side) == Side::Left) {
  3607. if (tokens.has_next_token())
  3608. return nullptr;
  3609. break;
  3610. }
  3611. bool next_is_comma = tokens.peek_token().is(Token::Type::Comma);
  3612. // Authors should separate offset values with commas. User agents must support separation
  3613. // with commas, but may also support separation without commas (but not a combination),
  3614. // because a previous revision of this specification was ambiguous in this respect.
  3615. if (comma_requirement == CommaRequirement::Unknown)
  3616. comma_requirement = next_is_comma ? CommaRequirement::RequiresCommas : CommaRequirement::RequiresNoCommas;
  3617. if (comma_requirement == CommaRequirement::RequiresCommas) {
  3618. if (next_is_comma)
  3619. tokens.next_token();
  3620. else
  3621. return nullptr;
  3622. } else if (comma_requirement == CommaRequirement::RequiresNoCommas) {
  3623. if (next_is_comma)
  3624. return nullptr;
  3625. } else {
  3626. VERIFY_NOT_REACHED();
  3627. }
  3628. }
  3629. return RectStyleValue::create(EdgeRect { params[0], params[1], params[2], params[3] });
  3630. }
  3631. Optional<Color> Parser::parse_color(ComponentValue const& component_value)
  3632. {
  3633. // https://www.w3.org/TR/css-color-4/
  3634. if (component_value.is(Token::Type::Ident)) {
  3635. auto ident = component_value.token().ident();
  3636. auto color = Color::from_string(ident);
  3637. if (color.has_value())
  3638. return color;
  3639. } else if (component_value.is(Token::Type::Hash)) {
  3640. auto color = Color::from_string(DeprecatedString::formatted("#{}", component_value.token().hash_value()));
  3641. if (color.has_value())
  3642. return color;
  3643. return {};
  3644. } else if (component_value.is_function()) {
  3645. auto const& function = component_value.function();
  3646. auto const& values = function.values();
  3647. return parse_rgb_or_hsl_color(function.name(), values);
  3648. }
  3649. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  3650. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  3651. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  3652. // aborting on the first step that returns a value:
  3653. // 1. Let cv be the component value.
  3654. auto const& cv = component_value;
  3655. DeprecatedString serialization;
  3656. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  3657. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  3658. // 1. If cv’s type flag is not "integer", return an error.
  3659. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  3660. if (!cv.token().number().is_integer())
  3661. return {};
  3662. // 2. If cv’s value is less than zero, return an error.
  3663. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  3664. if (value < 0)
  3665. return {};
  3666. // 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.
  3667. StringBuilder serialization_builder;
  3668. serialization_builder.appendff("{}", value);
  3669. // 4. If cv is a <dimension-token>, append the unit to serialization.
  3670. if (cv.is(Token::Type::Dimension))
  3671. serialization_builder.append(cv.token().dimension_unit());
  3672. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  3673. serialization = serialization_builder.to_deprecated_string();
  3674. if (serialization_builder.length() < 6) {
  3675. StringBuilder builder;
  3676. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  3677. builder.append('0');
  3678. builder.append(serialization_builder.string_view());
  3679. serialization = builder.to_deprecated_string();
  3680. }
  3681. }
  3682. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  3683. else {
  3684. if (!cv.is(Token::Type::Ident))
  3685. return {};
  3686. serialization = cv.token().ident();
  3687. }
  3688. // 4. If serialization does not consist of three or six characters, return an error.
  3689. if (serialization.length() != 3 && serialization.length() != 6)
  3690. return {};
  3691. // 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.
  3692. for (auto c : serialization) {
  3693. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  3694. return {};
  3695. }
  3696. // 6. Return the concatenation of "#" (U+0023) and serialization.
  3697. DeprecatedString concatenation = DeprecatedString::formatted("#{}", serialization);
  3698. return Color::from_string(concatenation);
  3699. }
  3700. return {};
  3701. }
  3702. ErrorOr<RefPtr<StyleValue>> Parser::parse_color_value(ComponentValue const& component_value)
  3703. {
  3704. auto color = parse_color(component_value);
  3705. if (color.has_value())
  3706. return ColorStyleValue::create(color.value());
  3707. if (component_value.is(Token::Type::Ident)) {
  3708. if (auto ident = value_id_from_string(component_value.token().ident()); ident.has_value()) {
  3709. switch (ident.value()) {
  3710. case ValueID::Currentcolor:
  3711. case ValueID::LibwebLink:
  3712. case ValueID::LibwebPaletteActiveLink:
  3713. case ValueID::LibwebPaletteActiveWindowBorder1:
  3714. case ValueID::LibwebPaletteActiveWindowBorder2:
  3715. case ValueID::LibwebPaletteActiveWindowTitle:
  3716. case ValueID::LibwebPaletteBase:
  3717. case ValueID::LibwebPaletteBaseText:
  3718. case ValueID::LibwebPaletteButton:
  3719. case ValueID::LibwebPaletteButtonText:
  3720. case ValueID::LibwebPaletteDesktopBackground:
  3721. case ValueID::LibwebPaletteFocusOutline:
  3722. case ValueID::LibwebPaletteHighlightWindowBorder1:
  3723. case ValueID::LibwebPaletteHighlightWindowBorder2:
  3724. case ValueID::LibwebPaletteHighlightWindowTitle:
  3725. case ValueID::LibwebPaletteHoverHighlight:
  3726. case ValueID::LibwebPaletteInactiveSelection:
  3727. case ValueID::LibwebPaletteInactiveSelectionText:
  3728. case ValueID::LibwebPaletteInactiveWindowBorder1:
  3729. case ValueID::LibwebPaletteInactiveWindowBorder2:
  3730. case ValueID::LibwebPaletteInactiveWindowTitle:
  3731. case ValueID::LibwebPaletteLink:
  3732. case ValueID::LibwebPaletteMenuBase:
  3733. case ValueID::LibwebPaletteMenuBaseText:
  3734. case ValueID::LibwebPaletteMenuSelection:
  3735. case ValueID::LibwebPaletteMenuSelectionText:
  3736. case ValueID::LibwebPaletteMenuStripe:
  3737. case ValueID::LibwebPaletteMovingWindowBorder1:
  3738. case ValueID::LibwebPaletteMovingWindowBorder2:
  3739. case ValueID::LibwebPaletteMovingWindowTitle:
  3740. case ValueID::LibwebPaletteRubberBandBorder:
  3741. case ValueID::LibwebPaletteRubberBandFill:
  3742. case ValueID::LibwebPaletteRuler:
  3743. case ValueID::LibwebPaletteRulerActiveText:
  3744. case ValueID::LibwebPaletteRulerBorder:
  3745. case ValueID::LibwebPaletteRulerInactiveText:
  3746. case ValueID::LibwebPaletteSelection:
  3747. case ValueID::LibwebPaletteSelectionText:
  3748. case ValueID::LibwebPaletteSyntaxComment:
  3749. case ValueID::LibwebPaletteSyntaxControlKeyword:
  3750. case ValueID::LibwebPaletteSyntaxIdentifier:
  3751. case ValueID::LibwebPaletteSyntaxKeyword:
  3752. case ValueID::LibwebPaletteSyntaxNumber:
  3753. case ValueID::LibwebPaletteSyntaxOperator:
  3754. case ValueID::LibwebPaletteSyntaxPreprocessorStatement:
  3755. case ValueID::LibwebPaletteSyntaxPreprocessorValue:
  3756. case ValueID::LibwebPaletteSyntaxPunctuation:
  3757. case ValueID::LibwebPaletteSyntaxString:
  3758. case ValueID::LibwebPaletteSyntaxType:
  3759. case ValueID::LibwebPaletteTextCursor:
  3760. case ValueID::LibwebPaletteThreedHighlight:
  3761. case ValueID::LibwebPaletteThreedShadow1:
  3762. case ValueID::LibwebPaletteThreedShadow2:
  3763. case ValueID::LibwebPaletteVisitedLink:
  3764. case ValueID::LibwebPaletteWindow:
  3765. case ValueID::LibwebPaletteWindowText:
  3766. return IdentifierStyleValue::create(ident.value());
  3767. default:
  3768. break;
  3769. }
  3770. }
  3771. }
  3772. return nullptr;
  3773. }
  3774. ErrorOr<RefPtr<StyleValue>> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  3775. {
  3776. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  3777. return RatioStyleValue::create(ratio.release_value());
  3778. return nullptr;
  3779. }
  3780. ErrorOr<RefPtr<StyleValue>> Parser::parse_string_value(ComponentValue const& component_value)
  3781. {
  3782. if (component_value.is(Token::Type::String))
  3783. return StringStyleValue::create(TRY(String::from_utf8(component_value.token().string())));
  3784. return nullptr;
  3785. }
  3786. ErrorOr<RefPtr<StyleValue>> Parser::parse_image_value(ComponentValue const& component_value)
  3787. {
  3788. auto url = parse_url_function(component_value, AllowedDataUrlType::Image);
  3789. if (url.has_value())
  3790. return ImageStyleValue::create(url.value());
  3791. auto linear_gradient = TRY(parse_linear_gradient_function(component_value));
  3792. if (linear_gradient)
  3793. return linear_gradient;
  3794. auto conic_gradient = TRY(parse_conic_gradient_function(component_value));
  3795. if (conic_gradient)
  3796. return conic_gradient;
  3797. return parse_radial_gradient_function(component_value);
  3798. }
  3799. template<typename ParseFunction>
  3800. ErrorOr<RefPtr<StyleValue>> Parser::parse_comma_separated_value_list(Vector<ComponentValue> const& component_values, ParseFunction parse_one_value)
  3801. {
  3802. auto tokens = TokenStream { component_values };
  3803. auto first = TRY(parse_one_value(tokens));
  3804. if (!first || !tokens.has_next_token())
  3805. return first;
  3806. StyleValueVector values;
  3807. values.append(first.release_nonnull());
  3808. while (tokens.has_next_token()) {
  3809. if (!tokens.next_token().is(Token::Type::Comma))
  3810. return nullptr;
  3811. if (auto maybe_value = TRY(parse_one_value(tokens))) {
  3812. values.append(maybe_value.release_nonnull());
  3813. continue;
  3814. }
  3815. return nullptr;
  3816. }
  3817. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  3818. }
  3819. ErrorOr<RefPtr<StyleValue>> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, Vector<ComponentValue> const& component_values)
  3820. {
  3821. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> ErrorOr<RefPtr<StyleValue>> {
  3822. if (auto value = TRY(parse_css_value_for_property(property_id, tokens)))
  3823. return value;
  3824. tokens.reconsume_current_input_token();
  3825. return nullptr;
  3826. });
  3827. }
  3828. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  3829. {
  3830. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  3831. }
  3832. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  3833. ErrorOr<RefPtr<StyleValue>> Parser::parse_aspect_ratio_value(Vector<ComponentValue> const& component_values)
  3834. {
  3835. // `auto || <ratio>`
  3836. RefPtr<StyleValue> auto_value;
  3837. RefPtr<StyleValue> ratio_value;
  3838. auto tokens = TokenStream { component_values };
  3839. while (tokens.has_next_token()) {
  3840. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::AspectRatio, tokens));
  3841. if (!maybe_value)
  3842. return nullptr;
  3843. if (maybe_value->is_ratio()) {
  3844. if (ratio_value)
  3845. return nullptr;
  3846. ratio_value = maybe_value.release_nonnull();
  3847. continue;
  3848. }
  3849. if (maybe_value->is_identifier() && maybe_value->as_identifier().id() == ValueID::Auto) {
  3850. if (auto_value)
  3851. return nullptr;
  3852. auto_value = maybe_value.release_nonnull();
  3853. continue;
  3854. }
  3855. return nullptr;
  3856. }
  3857. if (auto_value && ratio_value) {
  3858. return TRY(StyleValueList::create(
  3859. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  3860. StyleValueList::Separator::Space));
  3861. }
  3862. if (ratio_value)
  3863. return ratio_value.release_nonnull();
  3864. if (auto_value)
  3865. return auto_value.release_nonnull();
  3866. return nullptr;
  3867. }
  3868. ErrorOr<RefPtr<StyleValue>> Parser::parse_background_value(Vector<ComponentValue> const& component_values)
  3869. {
  3870. StyleValueVector background_images;
  3871. StyleValueVector background_positions;
  3872. StyleValueVector background_sizes;
  3873. StyleValueVector background_repeats;
  3874. StyleValueVector background_attachments;
  3875. StyleValueVector background_clips;
  3876. StyleValueVector background_origins;
  3877. RefPtr<StyleValue> background_color;
  3878. auto initial_background_image = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundImage));
  3879. auto initial_background_position = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundPosition));
  3880. auto initial_background_size = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundSize));
  3881. auto initial_background_repeat = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat));
  3882. auto initial_background_attachment = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment));
  3883. auto initial_background_clip = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundClip));
  3884. auto initial_background_origin = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin));
  3885. auto initial_background_color = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundColor));
  3886. // Per-layer values
  3887. RefPtr<StyleValue> background_image;
  3888. RefPtr<StyleValue> background_position;
  3889. RefPtr<StyleValue> background_size;
  3890. RefPtr<StyleValue> background_repeat;
  3891. RefPtr<StyleValue> background_attachment;
  3892. RefPtr<StyleValue> background_clip;
  3893. RefPtr<StyleValue> background_origin;
  3894. bool has_multiple_layers = false;
  3895. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  3896. Vector<PropertyID> remaining_layer_properties {
  3897. PropertyID::BackgroundAttachment,
  3898. PropertyID::BackgroundClip,
  3899. PropertyID::BackgroundColor,
  3900. PropertyID::BackgroundImage,
  3901. PropertyID::BackgroundOrigin,
  3902. PropertyID::BackgroundPosition,
  3903. PropertyID::BackgroundRepeat,
  3904. };
  3905. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  3906. if (allow_background_color) {
  3907. if (background_color)
  3908. return true;
  3909. } else {
  3910. if (background_color)
  3911. return false;
  3912. }
  3913. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  3914. };
  3915. auto complete_background_layer = [&]() -> ErrorOr<void> {
  3916. TRY(background_images.try_append(background_image ? background_image.release_nonnull() : initial_background_image));
  3917. TRY(background_positions.try_append(background_position ? background_position.release_nonnull() : initial_background_position));
  3918. TRY(background_sizes.try_append(background_size ? background_size.release_nonnull() : initial_background_size));
  3919. TRY(background_repeats.try_append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat));
  3920. TRY(background_attachments.try_append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment));
  3921. if (!background_origin && !background_clip) {
  3922. background_origin = initial_background_origin;
  3923. background_clip = initial_background_clip;
  3924. } else if (!background_clip) {
  3925. background_clip = background_origin;
  3926. }
  3927. TRY(background_origins.try_append(background_origin.release_nonnull()));
  3928. TRY(background_clips.try_append(background_clip.release_nonnull()));
  3929. background_image = nullptr;
  3930. background_position = nullptr;
  3931. background_size = nullptr;
  3932. background_repeat = nullptr;
  3933. background_attachment = nullptr;
  3934. background_clip = nullptr;
  3935. background_origin = nullptr;
  3936. remaining_layer_properties.clear_with_capacity();
  3937. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  3938. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  3939. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  3940. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  3941. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  3942. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  3943. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  3944. return {};
  3945. };
  3946. auto tokens = TokenStream { component_values };
  3947. while (tokens.has_next_token()) {
  3948. if (tokens.peek_token().is(Token::Type::Comma)) {
  3949. has_multiple_layers = true;
  3950. if (!background_layer_is_valid(false))
  3951. return nullptr;
  3952. TRY(complete_background_layer());
  3953. (void)tokens.next_token();
  3954. continue;
  3955. }
  3956. auto value_and_property = TRY(parse_css_value_for_properties(remaining_layer_properties, tokens));
  3957. if (!value_and_property.style_value)
  3958. return nullptr;
  3959. auto& value = value_and_property.style_value;
  3960. remove_property(remaining_layer_properties, value_and_property.property);
  3961. switch (value_and_property.property) {
  3962. case PropertyID::BackgroundAttachment:
  3963. VERIFY(!background_attachment);
  3964. background_attachment = value.release_nonnull();
  3965. continue;
  3966. case PropertyID::BackgroundColor:
  3967. VERIFY(!background_color);
  3968. background_color = value.release_nonnull();
  3969. continue;
  3970. case PropertyID::BackgroundImage:
  3971. VERIFY(!background_image);
  3972. background_image = value.release_nonnull();
  3973. continue;
  3974. case PropertyID::BackgroundClip:
  3975. case PropertyID::BackgroundOrigin: {
  3976. // background-origin and background-clip accept the same values. From the spec:
  3977. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  3978. // If two values are present, then the first sets background-origin and the second background-clip."
  3979. // - https://www.w3.org/TR/css-backgrounds-3/#background
  3980. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  3981. // If we only get one, we copy the value before creating the BackgroundStyleValue.
  3982. if (!background_origin) {
  3983. background_origin = value.release_nonnull();
  3984. } else if (!background_clip) {
  3985. background_clip = value.release_nonnull();
  3986. } else {
  3987. VERIFY_NOT_REACHED();
  3988. }
  3989. continue;
  3990. }
  3991. case PropertyID::BackgroundPosition: {
  3992. VERIFY(!background_position);
  3993. tokens.reconsume_current_input_token();
  3994. if (auto maybe_background_position = TRY(parse_single_background_position_value(tokens))) {
  3995. background_position = maybe_background_position.release_nonnull();
  3996. // Attempt to parse `/ <background-size>`
  3997. auto transaction = tokens.begin_transaction();
  3998. auto& maybe_slash = tokens.next_token();
  3999. if (maybe_slash.is_delim('/')) {
  4000. if (auto maybe_background_size = TRY(parse_single_background_size_value(tokens))) {
  4001. transaction.commit();
  4002. background_size = maybe_background_size.release_nonnull();
  4003. continue;
  4004. }
  4005. return nullptr;
  4006. }
  4007. continue;
  4008. }
  4009. return nullptr;
  4010. }
  4011. case PropertyID::BackgroundRepeat: {
  4012. VERIFY(!background_repeat);
  4013. tokens.reconsume_current_input_token();
  4014. if (auto maybe_repeat = TRY(parse_single_background_repeat_value(tokens))) {
  4015. background_repeat = maybe_repeat.release_nonnull();
  4016. continue;
  4017. }
  4018. return nullptr;
  4019. }
  4020. default:
  4021. VERIFY_NOT_REACHED();
  4022. }
  4023. return nullptr;
  4024. }
  4025. if (!background_layer_is_valid(true))
  4026. return nullptr;
  4027. // We only need to create StyleValueLists if there are multiple layers.
  4028. // Otherwise, we can pass the single StyleValues directly.
  4029. if (has_multiple_layers) {
  4030. TRY(complete_background_layer());
  4031. if (!background_color)
  4032. background_color = initial_background_color;
  4033. return BackgroundStyleValue::create(
  4034. background_color.release_nonnull(),
  4035. TRY(StyleValueList::create(move(background_images), StyleValueList::Separator::Comma)),
  4036. TRY(StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma)),
  4037. TRY(StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma)),
  4038. TRY(StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma)),
  4039. TRY(StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma)),
  4040. TRY(StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma)),
  4041. TRY(StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma)));
  4042. }
  4043. if (!background_color)
  4044. background_color = initial_background_color;
  4045. if (!background_image)
  4046. background_image = initial_background_image;
  4047. if (!background_position)
  4048. background_position = initial_background_position;
  4049. if (!background_size)
  4050. background_size = initial_background_size;
  4051. if (!background_repeat)
  4052. background_repeat = initial_background_repeat;
  4053. if (!background_attachment)
  4054. background_attachment = initial_background_attachment;
  4055. if (!background_origin && !background_clip) {
  4056. background_origin = initial_background_origin;
  4057. background_clip = initial_background_clip;
  4058. } else if (!background_clip) {
  4059. background_clip = background_origin;
  4060. }
  4061. return BackgroundStyleValue::create(
  4062. background_color.release_nonnull(),
  4063. background_image.release_nonnull(),
  4064. background_position.release_nonnull(),
  4065. background_size.release_nonnull(),
  4066. background_repeat.release_nonnull(),
  4067. background_attachment.release_nonnull(),
  4068. background_origin.release_nonnull(),
  4069. background_clip.release_nonnull());
  4070. }
  4071. static Optional<PositionEdge> identifier_to_edge(ValueID identifier)
  4072. {
  4073. switch (identifier) {
  4074. case ValueID::Top:
  4075. return PositionEdge::Top;
  4076. case ValueID::Bottom:
  4077. return PositionEdge::Bottom;
  4078. case ValueID::Left:
  4079. return PositionEdge::Left;
  4080. case ValueID::Right:
  4081. return PositionEdge::Right;
  4082. default:
  4083. return {};
  4084. }
  4085. };
  4086. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  4087. {
  4088. if (value->is_percentage())
  4089. return LengthPercentage { value->as_percentage().percentage() };
  4090. if (value->is_length())
  4091. return LengthPercentage { value->as_length().length() };
  4092. if (value->is_calculated())
  4093. return LengthPercentage { value->as_calculated() };
  4094. return {};
  4095. };
  4096. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_position_value(TokenStream<ComponentValue>& tokens)
  4097. {
  4098. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  4099. // "Note: The background-position property also accepts a three-value syntax.
  4100. // This has been disallowed generically because it creates parsing ambiguities
  4101. // when combined with other length or percentage components in a property value."
  4102. // - https://www.w3.org/TR/css-values-4/#typedef-position
  4103. // So, we'll need a separate function to parse <position> later.
  4104. auto transaction = tokens.begin_transaction();
  4105. auto is_horizontal = [](ValueID identifier) -> bool {
  4106. switch (identifier) {
  4107. case ValueID::Left:
  4108. case ValueID::Right:
  4109. return true;
  4110. default:
  4111. return false;
  4112. }
  4113. };
  4114. auto is_vertical = [](ValueID identifier) -> bool {
  4115. switch (identifier) {
  4116. case ValueID::Top:
  4117. case ValueID::Bottom:
  4118. return true;
  4119. default:
  4120. return false;
  4121. }
  4122. };
  4123. struct EdgeOffset {
  4124. PositionEdge edge;
  4125. LengthPercentage offset;
  4126. bool edge_provided;
  4127. bool offset_provided;
  4128. };
  4129. Optional<EdgeOffset> horizontal;
  4130. Optional<EdgeOffset> vertical;
  4131. bool found_center = false;
  4132. auto const center_offset = Percentage { 50 };
  4133. auto const zero_offset = Length::make_px(0);
  4134. while (tokens.has_next_token()) {
  4135. // Check if we're done
  4136. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  4137. if (seen_items == 2)
  4138. break;
  4139. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::BackgroundPosition, tokens));
  4140. if (!maybe_value)
  4141. break;
  4142. auto value = maybe_value.release_nonnull();
  4143. if (auto offset = style_value_to_length_percentage(value); offset.has_value()) {
  4144. if (!horizontal.has_value()) {
  4145. horizontal = EdgeOffset { PositionEdge::Left, *offset, false, true };
  4146. } else if (!vertical.has_value()) {
  4147. vertical = EdgeOffset { PositionEdge::Top, *offset, false, true };
  4148. } else {
  4149. return nullptr;
  4150. }
  4151. continue;
  4152. }
  4153. auto try_parse_offset = [&](bool& offset_provided) -> ErrorOr<LengthPercentage> {
  4154. auto transaction = tokens.begin_transaction();
  4155. if (tokens.has_next_token()) {
  4156. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::BackgroundPosition, tokens));
  4157. if (!maybe_value)
  4158. return zero_offset;
  4159. auto offset = style_value_to_length_percentage(maybe_value.release_nonnull());
  4160. if (offset.has_value()) {
  4161. offset_provided = true;
  4162. transaction.commit();
  4163. return *offset;
  4164. }
  4165. }
  4166. return zero_offset;
  4167. };
  4168. if (value->is_identifier()) {
  4169. auto identifier = value->to_identifier();
  4170. if (is_horizontal(identifier)) {
  4171. bool offset_provided = false;
  4172. auto offset = TRY(try_parse_offset(offset_provided));
  4173. horizontal = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  4174. } else if (is_vertical(identifier)) {
  4175. bool offset_provided = false;
  4176. auto offset = TRY(try_parse_offset(offset_provided));
  4177. vertical = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  4178. } else if (identifier == ValueID::Center) {
  4179. found_center = true;
  4180. } else {
  4181. return nullptr;
  4182. }
  4183. continue;
  4184. }
  4185. tokens.reconsume_current_input_token();
  4186. break;
  4187. }
  4188. if (found_center) {
  4189. if (horizontal.has_value() && vertical.has_value())
  4190. return nullptr;
  4191. if (!horizontal.has_value())
  4192. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  4193. if (!vertical.has_value())
  4194. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  4195. }
  4196. if (!horizontal.has_value() && !vertical.has_value())
  4197. return nullptr;
  4198. // Unpack `<edge> <length>`:
  4199. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  4200. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  4201. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  4202. // Split into `x y`
  4203. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  4204. horizontal->offset = zero_offset;
  4205. horizontal->offset_provided = false;
  4206. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  4207. // `y`, reconsume
  4208. vertical->offset = zero_offset;
  4209. vertical->offset_provided = false;
  4210. tokens.reconsume_current_input_token();
  4211. }
  4212. // If only one value is specified, the second value is assumed to be center.
  4213. if (!horizontal.has_value())
  4214. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  4215. if (!vertical.has_value())
  4216. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  4217. transaction.commit();
  4218. return PositionStyleValue::create(
  4219. TRY(EdgeStyleValue::create(horizontal->edge, horizontal->offset)),
  4220. TRY(EdgeStyleValue::create(vertical->edge, vertical->offset)));
  4221. }
  4222. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  4223. {
  4224. PositionEdge relative_edge {};
  4225. if (property == PropertyID::BackgroundPositionX) {
  4226. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  4227. relative_edge = PositionEdge::Left;
  4228. } else if (property == PropertyID::BackgroundPositionY) {
  4229. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  4230. relative_edge = PositionEdge::Top;
  4231. } else {
  4232. VERIFY_NOT_REACHED();
  4233. }
  4234. auto transaction = tokens.begin_transaction();
  4235. if (!tokens.has_next_token())
  4236. return nullptr;
  4237. auto value = TRY(parse_css_value_for_property(property, tokens));
  4238. if (!value)
  4239. return nullptr;
  4240. if (value->is_identifier()) {
  4241. auto identifier = value->to_identifier();
  4242. if (identifier == ValueID::Center) {
  4243. transaction.commit();
  4244. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  4245. }
  4246. if (auto edge = identifier_to_edge(identifier); edge.has_value()) {
  4247. relative_edge = *edge;
  4248. } else {
  4249. return nullptr;
  4250. }
  4251. if (tokens.has_next_token()) {
  4252. value = TRY(parse_css_value_for_property(property, tokens));
  4253. if (!value) {
  4254. transaction.commit();
  4255. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  4256. }
  4257. }
  4258. }
  4259. auto offset = style_value_to_length_percentage(value);
  4260. if (offset.has_value()) {
  4261. transaction.commit();
  4262. return EdgeStyleValue::create(relative_edge, *offset);
  4263. }
  4264. return nullptr;
  4265. }
  4266. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  4267. {
  4268. auto transaction = tokens.begin_transaction();
  4269. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  4270. auto value_id = value.to_identifier();
  4271. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  4272. };
  4273. auto as_repeat = [](ValueID identifier) -> Optional<Repeat> {
  4274. switch (identifier) {
  4275. case ValueID::NoRepeat:
  4276. return Repeat::NoRepeat;
  4277. case ValueID::Repeat:
  4278. return Repeat::Repeat;
  4279. case ValueID::Round:
  4280. return Repeat::Round;
  4281. case ValueID::Space:
  4282. return Repeat::Space;
  4283. default:
  4284. return {};
  4285. }
  4286. };
  4287. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens));
  4288. if (!maybe_x_value)
  4289. return nullptr;
  4290. auto x_value = maybe_x_value.release_nonnull();
  4291. if (is_directional_repeat(*x_value)) {
  4292. auto value_id = x_value->to_identifier();
  4293. transaction.commit();
  4294. return BackgroundRepeatStyleValue::create(
  4295. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  4296. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  4297. }
  4298. auto x_repeat = as_repeat(x_value->to_identifier());
  4299. if (!x_repeat.has_value())
  4300. return nullptr;
  4301. // See if we have a second value for Y
  4302. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens));
  4303. if (!maybe_y_value) {
  4304. // We don't have a second value, so use x for both
  4305. transaction.commit();
  4306. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  4307. }
  4308. auto y_value = maybe_y_value.release_nonnull();
  4309. if (is_directional_repeat(*y_value))
  4310. return nullptr;
  4311. auto y_repeat = as_repeat(y_value->to_identifier());
  4312. if (!y_repeat.has_value())
  4313. return nullptr;
  4314. transaction.commit();
  4315. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  4316. }
  4317. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  4318. {
  4319. auto transaction = tokens.begin_transaction();
  4320. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  4321. if (style_value.has_auto())
  4322. return LengthPercentage { Length::make_auto() };
  4323. if (style_value.is_percentage())
  4324. return LengthPercentage { style_value.as_percentage().percentage() };
  4325. if (style_value.is_length())
  4326. return LengthPercentage { style_value.as_length().length() };
  4327. return {};
  4328. };
  4329. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::BackgroundSize, tokens));
  4330. if (!maybe_x_value)
  4331. return nullptr;
  4332. auto x_value = maybe_x_value.release_nonnull();
  4333. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain) {
  4334. transaction.commit();
  4335. return x_value;
  4336. }
  4337. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::BackgroundSize, tokens));
  4338. if (!maybe_y_value) {
  4339. auto y_value = LengthPercentage { Length::make_auto() };
  4340. auto x_size = get_length_percentage(*x_value);
  4341. if (!x_size.has_value())
  4342. return nullptr;
  4343. transaction.commit();
  4344. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  4345. }
  4346. auto y_value = maybe_y_value.release_nonnull();
  4347. auto x_size = get_length_percentage(*x_value);
  4348. auto y_size = get_length_percentage(*y_value);
  4349. if (!x_size.has_value() || !y_size.has_value())
  4350. return nullptr;
  4351. transaction.commit();
  4352. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  4353. }
  4354. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_value(Vector<ComponentValue> const& component_values)
  4355. {
  4356. if (component_values.size() > 3)
  4357. return nullptr;
  4358. RefPtr<StyleValue> border_width;
  4359. RefPtr<StyleValue> border_color;
  4360. RefPtr<StyleValue> border_style;
  4361. auto remaining_longhands = Vector { PropertyID::BorderWidth, PropertyID::BorderColor, PropertyID::BorderStyle };
  4362. auto tokens = TokenStream { component_values };
  4363. while (tokens.has_next_token()) {
  4364. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  4365. if (!property_and_value.style_value)
  4366. return nullptr;
  4367. auto& value = property_and_value.style_value;
  4368. remove_property(remaining_longhands, property_and_value.property);
  4369. switch (property_and_value.property) {
  4370. case PropertyID::BorderWidth: {
  4371. VERIFY(!border_width);
  4372. border_width = value.release_nonnull();
  4373. continue;
  4374. }
  4375. case PropertyID::BorderColor: {
  4376. VERIFY(!border_color);
  4377. border_color = value.release_nonnull();
  4378. continue;
  4379. }
  4380. case PropertyID::BorderStyle: {
  4381. VERIFY(!border_style);
  4382. border_style = value.release_nonnull();
  4383. continue;
  4384. }
  4385. default:
  4386. VERIFY_NOT_REACHED();
  4387. }
  4388. }
  4389. if (!border_width)
  4390. border_width = TRY(property_initial_value(m_context.realm(), PropertyID::BorderWidth));
  4391. if (!border_style)
  4392. border_style = TRY(property_initial_value(m_context.realm(), PropertyID::BorderStyle));
  4393. if (!border_color)
  4394. border_color = TRY(property_initial_value(m_context.realm(), PropertyID::BorderColor));
  4395. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  4396. }
  4397. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_radius_value(Vector<ComponentValue> const& component_values)
  4398. {
  4399. if (component_values.size() == 2) {
  4400. auto horizontal = parse_dimension(component_values[0]);
  4401. auto vertical = parse_dimension(component_values[1]);
  4402. if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage())
  4403. return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());
  4404. return nullptr;
  4405. }
  4406. if (component_values.size() == 1) {
  4407. auto radius = parse_dimension(component_values[0]);
  4408. if (radius.has_value() && radius->is_length_percentage())
  4409. return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
  4410. return nullptr;
  4411. }
  4412. return nullptr;
  4413. }
  4414. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_radius_shorthand_value(Vector<ComponentValue> const& component_values)
  4415. {
  4416. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  4417. auto top_right = [&](Vector<LengthPercentage>& radii) {
  4418. switch (radii.size()) {
  4419. case 4:
  4420. case 3:
  4421. case 2:
  4422. return radii[1];
  4423. case 1:
  4424. return radii[0];
  4425. default:
  4426. VERIFY_NOT_REACHED();
  4427. }
  4428. };
  4429. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  4430. switch (radii.size()) {
  4431. case 4:
  4432. case 3:
  4433. return radii[2];
  4434. case 2:
  4435. case 1:
  4436. return radii[0];
  4437. default:
  4438. VERIFY_NOT_REACHED();
  4439. }
  4440. };
  4441. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  4442. switch (radii.size()) {
  4443. case 4:
  4444. return radii[3];
  4445. case 3:
  4446. case 2:
  4447. return radii[1];
  4448. case 1:
  4449. return radii[0];
  4450. default:
  4451. VERIFY_NOT_REACHED();
  4452. }
  4453. };
  4454. Vector<LengthPercentage> horizontal_radii;
  4455. Vector<LengthPercentage> vertical_radii;
  4456. bool reading_vertical = false;
  4457. for (auto const& value : component_values) {
  4458. if (value.is_delim('/')) {
  4459. if (reading_vertical || horizontal_radii.is_empty())
  4460. return nullptr;
  4461. reading_vertical = true;
  4462. continue;
  4463. }
  4464. auto maybe_dimension = parse_dimension(value);
  4465. if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
  4466. return nullptr;
  4467. if (reading_vertical) {
  4468. vertical_radii.append(maybe_dimension->length_percentage());
  4469. } else {
  4470. horizontal_radii.append(maybe_dimension->length_percentage());
  4471. }
  4472. }
  4473. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  4474. || horizontal_radii.is_empty()
  4475. || (reading_vertical && vertical_radii.is_empty()))
  4476. return nullptr;
  4477. auto top_left_radius = TRY(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  4478. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  4479. auto top_right_radius = TRY(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  4480. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  4481. auto bottom_right_radius = TRY(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  4482. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  4483. auto bottom_left_radius = TRY(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  4484. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  4485. return BorderRadiusShorthandStyleValue::create(move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius));
  4486. }
  4487. ErrorOr<RefPtr<StyleValue>> Parser::parse_shadow_value(Vector<ComponentValue> const& component_values, AllowInsetKeyword allow_inset_keyword)
  4488. {
  4489. // "none"
  4490. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  4491. auto ident = TRY(parse_identifier_value(component_values.first()));
  4492. if (ident && ident->to_identifier() == ValueID::None)
  4493. return ident;
  4494. }
  4495. return parse_comma_separated_value_list(component_values, [this, allow_inset_keyword](auto& tokens) {
  4496. return parse_single_shadow_value(tokens, allow_inset_keyword);
  4497. });
  4498. }
  4499. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  4500. {
  4501. auto transaction = tokens.begin_transaction();
  4502. Optional<Color> color;
  4503. Optional<Length> offset_x;
  4504. Optional<Length> offset_y;
  4505. Optional<Length> blur_radius;
  4506. Optional<Length> spread_distance;
  4507. Optional<ShadowPlacement> placement;
  4508. while (tokens.has_next_token()) {
  4509. auto const& token = tokens.peek_token();
  4510. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  4511. if (color.has_value())
  4512. return nullptr;
  4513. color = maybe_color.release_value();
  4514. tokens.next_token();
  4515. continue;
  4516. }
  4517. if (auto maybe_offset_x = parse_length(token); maybe_offset_x.has_value()) {
  4518. // horizontal offset
  4519. if (offset_x.has_value())
  4520. return nullptr;
  4521. offset_x = maybe_offset_x.release_value();
  4522. tokens.next_token();
  4523. // vertical offset
  4524. if (!tokens.has_next_token())
  4525. return nullptr;
  4526. auto maybe_offset_y = parse_length(tokens.peek_token());
  4527. if (!maybe_offset_y.has_value())
  4528. return nullptr;
  4529. offset_y = maybe_offset_y.release_value();
  4530. tokens.next_token();
  4531. // blur radius (optional)
  4532. if (!tokens.has_next_token())
  4533. break;
  4534. auto maybe_blur_radius = parse_length(tokens.peek_token());
  4535. if (!maybe_blur_radius.has_value())
  4536. continue;
  4537. blur_radius = maybe_blur_radius.release_value();
  4538. tokens.next_token();
  4539. // spread distance (optional)
  4540. if (!tokens.has_next_token())
  4541. break;
  4542. auto maybe_spread_distance = parse_length(tokens.peek_token());
  4543. if (!maybe_spread_distance.has_value())
  4544. continue;
  4545. spread_distance = maybe_spread_distance.release_value();
  4546. tokens.next_token();
  4547. continue;
  4548. }
  4549. if (allow_inset_keyword == AllowInsetKeyword::Yes
  4550. && token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("inset"sv)) {
  4551. if (placement.has_value())
  4552. return nullptr;
  4553. placement = ShadowPlacement::Inner;
  4554. tokens.next_token();
  4555. continue;
  4556. }
  4557. if (token.is(Token::Type::Comma))
  4558. break;
  4559. return nullptr;
  4560. }
  4561. // FIXME: If color is absent, default to `currentColor`
  4562. if (!color.has_value())
  4563. color = Color::NamedColor::Black;
  4564. // x/y offsets are required
  4565. if (!offset_x.has_value() || !offset_y.has_value())
  4566. return nullptr;
  4567. // Other lengths default to 0
  4568. if (!blur_radius.has_value())
  4569. blur_radius = Length::make_px(0);
  4570. if (!spread_distance.has_value())
  4571. spread_distance = Length::make_px(0);
  4572. // Placement is outer by default
  4573. if (!placement.has_value())
  4574. placement = ShadowPlacement::Outer;
  4575. transaction.commit();
  4576. 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());
  4577. }
  4578. ErrorOr<RefPtr<StyleValue>> Parser::parse_content_value(Vector<ComponentValue> const& component_values)
  4579. {
  4580. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  4581. auto is_single_value_identifier = [](ValueID identifier) -> bool {
  4582. switch (identifier) {
  4583. case ValueID::None:
  4584. case ValueID::Normal:
  4585. return true;
  4586. default:
  4587. return false;
  4588. }
  4589. };
  4590. if (component_values.size() == 1) {
  4591. if (auto identifier = TRY(parse_identifier_value(component_values.first()))) {
  4592. if (is_single_value_identifier(identifier->to_identifier()))
  4593. return identifier;
  4594. }
  4595. }
  4596. StyleValueVector content_values;
  4597. StyleValueVector alt_text_values;
  4598. bool in_alt_text = false;
  4599. auto tokens = TokenStream { component_values };
  4600. while (tokens.has_next_token()) {
  4601. auto& next = tokens.peek_token();
  4602. if (next.is_delim('/')) {
  4603. if (in_alt_text || content_values.is_empty())
  4604. return nullptr;
  4605. in_alt_text = true;
  4606. (void)tokens.next_token();
  4607. continue;
  4608. }
  4609. if (auto style_value = TRY(parse_css_value_for_property(PropertyID::Content, tokens))) {
  4610. if (is_single_value_identifier(style_value->to_identifier()))
  4611. return nullptr;
  4612. if (in_alt_text) {
  4613. TRY(alt_text_values.try_append(style_value.release_nonnull()));
  4614. } else {
  4615. TRY(content_values.try_append(style_value.release_nonnull()));
  4616. }
  4617. continue;
  4618. }
  4619. return nullptr;
  4620. }
  4621. if (content_values.is_empty())
  4622. return nullptr;
  4623. if (in_alt_text && alt_text_values.is_empty())
  4624. return nullptr;
  4625. RefPtr<StyleValueList> alt_text;
  4626. if (!alt_text_values.is_empty())
  4627. alt_text = TRY(StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space));
  4628. return ContentStyleValue::create(TRY(StyleValueList::create(move(content_values), StyleValueList::Separator::Space)), move(alt_text));
  4629. }
  4630. // https://www.w3.org/TR/css-display-3/#the-display-properties
  4631. ErrorOr<RefPtr<StyleValue>> Parser::parse_display_value(Vector<ComponentValue> const& component_values)
  4632. {
  4633. auto parse_inside = [](ValueID identifier) -> Optional<Display::Inside> {
  4634. switch (identifier) {
  4635. case ValueID::Flow:
  4636. return Display::Inside::Flow;
  4637. case ValueID::FlowRoot:
  4638. return Display::Inside::FlowRoot;
  4639. case ValueID::Table:
  4640. return Display::Inside::Table;
  4641. case ValueID::Flex:
  4642. return Display::Inside::Flex;
  4643. case ValueID::Grid:
  4644. return Display::Inside::Grid;
  4645. case ValueID::Ruby:
  4646. return Display::Inside::Ruby;
  4647. default:
  4648. return {};
  4649. }
  4650. };
  4651. auto parse_outside = [](ValueID identifier) -> Optional<Display::Outside> {
  4652. switch (identifier) {
  4653. case ValueID::Block:
  4654. return Display::Outside::Block;
  4655. case ValueID::Inline:
  4656. return Display::Outside::Inline;
  4657. case ValueID::RunIn:
  4658. return Display::Outside::RunIn;
  4659. default:
  4660. return {};
  4661. }
  4662. };
  4663. auto parse_single_component_display = [&](Vector<ComponentValue> const& component_values) -> ErrorOr<Optional<Display>> {
  4664. if (auto identifier = TRY(parse_identifier_value(component_values.first()))) {
  4665. switch (identifier->to_identifier()) {
  4666. // display-outside
  4667. case ValueID::Block:
  4668. return Display::from_short(Display::Short::Block);
  4669. case ValueID::Inline:
  4670. return Display::from_short(Display::Short::Inline);
  4671. case ValueID::RunIn:
  4672. return Display::from_short(Display::Short::RunIn);
  4673. // display-inside
  4674. case ValueID::Flow:
  4675. return Display::from_short(Display::Short::Flow);
  4676. case ValueID::FlowRoot:
  4677. return Display::from_short(Display::Short::FlowRoot);
  4678. case ValueID::Table:
  4679. return Display::from_short(Display::Short::Table);
  4680. case ValueID::Flex:
  4681. return Display::from_short(Display::Short::Flex);
  4682. case ValueID::Grid:
  4683. return Display::from_short(Display::Short::Grid);
  4684. case ValueID::Ruby:
  4685. return Display::from_short(Display::Short::Ruby);
  4686. // display-listitem
  4687. case ValueID::ListItem:
  4688. return Display::from_short(Display::Short::ListItem);
  4689. // display-internal
  4690. case ValueID::TableRowGroup:
  4691. return Display { Display::Internal::TableRowGroup };
  4692. case ValueID::TableHeaderGroup:
  4693. return Display { Display::Internal::TableHeaderGroup };
  4694. case ValueID::TableFooterGroup:
  4695. return Display { Display::Internal::TableFooterGroup };
  4696. case ValueID::TableRow:
  4697. return Display { Display::Internal::TableRow };
  4698. case ValueID::TableCell:
  4699. return Display { Display::Internal::TableCell };
  4700. case ValueID::TableColumnGroup:
  4701. return Display { Display::Internal::TableColumnGroup };
  4702. case ValueID::TableColumn:
  4703. return Display { Display::Internal::TableColumn };
  4704. case ValueID::TableCaption:
  4705. return Display { Display::Internal::TableCaption };
  4706. case ValueID::RubyBase:
  4707. return Display { Display::Internal::RubyBase };
  4708. case ValueID::RubyText:
  4709. return Display { Display::Internal::RubyText };
  4710. case ValueID::RubyBaseContainer:
  4711. return Display { Display::Internal::RubyBaseContainer };
  4712. case ValueID::RubyTextContainer:
  4713. return Display { Display::Internal::RubyTextContainer };
  4714. // display-box
  4715. case ValueID::Contents:
  4716. // FIXME this should be Display::Short::Contents but contents is currently not implemented
  4717. return Display::from_short(Display::Short::Flow);
  4718. case ValueID::None:
  4719. return Display::from_short(Display::Short::None);
  4720. // display-legacy
  4721. case ValueID::InlineBlock:
  4722. return Display::from_short(Display::Short::InlineBlock);
  4723. case ValueID::InlineTable:
  4724. return Display::from_short(Display::Short::InlineTable);
  4725. case ValueID::InlineFlex:
  4726. return Display::from_short(Display::Short::InlineFlex);
  4727. case ValueID::InlineGrid:
  4728. return Display::from_short(Display::Short::InlineGrid);
  4729. default:
  4730. return OptionalNone {};
  4731. }
  4732. }
  4733. return OptionalNone {};
  4734. };
  4735. auto parse_multi_component_display = [&](Vector<ComponentValue> const& component_values) -> ErrorOr<Optional<Display>> {
  4736. auto list_item = Display::ListItem::No;
  4737. Display::Inside inside = Display::Inside::Flow;
  4738. Display::Outside outside = Display::Outside::Block;
  4739. for (size_t i = 0; i < component_values.size(); ++i) {
  4740. if (auto value = TRY(parse_identifier_value(component_values[i]))) {
  4741. auto identifier = value->to_identifier();
  4742. if (ValueID::ListItem == identifier) {
  4743. list_item = Display::ListItem::Yes;
  4744. continue;
  4745. }
  4746. auto inside_value = parse_inside(identifier);
  4747. if (inside_value.has_value()) {
  4748. inside = inside_value.value();
  4749. continue;
  4750. }
  4751. auto outside_value = parse_outside(identifier);
  4752. if (outside_value.has_value()) {
  4753. outside = outside_value.value();
  4754. }
  4755. }
  4756. }
  4757. // The spec does not allow any other inside values to be combined with list-item
  4758. // <display-outside>? && [ flow | flow-root ]? && list-item
  4759. if (list_item == Display::ListItem::Yes && inside != Display::Inside::Flow && inside != Display::Inside::FlowRoot)
  4760. return OptionalNone {};
  4761. return Display { outside, inside, list_item };
  4762. };
  4763. Optional<Display> display;
  4764. if (component_values.size() == 1)
  4765. display = TRY(parse_single_component_display(component_values));
  4766. else
  4767. display = TRY(parse_multi_component_display(component_values));
  4768. if (display.has_value())
  4769. return DisplayStyleValue::create(display.value());
  4770. return nullptr;
  4771. }
  4772. ErrorOr<RefPtr<StyleValue>> Parser::parse_filter_value_list_value(Vector<ComponentValue> const& component_values)
  4773. {
  4774. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  4775. auto ident = TRY(parse_identifier_value(component_values.first()));
  4776. if (ident && ident->to_identifier() == ValueID::None)
  4777. return ident;
  4778. }
  4779. TokenStream tokens { component_values };
  4780. // FIXME: <url>s are ignored for now
  4781. // <filter-value-list> = [ <filter-function> | <url> ]+
  4782. enum class FilterToken {
  4783. // Color filters:
  4784. Brightness,
  4785. Contrast,
  4786. Grayscale,
  4787. Invert,
  4788. Opacity,
  4789. Saturate,
  4790. Sepia,
  4791. // Special filters:
  4792. Blur,
  4793. DropShadow,
  4794. HueRotate
  4795. };
  4796. auto filter_token_to_operation = [&](auto filter) {
  4797. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  4798. return static_cast<Filter::Color::Operation>(filter);
  4799. };
  4800. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  4801. if (token.is(Token::Type::Percentage))
  4802. return NumberPercentage(Percentage(token.token().percentage()));
  4803. if (token.is(Token::Type::Number))
  4804. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  4805. return {};
  4806. };
  4807. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  4808. if (name.equals_ignoring_ascii_case("blur"sv))
  4809. return FilterToken::Blur;
  4810. if (name.equals_ignoring_ascii_case("brightness"sv))
  4811. return FilterToken::Brightness;
  4812. if (name.equals_ignoring_ascii_case("contrast"sv))
  4813. return FilterToken::Contrast;
  4814. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  4815. return FilterToken::DropShadow;
  4816. if (name.equals_ignoring_ascii_case("grayscale"sv))
  4817. return FilterToken::Grayscale;
  4818. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  4819. return FilterToken::HueRotate;
  4820. if (name.equals_ignoring_ascii_case("invert"sv))
  4821. return FilterToken::Invert;
  4822. if (name.equals_ignoring_ascii_case("opacity"sv))
  4823. return FilterToken::Opacity;
  4824. if (name.equals_ignoring_ascii_case("saturate"sv))
  4825. return FilterToken::Saturate;
  4826. if (name.equals_ignoring_ascii_case("sepia"sv))
  4827. return FilterToken::Sepia;
  4828. return {};
  4829. };
  4830. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  4831. TokenStream tokens { function_values };
  4832. tokens.skip_whitespace();
  4833. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  4834. tokens.skip_whitespace();
  4835. if (tokens.has_next_token())
  4836. return {};
  4837. return filter;
  4838. };
  4839. if (filter_token == FilterToken::Blur) {
  4840. // blur( <length>? )
  4841. if (!tokens.has_next_token())
  4842. return Filter::Blur {};
  4843. auto blur_radius = parse_length(tokens.next_token());
  4844. if (!blur_radius.has_value())
  4845. return {};
  4846. return if_no_more_tokens_return(Filter::Blur { *blur_radius });
  4847. } else if (filter_token == FilterToken::DropShadow) {
  4848. if (!tokens.has_next_token())
  4849. return {};
  4850. auto next_token = [&]() -> auto&
  4851. {
  4852. auto& token = tokens.next_token();
  4853. tokens.skip_whitespace();
  4854. return token;
  4855. };
  4856. // drop-shadow( [ <color>? && <length>{2,3} ] )
  4857. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  4858. auto& first_param = next_token();
  4859. Optional<Length> maybe_radius = {};
  4860. auto maybe_color = parse_color(first_param);
  4861. auto x_offset = parse_length(maybe_color.has_value() ? next_token() : first_param);
  4862. if (!x_offset.has_value() || !tokens.has_next_token()) {
  4863. return {};
  4864. }
  4865. auto y_offset = parse_length(next_token());
  4866. if (!y_offset.has_value()) {
  4867. return {};
  4868. }
  4869. if (tokens.has_next_token()) {
  4870. auto& token = next_token();
  4871. maybe_radius = parse_length(token);
  4872. if (!maybe_color.has_value() && (!maybe_radius.has_value() || tokens.has_next_token())) {
  4873. maybe_color = parse_color(!maybe_radius.has_value() ? token : next_token());
  4874. if (!maybe_color.has_value()) {
  4875. return {};
  4876. }
  4877. } else if (!maybe_radius.has_value()) {
  4878. return {};
  4879. }
  4880. }
  4881. return if_no_more_tokens_return(Filter::DropShadow { *x_offset, *y_offset, maybe_radius, maybe_color });
  4882. } else if (filter_token == FilterToken::HueRotate) {
  4883. // hue-rotate( [ <angle> | <zero> ]? )
  4884. if (!tokens.has_next_token())
  4885. return Filter::HueRotate {};
  4886. auto& token = tokens.next_token();
  4887. if (token.is(Token::Type::Number)) {
  4888. // hue-rotate(0)
  4889. auto number = token.token().number();
  4890. if (number.is_integer() && number.integer_value() == 0)
  4891. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  4892. return {};
  4893. }
  4894. if (!token.is(Token::Type::Dimension))
  4895. return {};
  4896. float angle_value = token.token().dimension_value();
  4897. auto angle_unit_name = token.token().dimension_unit();
  4898. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  4899. if (!angle_unit.has_value())
  4900. return {};
  4901. Angle angle { angle_value, angle_unit.release_value() };
  4902. return if_no_more_tokens_return(Filter::HueRotate { angle });
  4903. } else {
  4904. // Simple filters:
  4905. // brightness( <number-percentage>? )
  4906. // contrast( <number-percentage>? )
  4907. // grayscale( <number-percentage>? )
  4908. // invert( <number-percentage>? )
  4909. // opacity( <number-percentage>? )
  4910. // sepia( <number-percentage>? )
  4911. // saturate( <number-percentage>? )
  4912. if (!tokens.has_next_token())
  4913. return Filter::Color { filter_token_to_operation(filter_token) };
  4914. auto amount = parse_number_percentage(tokens.next_token());
  4915. if (!amount.has_value())
  4916. return {};
  4917. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  4918. }
  4919. };
  4920. Vector<FilterFunction> filter_value_list {};
  4921. while (tokens.has_next_token()) {
  4922. tokens.skip_whitespace();
  4923. if (!tokens.has_next_token())
  4924. break;
  4925. auto& token = tokens.next_token();
  4926. if (!token.is_function())
  4927. return nullptr;
  4928. auto filter_token = parse_filter_function_name(token.function().name());
  4929. if (!filter_token.has_value())
  4930. return nullptr;
  4931. auto filter_function = parse_filter_function(*filter_token, token.function().values());
  4932. if (!filter_function.has_value())
  4933. return nullptr;
  4934. filter_value_list.append(*filter_function);
  4935. }
  4936. if (filter_value_list.is_empty())
  4937. return nullptr;
  4938. return FilterValueListStyleValue::create(move(filter_value_list));
  4939. }
  4940. ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_value(Vector<ComponentValue> const& component_values)
  4941. {
  4942. auto tokens = TokenStream { component_values };
  4943. if (component_values.size() == 1) {
  4944. // One-value syntax: <flex-grow> | <flex-basis> | none
  4945. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  4946. auto property_and_value = TRY(parse_css_value_for_properties(properties, tokens));
  4947. if (!property_and_value.style_value)
  4948. return nullptr;
  4949. auto& value = property_and_value.style_value;
  4950. switch (property_and_value.property) {
  4951. case PropertyID::FlexGrow: {
  4952. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4953. // https://github.com/w3c/csswg-drafts/issues/5742
  4954. auto flex_basis = TRY(PercentageStyleValue::create(Percentage(0)));
  4955. auto one = TRY(NumberStyleValue::create(1));
  4956. return FlexStyleValue::create(*value, one, flex_basis);
  4957. }
  4958. case PropertyID::FlexBasis: {
  4959. auto one = TRY(NumberStyleValue::create(1));
  4960. return FlexStyleValue::create(one, one, *value);
  4961. }
  4962. case PropertyID::Flex: {
  4963. if (value->is_identifier() && value->to_identifier() == ValueID::None) {
  4964. auto zero = TRY(NumberStyleValue::create(0));
  4965. return FlexStyleValue::create(zero, zero, TRY(IdentifierStyleValue::create(ValueID::Auto)));
  4966. }
  4967. break;
  4968. }
  4969. default:
  4970. VERIFY_NOT_REACHED();
  4971. }
  4972. return nullptr;
  4973. }
  4974. RefPtr<StyleValue> flex_grow;
  4975. RefPtr<StyleValue> flex_shrink;
  4976. RefPtr<StyleValue> flex_basis;
  4977. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  4978. // if FlexGrow (along with optional FlexShrink) have already been specified.
  4979. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  4980. while (tokens.has_next_token()) {
  4981. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  4982. if (!property_and_value.style_value)
  4983. return nullptr;
  4984. auto& value = property_and_value.style_value;
  4985. remove_property(remaining_longhands, property_and_value.property);
  4986. switch (property_and_value.property) {
  4987. case PropertyID::FlexGrow: {
  4988. VERIFY(!flex_grow);
  4989. flex_grow = value.release_nonnull();
  4990. // Flex-shrink may optionally follow directly after.
  4991. auto maybe_flex_shrink = TRY(parse_css_value_for_property(PropertyID::FlexShrink, tokens));
  4992. if (maybe_flex_shrink)
  4993. flex_shrink = maybe_flex_shrink.release_nonnull();
  4994. continue;
  4995. }
  4996. case PropertyID::FlexBasis: {
  4997. VERIFY(!flex_basis);
  4998. flex_basis = value.release_nonnull();
  4999. continue;
  5000. }
  5001. default:
  5002. VERIFY_NOT_REACHED();
  5003. }
  5004. }
  5005. if (!flex_grow)
  5006. flex_grow = TRY(property_initial_value(m_context.realm(), PropertyID::FlexGrow));
  5007. if (!flex_shrink)
  5008. flex_shrink = TRY(property_initial_value(m_context.realm(), PropertyID::FlexShrink));
  5009. if (!flex_basis) {
  5010. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  5011. // https://github.com/w3c/csswg-drafts/issues/5742
  5012. flex_basis = TRY(PercentageStyleValue::create(Percentage(0)));
  5013. }
  5014. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  5015. }
  5016. ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_flow_value(Vector<ComponentValue> const& component_values)
  5017. {
  5018. if (component_values.size() > 2)
  5019. return nullptr;
  5020. RefPtr<StyleValue> flex_direction;
  5021. RefPtr<StyleValue> flex_wrap;
  5022. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  5023. auto tokens = TokenStream { component_values };
  5024. while (tokens.has_next_token()) {
  5025. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5026. if (!property_and_value.style_value)
  5027. return nullptr;
  5028. auto& value = property_and_value.style_value;
  5029. remove_property(remaining_longhands, property_and_value.property);
  5030. switch (property_and_value.property) {
  5031. case PropertyID::FlexDirection:
  5032. VERIFY(!flex_direction);
  5033. flex_direction = value.release_nonnull();
  5034. continue;
  5035. case PropertyID::FlexWrap:
  5036. VERIFY(!flex_wrap);
  5037. flex_wrap = value.release_nonnull();
  5038. continue;
  5039. default:
  5040. VERIFY_NOT_REACHED();
  5041. }
  5042. }
  5043. if (!flex_direction)
  5044. flex_direction = TRY(property_initial_value(m_context.realm(), PropertyID::FlexDirection));
  5045. if (!flex_wrap)
  5046. flex_wrap = TRY(property_initial_value(m_context.realm(), PropertyID::FlexWrap));
  5047. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  5048. }
  5049. static bool is_generic_font_family(ValueID identifier)
  5050. {
  5051. switch (identifier) {
  5052. case ValueID::Cursive:
  5053. case ValueID::Fantasy:
  5054. case ValueID::Monospace:
  5055. case ValueID::Serif:
  5056. case ValueID::SansSerif:
  5057. case ValueID::UiMonospace:
  5058. case ValueID::UiRounded:
  5059. case ValueID::UiSerif:
  5060. case ValueID::UiSansSerif:
  5061. return true;
  5062. default:
  5063. return false;
  5064. }
  5065. }
  5066. ErrorOr<RefPtr<StyleValue>> Parser::parse_font_value(Vector<ComponentValue> const& component_values)
  5067. {
  5068. RefPtr<StyleValue> font_stretch;
  5069. RefPtr<StyleValue> font_style;
  5070. RefPtr<StyleValue> font_weight;
  5071. RefPtr<StyleValue> font_size;
  5072. RefPtr<StyleValue> line_height;
  5073. RefPtr<StyleValue> font_families;
  5074. RefPtr<StyleValue> font_variant;
  5075. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  5076. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  5077. // So, we have to handle that separately.
  5078. int normal_count = 0;
  5079. auto tokens = TokenStream { component_values };
  5080. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStretch, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight };
  5081. while (tokens.has_next_token()) {
  5082. auto& peek_token = tokens.peek_token();
  5083. if (peek_token.is(Token::Type::Ident) && value_id_from_string(peek_token.token().ident()) == ValueID::Normal) {
  5084. normal_count++;
  5085. (void)tokens.next_token();
  5086. continue;
  5087. }
  5088. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5089. if (!property_and_value.style_value)
  5090. return nullptr;
  5091. auto& value = property_and_value.style_value;
  5092. remove_property(remaining_longhands, property_and_value.property);
  5093. switch (property_and_value.property) {
  5094. case PropertyID::FontSize: {
  5095. VERIFY(!font_size);
  5096. font_size = value.release_nonnull();
  5097. // Consume `/ line-height` if present
  5098. if (tokens.peek_token().is_delim('/')) {
  5099. (void)tokens.next_token();
  5100. auto maybe_line_height = TRY(parse_css_value_for_property(PropertyID::LineHeight, tokens));
  5101. if (!maybe_line_height)
  5102. return nullptr;
  5103. line_height = maybe_line_height.release_nonnull();
  5104. }
  5105. // Consume font-families
  5106. auto maybe_font_families = TRY(parse_font_family_value(tokens));
  5107. // font-family comes last, so we must not have any tokens left over.
  5108. if (!maybe_font_families || tokens.has_next_token())
  5109. return nullptr;
  5110. font_families = maybe_font_families.release_nonnull();
  5111. continue;
  5112. }
  5113. case PropertyID::FontStretch: {
  5114. VERIFY(!font_stretch);
  5115. font_stretch = value.release_nonnull();
  5116. continue;
  5117. }
  5118. case PropertyID::FontStyle: {
  5119. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  5120. VERIFY(!font_style);
  5121. font_style = value.release_nonnull();
  5122. continue;
  5123. }
  5124. case PropertyID::FontVariant: {
  5125. VERIFY(!font_variant);
  5126. font_variant = value.release_nonnull();
  5127. continue;
  5128. }
  5129. case PropertyID::FontWeight: {
  5130. VERIFY(!font_weight);
  5131. font_weight = value.release_nonnull();
  5132. continue;
  5133. }
  5134. default:
  5135. VERIFY_NOT_REACHED();
  5136. }
  5137. return nullptr;
  5138. }
  5139. // Since normal is the default value for all the properties that can have it, we don't have to actually
  5140. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  5141. // We just need to make sure we were not given more normals than will fit.
  5142. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  5143. if (unset_value_count < normal_count)
  5144. return nullptr;
  5145. if (!font_size || !font_families)
  5146. return nullptr;
  5147. if (!font_stretch)
  5148. font_stretch = TRY(property_initial_value(m_context.realm(), PropertyID::FontStretch));
  5149. if (!font_style)
  5150. font_style = TRY(property_initial_value(m_context.realm(), PropertyID::FontStyle));
  5151. if (!font_weight)
  5152. font_weight = TRY(property_initial_value(m_context.realm(), PropertyID::FontWeight));
  5153. if (!line_height)
  5154. line_height = TRY(property_initial_value(m_context.realm(), PropertyID::LineHeight));
  5155. 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());
  5156. }
  5157. ErrorOr<RefPtr<StyleValue>> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  5158. {
  5159. auto next_is_comma_or_eof = [&]() -> bool {
  5160. return !tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma);
  5161. };
  5162. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  5163. // eg, these are equivalent:
  5164. // font-family: my cool font\!, serif;
  5165. // font-family: "my cool font!", serif;
  5166. StyleValueVector font_families;
  5167. Vector<DeprecatedString> current_name_parts;
  5168. while (tokens.has_next_token()) {
  5169. auto const& peek = tokens.peek_token();
  5170. if (peek.is(Token::Type::String)) {
  5171. // `font-family: my cool "font";` is invalid.
  5172. if (!current_name_parts.is_empty())
  5173. return nullptr;
  5174. (void)tokens.next_token(); // String
  5175. if (!next_is_comma_or_eof())
  5176. return nullptr;
  5177. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::from_utf8(peek.token().string()))))));
  5178. (void)tokens.next_token(); // Comma
  5179. continue;
  5180. }
  5181. if (peek.is(Token::Type::Ident)) {
  5182. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  5183. // CSS-wide keywords are not allowed
  5184. if (auto builtin = TRY(parse_builtin_value(peek)))
  5185. return nullptr;
  5186. auto maybe_ident = value_id_from_string(peek.token().ident());
  5187. // Can't have a generic-font-name as a token in an unquoted font name.
  5188. if (maybe_ident.has_value() && is_generic_font_family(maybe_ident.value())) {
  5189. if (!current_name_parts.is_empty())
  5190. return nullptr;
  5191. (void)tokens.next_token(); // Ident
  5192. if (!next_is_comma_or_eof())
  5193. return nullptr;
  5194. TRY(font_families.try_append(TRY(IdentifierStyleValue::create(maybe_ident.value()))));
  5195. (void)tokens.next_token(); // Comma
  5196. continue;
  5197. }
  5198. TRY(current_name_parts.try_append(tokens.next_token().token().ident()));
  5199. continue;
  5200. }
  5201. if (peek.is(Token::Type::Comma)) {
  5202. if (current_name_parts.is_empty())
  5203. return nullptr;
  5204. (void)tokens.next_token(); // Comma
  5205. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::join(' ', current_name_parts))))));
  5206. current_name_parts.clear();
  5207. // Can't have a trailing comma
  5208. if (!tokens.has_next_token())
  5209. return nullptr;
  5210. continue;
  5211. }
  5212. return nullptr;
  5213. }
  5214. if (!current_name_parts.is_empty()) {
  5215. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::join(' ', current_name_parts))))));
  5216. current_name_parts.clear();
  5217. }
  5218. if (font_families.is_empty())
  5219. return nullptr;
  5220. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  5221. }
  5222. CSSRule* Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
  5223. {
  5224. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  5225. Optional<FlyString> font_family;
  5226. Vector<FontFace::Source> src;
  5227. Vector<UnicodeRange> unicode_range;
  5228. Optional<int> weight;
  5229. Optional<int> slope;
  5230. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  5231. if (declaration_or_at_rule.is_at_rule()) {
  5232. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-family; discarding.");
  5233. continue;
  5234. }
  5235. auto const& declaration = declaration_or_at_rule.declaration();
  5236. if (declaration.name().equals_ignoring_ascii_case("font-weight"sv)) {
  5237. TokenStream token_stream { declaration.values() };
  5238. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  5239. weight = value.value()->to_font_weight();
  5240. }
  5241. continue;
  5242. }
  5243. if (declaration.name().equals_ignoring_ascii_case("font-style"sv)) {
  5244. TokenStream token_stream { declaration.values() };
  5245. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  5246. slope = value.value()->to_font_slope();
  5247. }
  5248. continue;
  5249. }
  5250. if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
  5251. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  5252. // Ideally they could share code.
  5253. Vector<DeprecatedString> font_family_parts;
  5254. bool had_syntax_error = false;
  5255. for (size_t i = 0; i < declaration.values().size(); ++i) {
  5256. auto const& part = declaration.values()[i];
  5257. if (part.is(Token::Type::Whitespace))
  5258. continue;
  5259. if (part.is(Token::Type::String)) {
  5260. if (!font_family_parts.is_empty()) {
  5261. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5262. had_syntax_error = true;
  5263. break;
  5264. }
  5265. font_family_parts.append(part.token().string());
  5266. continue;
  5267. }
  5268. if (part.is(Token::Type::Ident)) {
  5269. if (is_builtin(part.token().ident())) {
  5270. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5271. had_syntax_error = true;
  5272. break;
  5273. }
  5274. auto value_id = value_id_from_string(part.token().ident());
  5275. if (value_id.has_value() && is_generic_font_family(value_id.value())) {
  5276. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5277. had_syntax_error = true;
  5278. break;
  5279. }
  5280. font_family_parts.append(part.token().ident());
  5281. continue;
  5282. }
  5283. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5284. had_syntax_error = true;
  5285. break;
  5286. }
  5287. if (had_syntax_error || font_family_parts.is_empty())
  5288. continue;
  5289. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  5290. continue;
  5291. }
  5292. if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
  5293. TokenStream token_stream { declaration.values() };
  5294. Vector<FontFace::Source> supported_sources = parse_font_face_src(token_stream);
  5295. if (!supported_sources.is_empty())
  5296. src = move(supported_sources);
  5297. continue;
  5298. }
  5299. if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
  5300. Vector<UnicodeRange> unicode_ranges;
  5301. bool unicode_range_invalid = false;
  5302. TokenStream all_tokens { declaration.values() };
  5303. auto range_token_lists = parse_a_comma_separated_list_of_component_values(all_tokens);
  5304. for (auto& range_tokens : range_token_lists) {
  5305. TokenStream range_token_stream { range_tokens };
  5306. auto maybe_unicode_range = parse_unicode_range(range_token_stream);
  5307. if (!maybe_unicode_range.has_value()) {
  5308. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face unicode-range format invalid; discarding.");
  5309. unicode_range_invalid = true;
  5310. break;
  5311. }
  5312. unicode_ranges.append(maybe_unicode_range.release_value());
  5313. }
  5314. if (unicode_range_invalid || unicode_ranges.is_empty())
  5315. continue;
  5316. unicode_range = move(unicode_ranges);
  5317. continue;
  5318. }
  5319. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-family; discarding.", declaration.name());
  5320. }
  5321. if (!font_family.has_value()) {
  5322. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  5323. return {};
  5324. }
  5325. if (unicode_range.is_empty()) {
  5326. unicode_range.empend(0x0u, 0x10FFFFu);
  5327. }
  5328. 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();
  5329. }
  5330. Vector<FontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values)
  5331. {
  5332. // FIXME: Get this information from the system somehow?
  5333. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  5334. auto font_format_is_supported = [](StringView name) {
  5335. // The spec requires us to treat opentype and truetype as synonymous.
  5336. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv))
  5337. return true;
  5338. return false;
  5339. };
  5340. Vector<FontFace::Source> supported_sources;
  5341. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  5342. for (auto const& source_token_list : list_of_source_token_lists) {
  5343. TokenStream source_tokens { source_token_list };
  5344. source_tokens.skip_whitespace();
  5345. auto const& first = source_tokens.next_token();
  5346. // <url> [ format(<font-format>)]?
  5347. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  5348. if (auto maybe_url = parse_url_function(first, AllowedDataUrlType::Font); maybe_url.has_value()) {
  5349. auto url = maybe_url.release_value();
  5350. if (!url.is_valid()) {
  5351. continue;
  5352. }
  5353. Optional<FlyString> format;
  5354. source_tokens.skip_whitespace();
  5355. if (!source_tokens.has_next_token()) {
  5356. supported_sources.empend(move(url), format);
  5357. continue;
  5358. }
  5359. auto maybe_function = source_tokens.next_token();
  5360. if (!maybe_function.is_function()) {
  5361. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  5362. return {};
  5363. }
  5364. auto const& function = maybe_function.function();
  5365. if (function.name().equals_ignoring_ascii_case("format"sv)) {
  5366. TokenStream format_tokens { function.values() };
  5367. format_tokens.skip_whitespace();
  5368. auto const& format_name_token = format_tokens.next_token();
  5369. StringView format_name;
  5370. if (format_name_token.is(Token::Type::Ident)) {
  5371. format_name = format_name_token.token().ident();
  5372. } else if (format_name_token.is(Token::Type::String)) {
  5373. format_name = format_name_token.token().string();
  5374. } else {
  5375. 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());
  5376. return {};
  5377. }
  5378. if (!font_format_is_supported(format_name)) {
  5379. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  5380. continue;
  5381. }
  5382. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  5383. } else {
  5384. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
  5385. return {};
  5386. }
  5387. source_tokens.skip_whitespace();
  5388. if (source_tokens.has_next_token()) {
  5389. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
  5390. return {};
  5391. }
  5392. supported_sources.empend(move(url), format);
  5393. continue;
  5394. }
  5395. // FIXME: Implement `local()`.
  5396. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  5397. return {};
  5398. }
  5399. return supported_sources;
  5400. }
  5401. ErrorOr<RefPtr<StyleValue>> Parser::parse_list_style_value(Vector<ComponentValue> const& component_values)
  5402. {
  5403. if (component_values.size() > 3)
  5404. return nullptr;
  5405. RefPtr<StyleValue> list_position;
  5406. RefPtr<StyleValue> list_image;
  5407. RefPtr<StyleValue> list_type;
  5408. int found_nones = 0;
  5409. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  5410. auto tokens = TokenStream { component_values };
  5411. while (tokens.has_next_token()) {
  5412. if (auto peek = tokens.peek_token(); peek.is(Token::Type::Ident) && peek.token().ident().equals_ignoring_ascii_case("none"sv)) {
  5413. (void)tokens.next_token();
  5414. found_nones++;
  5415. continue;
  5416. }
  5417. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5418. if (!property_and_value.style_value)
  5419. return nullptr;
  5420. auto& value = property_and_value.style_value;
  5421. remove_property(remaining_longhands, property_and_value.property);
  5422. switch (property_and_value.property) {
  5423. case PropertyID::ListStylePosition: {
  5424. VERIFY(!list_position);
  5425. list_position = value.release_nonnull();
  5426. continue;
  5427. }
  5428. case PropertyID::ListStyleImage: {
  5429. VERIFY(!list_image);
  5430. list_image = value.release_nonnull();
  5431. continue;
  5432. }
  5433. case PropertyID::ListStyleType: {
  5434. VERIFY(!list_type);
  5435. list_type = value.release_nonnull();
  5436. continue;
  5437. }
  5438. default:
  5439. VERIFY_NOT_REACHED();
  5440. }
  5441. }
  5442. if (found_nones > 2)
  5443. return nullptr;
  5444. if (found_nones == 2) {
  5445. if (list_image || list_type)
  5446. return nullptr;
  5447. auto none = TRY(IdentifierStyleValue::create(ValueID::None));
  5448. list_image = none;
  5449. list_type = none;
  5450. } else if (found_nones == 1) {
  5451. if (list_image && list_type)
  5452. return nullptr;
  5453. auto none = TRY(IdentifierStyleValue::create(ValueID::None));
  5454. if (!list_image)
  5455. list_image = none;
  5456. if (!list_type)
  5457. list_type = none;
  5458. }
  5459. if (!list_position)
  5460. list_position = TRY(property_initial_value(m_context.realm(), PropertyID::ListStylePosition));
  5461. if (!list_image)
  5462. list_image = TRY(property_initial_value(m_context.realm(), PropertyID::ListStyleImage));
  5463. if (!list_type)
  5464. list_type = TRY(property_initial_value(m_context.realm(), PropertyID::ListStyleType));
  5465. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  5466. }
  5467. ErrorOr<RefPtr<StyleValue>> Parser::parse_overflow_value(Vector<ComponentValue> const& component_values)
  5468. {
  5469. auto tokens = TokenStream { component_values };
  5470. if (component_values.size() == 1) {
  5471. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::Overflow, tokens));
  5472. if (!maybe_value)
  5473. return nullptr;
  5474. return OverflowStyleValue::create(*maybe_value, *maybe_value);
  5475. }
  5476. if (component_values.size() == 2) {
  5477. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::OverflowX, tokens));
  5478. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::OverflowY, tokens));
  5479. if (!maybe_x_value || !maybe_y_value)
  5480. return nullptr;
  5481. return OverflowStyleValue::create(maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull());
  5482. }
  5483. return nullptr;
  5484. }
  5485. ErrorOr<RefPtr<StyleValue>> Parser::parse_place_content_value(Vector<ComponentValue> const& component_values)
  5486. {
  5487. if (component_values.size() > 2)
  5488. return nullptr;
  5489. auto tokens = TokenStream { component_values };
  5490. auto maybe_align_content_value = TRY(parse_css_value_for_property(PropertyID::AlignContent, tokens));
  5491. if (!maybe_align_content_value)
  5492. return nullptr;
  5493. if (component_values.size() == 1) {
  5494. if (!property_accepts_identifier(PropertyID::JustifyContent, maybe_align_content_value->to_identifier()))
  5495. return nullptr;
  5496. return PlaceContentStyleValue::create(*maybe_align_content_value, *maybe_align_content_value);
  5497. }
  5498. auto maybe_justify_content_value = TRY(parse_css_value_for_property(PropertyID::JustifyContent, tokens));
  5499. if (!maybe_justify_content_value)
  5500. return nullptr;
  5501. return PlaceContentStyleValue::create(maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull());
  5502. }
  5503. ErrorOr<RefPtr<StyleValue>> Parser::parse_text_decoration_value(Vector<ComponentValue> const& component_values)
  5504. {
  5505. RefPtr<StyleValue> decoration_line;
  5506. RefPtr<StyleValue> decoration_thickness;
  5507. RefPtr<StyleValue> decoration_style;
  5508. RefPtr<StyleValue> decoration_color;
  5509. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  5510. auto tokens = TokenStream { component_values };
  5511. while (tokens.has_next_token()) {
  5512. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5513. if (!property_and_value.style_value)
  5514. return nullptr;
  5515. auto& value = property_and_value.style_value;
  5516. remove_property(remaining_longhands, property_and_value.property);
  5517. switch (property_and_value.property) {
  5518. case PropertyID::TextDecorationColor: {
  5519. VERIFY(!decoration_color);
  5520. decoration_color = value.release_nonnull();
  5521. continue;
  5522. }
  5523. case PropertyID::TextDecorationLine: {
  5524. VERIFY(!decoration_line);
  5525. tokens.reconsume_current_input_token();
  5526. auto parsed_decoration_line = TRY(parse_text_decoration_line_value(tokens));
  5527. if (!parsed_decoration_line)
  5528. return nullptr;
  5529. decoration_line = parsed_decoration_line.release_nonnull();
  5530. continue;
  5531. }
  5532. case PropertyID::TextDecorationThickness: {
  5533. VERIFY(!decoration_thickness);
  5534. decoration_thickness = value.release_nonnull();
  5535. continue;
  5536. }
  5537. case PropertyID::TextDecorationStyle: {
  5538. VERIFY(!decoration_style);
  5539. decoration_style = value.release_nonnull();
  5540. continue;
  5541. }
  5542. default:
  5543. VERIFY_NOT_REACHED();
  5544. }
  5545. }
  5546. if (!decoration_line)
  5547. decoration_line = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationLine));
  5548. if (!decoration_thickness)
  5549. decoration_thickness = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness));
  5550. if (!decoration_style)
  5551. decoration_style = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle));
  5552. if (!decoration_color)
  5553. decoration_color = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationColor));
  5554. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  5555. }
  5556. ErrorOr<RefPtr<StyleValue>> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  5557. {
  5558. StyleValueVector style_values;
  5559. while (tokens.has_next_token()) {
  5560. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::TextDecorationLine, tokens));
  5561. if (!maybe_value)
  5562. break;
  5563. auto value = maybe_value.release_nonnull();
  5564. if (auto maybe_line = value_id_to_text_decoration_line(value->to_identifier()); maybe_line.has_value()) {
  5565. if (maybe_line == TextDecorationLine::None) {
  5566. if (!style_values.is_empty())
  5567. break;
  5568. return value;
  5569. }
  5570. if (style_values.contains_slow(value))
  5571. break;
  5572. TRY(style_values.try_append(move(value)));
  5573. continue;
  5574. }
  5575. break;
  5576. }
  5577. if (style_values.is_empty())
  5578. return nullptr;
  5579. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  5580. }
  5581. ErrorOr<RefPtr<StyleValue>> Parser::parse_transform_value(Vector<ComponentValue> const& component_values)
  5582. {
  5583. StyleValueVector transformations;
  5584. auto tokens = TokenStream { component_values };
  5585. tokens.skip_whitespace();
  5586. while (tokens.has_next_token()) {
  5587. tokens.skip_whitespace();
  5588. auto const& part = tokens.next_token();
  5589. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_ascii_case("none"sv)) {
  5590. if (!transformations.is_empty())
  5591. return nullptr;
  5592. tokens.skip_whitespace();
  5593. if (tokens.has_next_token())
  5594. return nullptr;
  5595. return IdentifierStyleValue::create(ValueID::None);
  5596. }
  5597. if (!part.is_function())
  5598. return nullptr;
  5599. auto maybe_function = transform_function_from_string(part.function().name());
  5600. if (!maybe_function.has_value())
  5601. return nullptr;
  5602. auto function = maybe_function.release_value();
  5603. auto function_metadata = transform_function_metadata(function);
  5604. StyleValueVector values;
  5605. auto argument_tokens = TokenStream { part.function().values() };
  5606. argument_tokens.skip_whitespace();
  5607. size_t argument_index = 0;
  5608. while (argument_tokens.has_next_token()) {
  5609. if (argument_index == function_metadata.parameters.size()) {
  5610. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
  5611. return nullptr;
  5612. }
  5613. auto const& value = argument_tokens.next_token();
  5614. RefPtr<CalculatedStyleValue> maybe_calc_value;
  5615. if (auto maybe_dynamic_value = TRY(parse_dynamic_value(value))) {
  5616. // TODO: calc() is the only dynamic value we support for now, but more will come later.
  5617. // FIXME: Actually, calc() should probably be parsed inside parse_dimension_value() etc,
  5618. // so that it affects every use instead of us having to manually implement it.
  5619. VERIFY(maybe_dynamic_value->is_calculated());
  5620. maybe_calc_value = maybe_dynamic_value->as_calculated();
  5621. }
  5622. switch (function_metadata.parameters[argument_index].type) {
  5623. case TransformFunctionParameterType::Angle: {
  5624. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  5625. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  5626. values.append(maybe_calc_value.release_nonnull());
  5627. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  5628. values.append(TRY(AngleStyleValue::create(Angle::make_degrees(0))));
  5629. } else {
  5630. auto dimension_value = TRY(parse_dimension_value(value));
  5631. if (!dimension_value || !dimension_value->is_angle())
  5632. return nullptr;
  5633. values.append(dimension_value.release_nonnull());
  5634. }
  5635. break;
  5636. }
  5637. case TransformFunctionParameterType::Length: {
  5638. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  5639. values.append(maybe_calc_value.release_nonnull());
  5640. } else {
  5641. auto dimension_value = TRY(parse_dimension_value(value));
  5642. if (!dimension_value)
  5643. return nullptr;
  5644. if (dimension_value->is_length())
  5645. values.append(dimension_value.release_nonnull());
  5646. else
  5647. return nullptr;
  5648. }
  5649. break;
  5650. }
  5651. case TransformFunctionParameterType::LengthPercentage: {
  5652. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  5653. values.append(maybe_calc_value.release_nonnull());
  5654. } else {
  5655. auto dimension_value = TRY(parse_dimension_value(value));
  5656. if (!dimension_value)
  5657. return nullptr;
  5658. if (dimension_value->is_percentage() || dimension_value->is_length())
  5659. values.append(dimension_value.release_nonnull());
  5660. else
  5661. return nullptr;
  5662. }
  5663. break;
  5664. }
  5665. case TransformFunctionParameterType::Number: {
  5666. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5667. values.append(maybe_calc_value.release_nonnull());
  5668. } else {
  5669. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5670. argument_tokens.reconsume_current_input_token();
  5671. auto number = TRY(parse_number_value(argument_tokens));
  5672. if (!number)
  5673. return nullptr;
  5674. values.append(number.release_nonnull());
  5675. }
  5676. break;
  5677. }
  5678. }
  5679. argument_tokens.skip_whitespace();
  5680. if (argument_tokens.has_next_token()) {
  5681. // Arguments must be separated by commas.
  5682. if (!argument_tokens.next_token().is(Token::Type::Comma))
  5683. return nullptr;
  5684. argument_tokens.skip_whitespace();
  5685. // If there are no more parameters after the comma, this is invalid.
  5686. if (!argument_tokens.has_next_token())
  5687. return nullptr;
  5688. }
  5689. argument_index++;
  5690. }
  5691. if (argument_index < function_metadata.parameters.size() && function_metadata.parameters[argument_index].required) {
  5692. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  5693. return nullptr;
  5694. }
  5695. transformations.append(TRY(TransformationStyleValue::create(function, move(values))));
  5696. }
  5697. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  5698. }
  5699. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  5700. // FIXME: This only supports a 2D position
  5701. ErrorOr<RefPtr<StyleValue>> Parser::parse_transform_origin_value(Vector<ComponentValue> const& component_values)
  5702. {
  5703. enum class Axis {
  5704. None,
  5705. X,
  5706. Y,
  5707. };
  5708. struct AxisOffset {
  5709. Axis axis;
  5710. NonnullRefPtr<StyleValue> offset;
  5711. };
  5712. auto to_axis_offset = [](RefPtr<StyleValue> value) -> ErrorOr<Optional<AxisOffset>> {
  5713. if (value->is_percentage())
  5714. return AxisOffset { Axis::None, value->as_percentage() };
  5715. if (value->is_length())
  5716. return AxisOffset { Axis::None, value->as_length() };
  5717. if (value->is_identifier()) {
  5718. switch (value->to_identifier()) {
  5719. case ValueID::Top:
  5720. return AxisOffset { Axis::Y, TRY(PercentageStyleValue::create(Percentage(0))) };
  5721. case ValueID::Left:
  5722. return AxisOffset { Axis::X, TRY(PercentageStyleValue::create(Percentage(0))) };
  5723. case ValueID::Center:
  5724. return AxisOffset { Axis::None, TRY(PercentageStyleValue::create(Percentage(50))) };
  5725. case ValueID::Bottom:
  5726. return AxisOffset { Axis::Y, TRY(PercentageStyleValue::create(Percentage(100))) };
  5727. case ValueID::Right:
  5728. return AxisOffset { Axis::X, TRY(PercentageStyleValue::create(Percentage(100))) };
  5729. default:
  5730. return OptionalNone {};
  5731. }
  5732. }
  5733. return OptionalNone {};
  5734. };
  5735. auto make_list = [](NonnullRefPtr<StyleValue> const& x_value, NonnullRefPtr<StyleValue> const& y_value) -> ErrorOr<NonnullRefPtr<StyleValueList>> {
  5736. StyleValueVector values;
  5737. values.append(x_value);
  5738. values.append(y_value);
  5739. return StyleValueList::create(move(values), StyleValueList::Separator::Space);
  5740. };
  5741. auto tokens = TokenStream { component_values };
  5742. switch (component_values.size()) {
  5743. case 1: {
  5744. auto single_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  5745. if (!single_value.has_value())
  5746. return nullptr;
  5747. // If only one value is specified, the second value is assumed to be center.
  5748. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  5749. switch (single_value->axis) {
  5750. case Axis::None:
  5751. case Axis::X:
  5752. return make_list(single_value->offset, TRY(PercentageStyleValue::create(Percentage(50))));
  5753. case Axis::Y:
  5754. return make_list(TRY(PercentageStyleValue::create(Percentage(50))), single_value->offset);
  5755. }
  5756. VERIFY_NOT_REACHED();
  5757. }
  5758. case 2: {
  5759. auto first_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  5760. auto second_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  5761. if (!first_value.has_value() || !second_value.has_value())
  5762. return nullptr;
  5763. RefPtr<StyleValue> x_value;
  5764. RefPtr<StyleValue> y_value;
  5765. if (first_value->axis == Axis::X) {
  5766. x_value = first_value->offset;
  5767. } else if (first_value->axis == Axis::Y) {
  5768. y_value = first_value->offset;
  5769. }
  5770. if (second_value->axis == Axis::X) {
  5771. if (x_value)
  5772. return nullptr;
  5773. x_value = second_value->offset;
  5774. // Put the other in Y since its axis can't have been X
  5775. y_value = first_value->offset;
  5776. } else if (second_value->axis == Axis::Y) {
  5777. if (y_value)
  5778. return nullptr;
  5779. y_value = second_value->offset;
  5780. // Put the other in X since its axis can't have been Y
  5781. x_value = first_value->offset;
  5782. } else {
  5783. if (x_value) {
  5784. VERIFY(!y_value);
  5785. y_value = second_value->offset;
  5786. } else {
  5787. VERIFY(!x_value);
  5788. x_value = second_value->offset;
  5789. }
  5790. }
  5791. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  5792. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  5793. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  5794. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  5795. x_value = first_value->offset;
  5796. y_value = second_value->offset;
  5797. }
  5798. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  5799. }
  5800. }
  5801. return nullptr;
  5802. }
  5803. ErrorOr<RefPtr<StyleValue>> Parser::parse_as_css_value(PropertyID property_id)
  5804. {
  5805. auto component_values = parse_a_list_of_component_values(m_token_stream);
  5806. auto tokens = TokenStream(component_values);
  5807. auto parsed_value = parse_css_value(property_id, tokens);
  5808. if (parsed_value.is_error())
  5809. return nullptr;
  5810. return parsed_value.release_value();
  5811. }
  5812. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  5813. {
  5814. if (component_value.is_function()) {
  5815. auto const& function = component_value.function();
  5816. if (function.name().equals_ignoring_ascii_case("calc"sv)) {
  5817. auto calculated_style_value = parse_calculated_value(function.values());
  5818. if (calculated_style_value.is_error() || calculated_style_value.value().is_null()) {
  5819. // FIXME: Propagate error
  5820. return {};
  5821. }
  5822. return GridSize(LengthPercentage { *calculated_style_value.release_value() });
  5823. }
  5824. return {};
  5825. }
  5826. auto token = component_value.token();
  5827. if (token.is(Token::Type::Dimension) && token.dimension_unit().equals_ignoring_ascii_case("fr"sv)) {
  5828. float numeric_value = token.dimension_value();
  5829. if (numeric_value)
  5830. return GridSize(numeric_value);
  5831. }
  5832. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  5833. return GridSize::make_auto();
  5834. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("max-content"sv))
  5835. return GridSize(GridSize::Type::MaxContent);
  5836. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("min-content"sv))
  5837. return GridSize(GridSize::Type::MinContent);
  5838. auto dimension = parse_dimension(token);
  5839. if (!dimension.has_value())
  5840. return {};
  5841. if (dimension->is_length())
  5842. return GridSize(dimension->length());
  5843. else if (dimension->is_percentage())
  5844. return GridSize(dimension->percentage());
  5845. return {};
  5846. }
  5847. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  5848. {
  5849. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5850. // 'minmax(min, max)'
  5851. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  5852. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  5853. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5854. auto function_tokens = TokenStream(component_values);
  5855. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5856. if (comma_separated_list.size() != 2)
  5857. return {};
  5858. TokenStream part_one_tokens { comma_separated_list[0] };
  5859. part_one_tokens.skip_whitespace();
  5860. if (!part_one_tokens.has_next_token())
  5861. return {};
  5862. auto current_token = part_one_tokens.next_token();
  5863. auto min_grid_size = parse_grid_size(current_token);
  5864. TokenStream part_two_tokens { comma_separated_list[1] };
  5865. part_two_tokens.skip_whitespace();
  5866. if (!part_two_tokens.has_next_token())
  5867. return {};
  5868. current_token = part_two_tokens.next_token();
  5869. auto max_grid_size = parse_grid_size(current_token);
  5870. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  5871. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5872. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5873. if (min_grid_size.value().is_flexible_length())
  5874. return {};
  5875. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  5876. }
  5877. return {};
  5878. }
  5879. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  5880. {
  5881. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  5882. // 7.2.3.1. Syntax of repeat()
  5883. // The generic form of the repeat() syntax is, approximately,
  5884. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  5885. auto is_auto_fill = false;
  5886. auto is_auto_fit = false;
  5887. auto function_tokens = TokenStream(component_values);
  5888. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5889. if (comma_separated_list.size() != 2)
  5890. return {};
  5891. // The first argument specifies the number of repetitions.
  5892. TokenStream part_one_tokens { comma_separated_list[0] };
  5893. part_one_tokens.skip_whitespace();
  5894. if (!part_one_tokens.has_next_token())
  5895. return {};
  5896. auto current_token = part_one_tokens.next_token().token();
  5897. auto repeat_count = 0;
  5898. if (current_token.is(Token::Type::Number) && current_token.number().is_integer() && current_token.number_value() > 0)
  5899. repeat_count = current_token.number_value();
  5900. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fill"sv))
  5901. is_auto_fill = true;
  5902. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fit"sv))
  5903. is_auto_fit = true;
  5904. // The second argument is a track list, which is repeated that number of times.
  5905. TokenStream part_two_tokens { comma_separated_list[1] };
  5906. part_two_tokens.skip_whitespace();
  5907. if (!part_two_tokens.has_next_token())
  5908. return {};
  5909. Vector<CSS::ExplicitGridTrack> repeat_params;
  5910. Vector<Vector<String>> line_names_list;
  5911. auto last_object_was_line_names = false;
  5912. while (part_two_tokens.has_next_token()) {
  5913. auto token = part_two_tokens.next_token();
  5914. Vector<String> line_names;
  5915. if (token.is_block()) {
  5916. if (last_object_was_line_names)
  5917. return {};
  5918. last_object_was_line_names = true;
  5919. if (!token.block().is_square())
  5920. return {};
  5921. TokenStream block_tokens { token.block().values() };
  5922. while (block_tokens.has_next_token()) {
  5923. auto current_block_token = block_tokens.next_token();
  5924. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  5925. if (maybe_string.is_error())
  5926. return {};
  5927. line_names.append(maybe_string.value());
  5928. block_tokens.skip_whitespace();
  5929. }
  5930. line_names_list.append(line_names);
  5931. part_two_tokens.skip_whitespace();
  5932. } else {
  5933. last_object_was_line_names = false;
  5934. auto track_sizing_function = parse_track_sizing_function(token);
  5935. if (!track_sizing_function.has_value())
  5936. return {};
  5937. // However, there are some restrictions:
  5938. // The repeat() notation can’t be nested.
  5939. if (track_sizing_function.value().is_repeat())
  5940. return {};
  5941. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  5942. if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit))
  5943. return {};
  5944. repeat_params.append(track_sizing_function.value());
  5945. part_two_tokens.skip_whitespace();
  5946. }
  5947. }
  5948. while (line_names_list.size() <= repeat_params.size())
  5949. line_names_list.append({});
  5950. // Thus the precise syntax of the repeat() notation has several forms:
  5951. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  5952. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  5953. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  5954. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  5955. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  5956. // fixed number of repetitions.
  5957. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  5958. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  5959. // list, but the same track list can also contain <fixed-repeat>s.
  5960. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  5961. // subgrid keyword and cannot specify track sizes, only line names.
  5962. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  5963. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  5964. // 1fr [b a] 1fr [b].
  5965. if (is_auto_fill)
  5966. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFill);
  5967. else if (is_auto_fit)
  5968. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFit);
  5969. else
  5970. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), repeat_count);
  5971. }
  5972. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  5973. {
  5974. if (token.is_function()) {
  5975. auto const& function_token = token.function();
  5976. if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
  5977. auto maybe_repeat = parse_repeat(function_token.values());
  5978. if (maybe_repeat.has_value())
  5979. return CSS::ExplicitGridTrack(maybe_repeat.value());
  5980. else
  5981. return {};
  5982. } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
  5983. auto maybe_min_max_value = parse_min_max(function_token.values());
  5984. if (maybe_min_max_value.has_value())
  5985. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  5986. else
  5987. return {};
  5988. } else if (auto maybe_dynamic = parse_dynamic_value(token); !maybe_dynamic.is_error() && maybe_dynamic.value()) {
  5989. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_dynamic.release_value()->as_calculated())));
  5990. }
  5991. return {};
  5992. } else if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("auto"sv)) {
  5993. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  5994. } else if (token.is_block()) {
  5995. return {};
  5996. } else {
  5997. auto grid_size = parse_grid_size(token);
  5998. if (!grid_size.has_value())
  5999. return {};
  6000. return CSS::ExplicitGridTrack(grid_size.value());
  6001. }
  6002. }
  6003. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_size_list(Vector<ComponentValue> const& component_values, bool allow_separate_line_name_blocks)
  6004. {
  6005. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  6006. auto ident = TRY(parse_identifier_value(component_values.first()));
  6007. if (ident && ident->to_identifier() == ValueID::None) {
  6008. return GridTrackSizeListStyleValue::make_none();
  6009. }
  6010. }
  6011. Vector<CSS::ExplicitGridTrack> track_list;
  6012. Vector<Vector<String>> line_names_list;
  6013. auto last_object_was_line_names = false;
  6014. TokenStream tokens { component_values };
  6015. while (tokens.has_next_token()) {
  6016. auto token = tokens.next_token();
  6017. if (token.is_block()) {
  6018. if (last_object_was_line_names && !allow_separate_line_name_blocks)
  6019. return GridTrackSizeListStyleValue::make_auto();
  6020. last_object_was_line_names = true;
  6021. Vector<String> line_names;
  6022. if (!token.block().is_square())
  6023. return GridTrackSizeListStyleValue::make_auto();
  6024. TokenStream block_tokens { token.block().values() };
  6025. while (block_tokens.has_next_token()) {
  6026. auto current_block_token = block_tokens.next_token();
  6027. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  6028. if (maybe_string.is_error())
  6029. return nullptr;
  6030. line_names.append(maybe_string.value());
  6031. block_tokens.skip_whitespace();
  6032. }
  6033. line_names_list.append(line_names);
  6034. } else {
  6035. last_object_was_line_names = false;
  6036. auto track_sizing_function = parse_track_sizing_function(token);
  6037. if (!track_sizing_function.has_value())
  6038. return GridTrackSizeListStyleValue::make_auto();
  6039. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6040. // any other ones if the first one is auto-fill, etc.)
  6041. track_list.append(track_sizing_function.value());
  6042. }
  6043. }
  6044. while (line_names_list.size() <= track_list.size())
  6045. line_names_list.append({});
  6046. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
  6047. }
  6048. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_auto_track_sizes(Vector<ComponentValue> const& component_values)
  6049. {
  6050. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  6051. // <track-size>+
  6052. Vector<CSS::ExplicitGridTrack> track_list;
  6053. TokenStream tokens { component_values };
  6054. while (tokens.has_next_token()) {
  6055. auto token = tokens.next_token();
  6056. auto track_sizing_function = parse_track_sizing_function(token);
  6057. if (!track_sizing_function.has_value())
  6058. return GridTrackSizeListStyleValue::make_auto();
  6059. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6060. // any other ones if the first one is auto-fill, etc.)
  6061. track_list.append(track_sizing_function.value());
  6062. }
  6063. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, {}));
  6064. }
  6065. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_placement(Vector<ComponentValue> const& component_values)
  6066. {
  6067. // https://www.w3.org/TR/css-grid-2/#line-placement
  6068. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  6069. // <grid-line> =
  6070. // auto |
  6071. // <custom-ident> |
  6072. // [ <integer> && <custom-ident>? ] |
  6073. // [ span && [ <integer> || <custom-ident> ] ]
  6074. auto is_auto = [](Token token) -> bool {
  6075. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  6076. return true;
  6077. return false;
  6078. };
  6079. auto is_span = [](Token token) -> bool {
  6080. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("span"sv))
  6081. return true;
  6082. return false;
  6083. };
  6084. auto is_valid_integer = [](Token token) -> bool {
  6085. // An <integer> value of zero makes the declaration invalid.
  6086. if (token.is(Token::Type::Number) && token.number().is_integer() && token.number_value() != 0)
  6087. return true;
  6088. return false;
  6089. };
  6090. auto is_line_name = [](Token token) -> bool {
  6091. // The <custom-ident> additionally excludes the keywords span and auto.
  6092. if (token.is(Token::Type::Ident) && !token.ident().equals_ignoring_ascii_case("span"sv) && !token.ident().equals_ignoring_ascii_case("auto"sv))
  6093. return true;
  6094. return false;
  6095. };
  6096. auto tokens = TokenStream { component_values };
  6097. tokens.skip_whitespace();
  6098. auto current_token = tokens.next_token().token();
  6099. if (!tokens.has_next_token()) {
  6100. if (is_auto(current_token))
  6101. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement());
  6102. if (is_span(current_token))
  6103. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(1, true));
  6104. if (is_valid_integer(current_token))
  6105. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(static_cast<int>(current_token.number_value())));
  6106. if (is_line_name(current_token)) {
  6107. auto maybe_string = String::from_utf8(current_token.ident());
  6108. if (!maybe_string.is_error())
  6109. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(maybe_string.value()));
  6110. }
  6111. return nullptr;
  6112. }
  6113. auto span_value = false;
  6114. auto span_or_position_value = 0;
  6115. String line_name_value;
  6116. while (true) {
  6117. if (is_auto(current_token))
  6118. return nullptr;
  6119. if (is_span(current_token)) {
  6120. if (span_value == false)
  6121. span_value = true;
  6122. else
  6123. return nullptr;
  6124. }
  6125. if (is_valid_integer(current_token)) {
  6126. if (span_or_position_value == 0)
  6127. span_or_position_value = static_cast<int>(current_token.number_value());
  6128. else
  6129. return nullptr;
  6130. }
  6131. if (is_line_name(current_token)) {
  6132. if (line_name_value.is_empty()) {
  6133. auto maybe_string = String::from_utf8(current_token.ident());
  6134. if (maybe_string.is_error())
  6135. return nullptr;
  6136. line_name_value = maybe_string.release_value();
  6137. } else {
  6138. return nullptr;
  6139. }
  6140. }
  6141. tokens.skip_whitespace();
  6142. if (tokens.has_next_token())
  6143. current_token = tokens.next_token().token();
  6144. else
  6145. break;
  6146. }
  6147. // Negative integers or zero are invalid.
  6148. if (span_value && span_or_position_value < 1)
  6149. return nullptr;
  6150. // If the <integer> is omitted, it defaults to 1.
  6151. if (span_or_position_value == 0)
  6152. span_or_position_value = 1;
  6153. if (!line_name_value.is_empty())
  6154. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(line_name_value, span_or_position_value, span_value));
  6155. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(span_or_position_value, span_value));
  6156. }
  6157. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_placement_shorthand_value(Vector<ComponentValue> const& component_values)
  6158. {
  6159. auto tokens = TokenStream { component_values };
  6160. auto current_token = tokens.next_token().token();
  6161. Vector<ComponentValue> track_start_placement_tokens;
  6162. while (true) {
  6163. if (current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  6164. break;
  6165. track_start_placement_tokens.append(current_token);
  6166. if (!tokens.has_next_token())
  6167. break;
  6168. current_token = tokens.next_token().token();
  6169. }
  6170. Vector<ComponentValue> track_end_placement_tokens;
  6171. if (tokens.has_next_token()) {
  6172. current_token = tokens.next_token().token();
  6173. while (true) {
  6174. track_end_placement_tokens.append(current_token);
  6175. if (!tokens.has_next_token())
  6176. break;
  6177. current_token = tokens.next_token().token();
  6178. }
  6179. }
  6180. auto parsed_start_value = TRY(parse_grid_track_placement(track_start_placement_tokens));
  6181. if (parsed_start_value && track_end_placement_tokens.is_empty())
  6182. return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement().grid_track_placement());
  6183. auto parsed_end_value = TRY(parse_grid_track_placement(track_end_placement_tokens));
  6184. if (parsed_start_value && parsed_end_value)
  6185. return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement(), parsed_end_value.release_nonnull()->as_grid_track_placement());
  6186. return nullptr;
  6187. }
  6188. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  6189. // 7.4. Explicit Grid Shorthand: the grid-template property
  6190. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_size_list_shorthand_value(Vector<ComponentValue> const& component_values)
  6191. {
  6192. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  6193. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  6194. // none
  6195. // - Sets all three properties to their initial values (none).
  6196. // <'grid-template-rows'> / <'grid-template-columns'>
  6197. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  6198. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  6199. // - Sets grid-template-areas to the strings listed.
  6200. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  6201. // and splicing in the named lines defined before/after each size.
  6202. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  6203. Vector<ComponentValue> template_rows_tokens;
  6204. Vector<ComponentValue> template_columns_tokens;
  6205. Vector<ComponentValue> template_area_tokens;
  6206. int forward_slash_index = -1;
  6207. for (size_t x = 0; x < component_values.size(); x++) {
  6208. if (component_values[x].is_delim('/')) {
  6209. forward_slash_index = x;
  6210. break;
  6211. }
  6212. }
  6213. for (size_t x = 0; x < (forward_slash_index > -1 ? forward_slash_index : component_values.size()); x++) {
  6214. if (component_values[x].is_token() && component_values[x].token().is(Token::Type::String))
  6215. template_area_tokens.append(component_values[x]);
  6216. else
  6217. template_rows_tokens.append(component_values[x]);
  6218. }
  6219. if (forward_slash_index > -1) {
  6220. for (size_t x = forward_slash_index + 1; x < component_values.size(); x++)
  6221. template_columns_tokens.append(component_values[x]);
  6222. }
  6223. auto parsed_template_areas_values = TRY(parse_grid_template_areas_value(template_area_tokens));
  6224. auto parsed_template_rows_values = TRY(parse_grid_track_size_list(template_rows_tokens, true));
  6225. auto parsed_template_columns_values = TRY(parse_grid_track_size_list(template_columns_tokens));
  6226. return GridTrackSizeListShorthandStyleValue::create(
  6227. parsed_template_areas_values.release_nonnull()->as_grid_template_area(),
  6228. parsed_template_rows_values.release_nonnull()->as_grid_track_size_list(),
  6229. parsed_template_columns_values.release_nonnull()->as_grid_track_size_list());
  6230. }
  6231. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_area_shorthand_value(Vector<ComponentValue> const& component_values)
  6232. {
  6233. auto tokens = TokenStream { component_values };
  6234. Token current_token;
  6235. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  6236. current_token = tokens.next_token().token();
  6237. while (true) {
  6238. if (check_for_delimiter && current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  6239. break;
  6240. placement_tokens.append(current_token);
  6241. tokens.skip_whitespace();
  6242. if (!tokens.has_next_token())
  6243. break;
  6244. current_token = tokens.next_token().token();
  6245. }
  6246. };
  6247. Vector<ComponentValue> row_start_placement_tokens;
  6248. parse_placement_tokens(row_start_placement_tokens);
  6249. Vector<ComponentValue> column_start_placement_tokens;
  6250. if (tokens.has_next_token())
  6251. parse_placement_tokens(column_start_placement_tokens);
  6252. Vector<ComponentValue> row_end_placement_tokens;
  6253. if (tokens.has_next_token())
  6254. parse_placement_tokens(row_end_placement_tokens);
  6255. Vector<ComponentValue> column_end_placement_tokens;
  6256. if (tokens.has_next_token())
  6257. parse_placement_tokens(column_end_placement_tokens, false);
  6258. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  6259. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  6260. // grid-column-end.
  6261. auto row_start_style_value = TRY(parse_grid_track_placement(row_start_placement_tokens));
  6262. auto column_start_style_value = TRY(parse_grid_track_placement(column_start_placement_tokens));
  6263. auto row_end_style_value = TRY(parse_grid_track_placement(row_end_placement_tokens));
  6264. auto column_end_style_value = TRY(parse_grid_track_placement(column_end_placement_tokens));
  6265. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  6266. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  6267. // fourth value.
  6268. auto row_start = GridTrackPlacement::make_auto();
  6269. auto column_start = GridTrackPlacement::make_auto();
  6270. auto row_end = GridTrackPlacement::make_auto();
  6271. auto column_end = GridTrackPlacement::make_auto();
  6272. if (row_start_style_value)
  6273. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6274. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  6275. // that value. Otherwise, it is set to auto.
  6276. if (column_start_style_value)
  6277. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6278. else
  6279. column_start = row_start;
  6280. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  6281. // <custom-ident>; otherwise, it is set to auto.
  6282. if (row_end_style_value)
  6283. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6284. else
  6285. row_end = column_start;
  6286. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  6287. // that <custom-ident>; otherwise, it is set to auto.
  6288. if (column_end_style_value)
  6289. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6290. else
  6291. column_end = row_end;
  6292. return GridAreaShorthandStyleValue::create(row_start, column_start, row_end, column_end);
  6293. }
  6294. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_shorthand_value(Vector<ComponentValue> const& component_value)
  6295. {
  6296. // <'grid-template'> |
  6297. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  6298. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  6299. return parse_grid_track_size_list_shorthand_value(component_value);
  6300. }
  6301. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_template_areas_value(Vector<ComponentValue> const& component_values)
  6302. {
  6303. Vector<Vector<String>> grid_area_rows;
  6304. for (auto& component_value : component_values) {
  6305. Vector<String> grid_area_columns;
  6306. if (component_value.is(Token::Type::String)) {
  6307. auto const parts = TRY(TRY(String::from_utf8(component_value.token().string())).split(' '));
  6308. for (auto& part : parts) {
  6309. grid_area_columns.append(part);
  6310. }
  6311. }
  6312. grid_area_rows.append(move(grid_area_columns));
  6313. }
  6314. return GridTemplateAreaStyleValue::create(grid_area_rows);
  6315. }
  6316. static bool block_contains_var_or_attr(Block const& block);
  6317. static bool function_contains_var_or_attr(Function const& function)
  6318. {
  6319. if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
  6320. return true;
  6321. for (auto const& token : function.values()) {
  6322. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6323. return true;
  6324. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6325. return true;
  6326. }
  6327. return false;
  6328. }
  6329. bool block_contains_var_or_attr(Block const& block)
  6330. {
  6331. for (auto const& token : block.values()) {
  6332. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6333. return true;
  6334. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6335. return true;
  6336. }
  6337. return false;
  6338. };
  6339. Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6340. {
  6341. // FIXME: This is a hack. Until we can reasonably combine the error types, just log the error
  6342. // and return ParseError::InternalError if we get an AK::Error result.
  6343. #define FIXME_TRY(expression) \
  6344. ({ \
  6345. /* Ignore -Wshadow to allow nesting the macro. */ \
  6346. AK_IGNORE_DIAGNOSTIC("-Wshadow", \
  6347. auto&& _temporary_result = (expression)); \
  6348. if (_temporary_result.is_error()) [[unlikely]] { \
  6349. dbgln("System error when parsing style value: {}", _temporary_result.release_error()); \
  6350. return ParseError::InternalError; \
  6351. } \
  6352. _temporary_result.release_value(); \
  6353. })
  6354. m_context.set_current_property_id(property_id);
  6355. Vector<ComponentValue> component_values;
  6356. bool contains_var_or_attr = false;
  6357. while (tokens.has_next_token()) {
  6358. auto const& token = tokens.next_token();
  6359. if (token.is(Token::Type::Semicolon)) {
  6360. tokens.reconsume_current_input_token();
  6361. break;
  6362. }
  6363. if (property_id != PropertyID::Custom) {
  6364. if (token.is(Token::Type::Whitespace))
  6365. continue;
  6366. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  6367. return ParseError::IncludesIgnoredVendorPrefix;
  6368. }
  6369. if (!contains_var_or_attr) {
  6370. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6371. contains_var_or_attr = true;
  6372. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  6373. contains_var_or_attr = true;
  6374. }
  6375. component_values.append(token);
  6376. }
  6377. if (property_id == PropertyID::Custom || contains_var_or_attr)
  6378. return FIXME_TRY(UnresolvedStyleValue::create(move(component_values), contains_var_or_attr));
  6379. if (component_values.is_empty())
  6380. return ParseError::SyntaxError;
  6381. if (component_values.size() == 1) {
  6382. if (auto parsed_value = FIXME_TRY(parse_builtin_value(component_values.first())))
  6383. return parsed_value.release_nonnull();
  6384. }
  6385. // Special-case property handling
  6386. switch (property_id) {
  6387. case PropertyID::AspectRatio:
  6388. if (auto parsed_value = FIXME_TRY(parse_aspect_ratio_value(component_values)))
  6389. return parsed_value.release_nonnull();
  6390. return ParseError::SyntaxError;
  6391. case PropertyID::BackdropFilter:
  6392. if (auto parsed_value = FIXME_TRY(parse_filter_value_list_value(component_values)))
  6393. return parsed_value.release_nonnull();
  6394. return ParseError::SyntaxError;
  6395. case PropertyID::Background:
  6396. if (auto parsed_value = FIXME_TRY(parse_background_value(component_values)))
  6397. return parsed_value.release_nonnull();
  6398. return ParseError::SyntaxError;
  6399. case PropertyID::BackgroundAttachment:
  6400. case PropertyID::BackgroundClip:
  6401. case PropertyID::BackgroundImage:
  6402. case PropertyID::BackgroundOrigin:
  6403. if (auto parsed_value = FIXME_TRY(parse_simple_comma_separated_value_list(property_id, component_values)))
  6404. return parsed_value.release_nonnull();
  6405. return ParseError::SyntaxError;
  6406. case PropertyID::BackgroundPosition:
  6407. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); })))
  6408. return parsed_value.release_nonnull();
  6409. return ParseError::SyntaxError;
  6410. case PropertyID::BackgroundPositionX:
  6411. case PropertyID::BackgroundPositionY:
  6412. 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); })))
  6413. return parsed_value.release_nonnull();
  6414. return ParseError::SyntaxError;
  6415. case PropertyID::BackgroundRepeat:
  6416. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); })))
  6417. return parsed_value.release_nonnull();
  6418. return ParseError::SyntaxError;
  6419. case PropertyID::BackgroundSize:
  6420. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); })))
  6421. return parsed_value.release_nonnull();
  6422. return ParseError::SyntaxError;
  6423. case PropertyID::Border:
  6424. case PropertyID::BorderBottom:
  6425. case PropertyID::BorderLeft:
  6426. case PropertyID::BorderRight:
  6427. case PropertyID::BorderTop:
  6428. if (auto parsed_value = FIXME_TRY(parse_border_value(component_values)))
  6429. return parsed_value.release_nonnull();
  6430. return ParseError::SyntaxError;
  6431. case PropertyID::BorderTopLeftRadius:
  6432. case PropertyID::BorderTopRightRadius:
  6433. case PropertyID::BorderBottomRightRadius:
  6434. case PropertyID::BorderBottomLeftRadius:
  6435. if (auto parsed_value = FIXME_TRY(parse_border_radius_value(component_values)))
  6436. return parsed_value.release_nonnull();
  6437. return ParseError::SyntaxError;
  6438. case PropertyID::BorderRadius:
  6439. if (auto parsed_value = FIXME_TRY(parse_border_radius_shorthand_value(component_values)))
  6440. return parsed_value.release_nonnull();
  6441. return ParseError::SyntaxError;
  6442. case PropertyID::BoxShadow:
  6443. if (auto parsed_value = FIXME_TRY(parse_shadow_value(component_values, AllowInsetKeyword::Yes)))
  6444. return parsed_value.release_nonnull();
  6445. return ParseError::SyntaxError;
  6446. case PropertyID::Content:
  6447. if (auto parsed_value = FIXME_TRY(parse_content_value(component_values)))
  6448. return parsed_value.release_nonnull();
  6449. return ParseError::SyntaxError;
  6450. case PropertyID::Display:
  6451. if (auto parsed_value = FIXME_TRY(parse_display_value(component_values)))
  6452. return parsed_value.release_nonnull();
  6453. return ParseError::SyntaxError;
  6454. case PropertyID::Flex:
  6455. if (auto parsed_value = FIXME_TRY(parse_flex_value(component_values)))
  6456. return parsed_value.release_nonnull();
  6457. return ParseError::SyntaxError;
  6458. case PropertyID::FlexFlow:
  6459. if (auto parsed_value = FIXME_TRY(parse_flex_flow_value(component_values)))
  6460. return parsed_value.release_nonnull();
  6461. return ParseError::SyntaxError;
  6462. case PropertyID::Font:
  6463. if (auto parsed_value = FIXME_TRY(parse_font_value(component_values)))
  6464. return parsed_value.release_nonnull();
  6465. return ParseError::SyntaxError;
  6466. case PropertyID::FontFamily: {
  6467. auto tokens_without_whitespace = TokenStream { component_values };
  6468. if (auto parsed_value = FIXME_TRY(parse_font_family_value(tokens_without_whitespace)))
  6469. return parsed_value.release_nonnull();
  6470. return ParseError::SyntaxError;
  6471. }
  6472. case PropertyID::GridColumn:
  6473. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement_shorthand_value(component_values)))
  6474. return parsed_value.release_nonnull();
  6475. return ParseError::SyntaxError;
  6476. case PropertyID::GridArea:
  6477. if (auto parsed_value = FIXME_TRY(parse_grid_area_shorthand_value(component_values)))
  6478. return parsed_value.release_nonnull();
  6479. return ParseError::SyntaxError;
  6480. case PropertyID::GridTemplateAreas:
  6481. if (auto parsed_value = FIXME_TRY(parse_grid_template_areas_value(component_values)))
  6482. return parsed_value.release_nonnull();
  6483. return ParseError::SyntaxError;
  6484. case PropertyID::GridColumnEnd:
  6485. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6486. return parsed_value.release_nonnull();
  6487. return ParseError::SyntaxError;
  6488. case PropertyID::GridColumnStart:
  6489. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6490. return parsed_value.release_nonnull();
  6491. return ParseError::SyntaxError;
  6492. case PropertyID::GridRow:
  6493. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement_shorthand_value(component_values)))
  6494. return parsed_value.release_nonnull();
  6495. return ParseError::SyntaxError;
  6496. case PropertyID::GridRowEnd:
  6497. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6498. return parsed_value.release_nonnull();
  6499. return ParseError::SyntaxError;
  6500. case PropertyID::GridRowStart:
  6501. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6502. return parsed_value.release_nonnull();
  6503. return ParseError::SyntaxError;
  6504. case PropertyID::Grid:
  6505. if (auto parsed_value = FIXME_TRY(parse_grid_shorthand_value(component_values)))
  6506. return parsed_value.release_nonnull();
  6507. return ParseError::SyntaxError;
  6508. case PropertyID::GridTemplate:
  6509. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list_shorthand_value(component_values)))
  6510. return parsed_value.release_nonnull();
  6511. return ParseError::SyntaxError;
  6512. case PropertyID::GridTemplateColumns:
  6513. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list(component_values)))
  6514. return parsed_value.release_nonnull();
  6515. return ParseError::SyntaxError;
  6516. case PropertyID::GridTemplateRows:
  6517. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list(component_values)))
  6518. return parsed_value.release_nonnull();
  6519. return ParseError::SyntaxError;
  6520. case PropertyID::GridAutoColumns:
  6521. if (auto parsed_value = FIXME_TRY(parse_grid_auto_track_sizes(component_values)))
  6522. return parsed_value.release_nonnull();
  6523. return ParseError::SyntaxError;
  6524. case PropertyID::GridAutoRows:
  6525. if (auto parsed_value = FIXME_TRY(parse_grid_auto_track_sizes(component_values)))
  6526. return parsed_value.release_nonnull();
  6527. return ParseError::SyntaxError;
  6528. case PropertyID::ListStyle:
  6529. if (auto parsed_value = FIXME_TRY(parse_list_style_value(component_values)))
  6530. return parsed_value.release_nonnull();
  6531. return ParseError::SyntaxError;
  6532. case PropertyID::Overflow:
  6533. if (auto parsed_value = FIXME_TRY(parse_overflow_value(component_values)))
  6534. return parsed_value.release_nonnull();
  6535. return ParseError::SyntaxError;
  6536. case PropertyID::PlaceContent:
  6537. if (auto parsed_value = FIXME_TRY(parse_place_content_value(component_values)))
  6538. return parsed_value.release_nonnull();
  6539. return ParseError::SyntaxError;
  6540. case PropertyID::TextDecoration:
  6541. if (auto parsed_value = FIXME_TRY(parse_text_decoration_value(component_values)))
  6542. return parsed_value.release_nonnull();
  6543. return ParseError::SyntaxError;
  6544. case PropertyID::TextDecorationLine: {
  6545. TokenStream value_tokens { component_values };
  6546. auto parsed_value = FIXME_TRY(parse_text_decoration_line_value(value_tokens));
  6547. if (parsed_value && !value_tokens.has_next_token())
  6548. return parsed_value.release_nonnull();
  6549. return ParseError::SyntaxError;
  6550. }
  6551. case PropertyID::TextShadow:
  6552. if (auto parsed_value = FIXME_TRY(parse_shadow_value(component_values, AllowInsetKeyword::No)))
  6553. return parsed_value.release_nonnull();
  6554. return ParseError::SyntaxError;
  6555. case PropertyID::Transform:
  6556. if (auto parsed_value = FIXME_TRY(parse_transform_value(component_values)))
  6557. return parsed_value.release_nonnull();
  6558. return ParseError::SyntaxError;
  6559. case PropertyID::TransformOrigin:
  6560. if (auto parsed_value = FIXME_TRY(parse_transform_origin_value(component_values)))
  6561. return parsed_value.release_nonnull();
  6562. return ParseError ::SyntaxError;
  6563. case PropertyID::Fill:
  6564. case PropertyID::Stroke:
  6565. if (component_values.size() == 1) {
  6566. if (auto parsed_url = FIXME_TRY(parse_url_value(component_values.first())))
  6567. return parsed_url.release_nonnull();
  6568. }
  6569. // Allow normal value parsing to continue.
  6570. // URL is done here to avoid ambiguity with images.
  6571. break;
  6572. default:
  6573. break;
  6574. }
  6575. // If there's only 1 ComponentValue, we can only produce a single StyleValue.
  6576. if (component_values.size() == 1) {
  6577. auto stream = TokenStream { component_values };
  6578. if (auto parsed_value = FIXME_TRY(parse_css_value_for_property(property_id, stream)))
  6579. return parsed_value.release_nonnull();
  6580. return ParseError::SyntaxError;
  6581. }
  6582. // Multiple ComponentValues will usually produce multiple StyleValues, so make a StyleValueList.
  6583. {
  6584. StyleValueVector parsed_values;
  6585. auto stream = TokenStream { component_values };
  6586. while (auto parsed_value = FIXME_TRY(parse_css_value_for_property(property_id, stream))) {
  6587. FIXME_TRY(parsed_values.try_append(parsed_value.release_nonnull()));
  6588. if (!stream.has_next_token())
  6589. break;
  6590. }
  6591. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 StyleValue, return it directly.
  6592. if (parsed_values.size() == 1)
  6593. return *parsed_values.take_first();
  6594. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  6595. return FIXME_TRY(StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space));
  6596. }
  6597. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  6598. auto unassigned_properties = longhands_for_shorthand(property_id);
  6599. if (unassigned_properties.is_empty())
  6600. return ParseError::SyntaxError;
  6601. auto stream = TokenStream { component_values };
  6602. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<StyleValue const>>> assigned_values;
  6603. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  6604. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  6605. if (!property_and_value.is_error() && property_and_value.value().style_value) {
  6606. auto property = property_and_value.value().property;
  6607. auto value = property_and_value.release_value().style_value;
  6608. auto& values = assigned_values.ensure(to_underlying(property));
  6609. if (values.size() + 1 == property_maximum_value_count(property)) {
  6610. // We're done with this property, move on to the next one.
  6611. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  6612. }
  6613. values.append(value.release_nonnull());
  6614. continue;
  6615. }
  6616. // No property matched, so we're done.
  6617. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.peek_token().to_debug_string());
  6618. for (auto id : unassigned_properties)
  6619. dbgln(" {}", string_from_property_id(id));
  6620. break;
  6621. }
  6622. for (auto& property : unassigned_properties)
  6623. assigned_values.ensure(to_underlying(property)).append(FIXME_TRY(property_initial_value(m_context.realm(), property)));
  6624. stream.skip_whitespace();
  6625. if (stream.has_next_token())
  6626. return ParseError::SyntaxError;
  6627. Vector<PropertyID> longhand_properties;
  6628. longhand_properties.ensure_capacity(assigned_values.size());
  6629. for (auto& it : assigned_values)
  6630. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  6631. StyleValueVector longhand_values;
  6632. longhand_values.ensure_capacity(assigned_values.size());
  6633. for (auto& it : assigned_values) {
  6634. if (it.value.size() == 1)
  6635. longhand_values.unchecked_append(it.value.take_first());
  6636. else
  6637. longhand_values.unchecked_append(FIXME_TRY(StyleValueList::create(move(it.value), StyleValueList::Separator::Space)));
  6638. }
  6639. return { FIXME_TRY(CompositeStyleValue::create(move(longhand_properties), move(longhand_values))) };
  6640. #undef FIXME_TRY
  6641. }
  6642. ErrorOr<RefPtr<StyleValue>> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6643. {
  6644. auto result = parse_css_value_for_properties({ &property_id, 1 }, tokens);
  6645. if (result.is_error())
  6646. return result.release_error();
  6647. return result.value().style_value;
  6648. }
  6649. ErrorOr<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  6650. {
  6651. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  6652. for (auto const& property : property_ids) {
  6653. if (property_accepts_type(property, value_type))
  6654. return property;
  6655. }
  6656. return {};
  6657. };
  6658. auto any_property_accepts_identifier = [](ReadonlySpan<PropertyID> property_ids, ValueID identifier) -> Optional<PropertyID> {
  6659. for (auto const& property : property_ids) {
  6660. if (property_accepts_identifier(property, identifier))
  6661. return property;
  6662. }
  6663. return {};
  6664. };
  6665. auto& peek_token = tokens.peek_token();
  6666. if (peek_token.is(Token::Type::Ident)) {
  6667. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  6668. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  6669. auto ident = value_id_from_string(peek_token.token().ident());
  6670. if (ident.has_value()) {
  6671. if (auto property = any_property_accepts_identifier(property_ids, ident.value()); property.has_value()) {
  6672. (void)tokens.next_token();
  6673. return PropertyAndValue { *property, TRY(IdentifierStyleValue::create(ident.value())) };
  6674. }
  6675. }
  6676. // Custom idents
  6677. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  6678. (void)tokens.next_token();
  6679. return PropertyAndValue { *property, TRY(CustomIdentStyleValue::create(TRY(FlyString::from_utf8(peek_token.token().ident())))) };
  6680. }
  6681. }
  6682. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  6683. if (auto maybe_color = TRY(parse_color_value(peek_token))) {
  6684. (void)tokens.next_token();
  6685. return PropertyAndValue { *property, maybe_color };
  6686. }
  6687. }
  6688. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  6689. if (auto maybe_image = TRY(parse_image_value(peek_token))) {
  6690. (void)tokens.next_token();
  6691. return PropertyAndValue { *property, maybe_image };
  6692. }
  6693. }
  6694. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  6695. if (auto maybe_ratio = TRY(parse_ratio_value(tokens)))
  6696. return PropertyAndValue { *property, maybe_ratio };
  6697. }
  6698. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  6699. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  6700. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  6701. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  6702. if (property_accepting_integer.has_value()) {
  6703. auto transaction = tokens.begin_transaction();
  6704. if (auto integer = TRY(parse_integer_value(tokens)); integer && property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  6705. transaction.commit();
  6706. return PropertyAndValue { *property_accepting_integer, integer };
  6707. }
  6708. }
  6709. if (property_accepting_number.has_value()) {
  6710. auto transaction = tokens.begin_transaction();
  6711. if (auto number = TRY(parse_number_value(tokens)); number && property_accepts_number(*property_accepting_number, number->as_number().number())) {
  6712. transaction.commit();
  6713. return PropertyAndValue { *property_accepting_number, number };
  6714. }
  6715. }
  6716. }
  6717. if (peek_token.is(Token::Type::Percentage)) {
  6718. auto percentage = Percentage(peek_token.token().percentage());
  6719. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  6720. (void)tokens.next_token();
  6721. return PropertyAndValue { *property, TRY(PercentageStyleValue::create(percentage)) };
  6722. }
  6723. }
  6724. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  6725. if (auto maybe_rect = TRY(parse_rect_value(peek_token))) {
  6726. (void)tokens.next_token();
  6727. return PropertyAndValue { *property, maybe_rect };
  6728. }
  6729. }
  6730. if (peek_token.is(Token::Type::String)) {
  6731. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  6732. return PropertyAndValue { *property, TRY(StringStyleValue::create(TRY(String::from_utf8(tokens.next_token().token().string())))) };
  6733. }
  6734. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  6735. if (auto url = TRY(parse_url_value(peek_token))) {
  6736. (void)tokens.next_token();
  6737. return PropertyAndValue { *property, url };
  6738. }
  6739. }
  6740. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  6741. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  6742. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  6743. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  6744. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  6745. if (property_accepts_dimension) {
  6746. auto transaction = tokens.begin_transaction();
  6747. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  6748. (void)tokens.next_token();
  6749. auto dimension = maybe_dimension.release_value();
  6750. if (dimension.is_angle()) {
  6751. auto angle = dimension.angle();
  6752. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  6753. transaction.commit();
  6754. return PropertyAndValue { *property, TRY(AngleStyleValue::create(angle)) };
  6755. }
  6756. }
  6757. if (dimension.is_frequency()) {
  6758. auto frequency = dimension.frequency();
  6759. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  6760. transaction.commit();
  6761. return PropertyAndValue { *property, TRY(FrequencyStyleValue::create(frequency)) };
  6762. }
  6763. }
  6764. if (dimension.is_length()) {
  6765. auto length = dimension.length();
  6766. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  6767. transaction.commit();
  6768. return PropertyAndValue { *property, TRY(LengthStyleValue::create(length)) };
  6769. }
  6770. }
  6771. if (dimension.is_resolution()) {
  6772. auto resolution = dimension.resolution();
  6773. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  6774. transaction.commit();
  6775. return PropertyAndValue { *property, TRY(ResolutionStyleValue::create(resolution)) };
  6776. }
  6777. }
  6778. if (dimension.is_time()) {
  6779. auto time = dimension.time();
  6780. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  6781. transaction.commit();
  6782. return PropertyAndValue { *property, TRY(TimeStyleValue::create(time)) };
  6783. }
  6784. }
  6785. }
  6786. }
  6787. // In order to not end up parsing `calc()` and other math expressions multiple times,
  6788. // we parse it once, and then see if its resolved type matches what the property accepts.
  6789. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  6790. if (auto maybe_dynamic = TRY(parse_dynamic_value(peek_token)); maybe_dynamic && maybe_dynamic->is_calculated()) {
  6791. (void)tokens.next_token();
  6792. auto& calculated = maybe_dynamic->as_calculated();
  6793. switch (calculated.resolved_type()) {
  6794. case CalculatedStyleValue::ResolvedType::Angle:
  6795. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  6796. return PropertyAndValue { *property, calculated };
  6797. break;
  6798. case CalculatedStyleValue::ResolvedType::Frequency:
  6799. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  6800. return PropertyAndValue { *property, calculated };
  6801. break;
  6802. case CalculatedStyleValue::ResolvedType::Integer:
  6803. case CalculatedStyleValue::ResolvedType::Number:
  6804. if (property_accepts_numeric) {
  6805. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  6806. return PropertyAndValue { property_or_resolved, calculated };
  6807. }
  6808. break;
  6809. case CalculatedStyleValue::ResolvedType::Length:
  6810. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  6811. return PropertyAndValue { *property, calculated };
  6812. break;
  6813. case CalculatedStyleValue::ResolvedType::Percentage:
  6814. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  6815. return PropertyAndValue { *property, calculated };
  6816. break;
  6817. case CalculatedStyleValue::ResolvedType::Time:
  6818. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  6819. return PropertyAndValue { *property, calculated };
  6820. break;
  6821. }
  6822. }
  6823. }
  6824. return PropertyAndValue { property_ids.first(), nullptr };
  6825. }
  6826. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<ComponentValue>& values)
  6827. {
  6828. auto transaction = values.begin_transaction();
  6829. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  6830. if constexpr (CSS_PARSER_DEBUG) {
  6831. dbgln_if(CSS_PARSER_DEBUG, "Invalid An+B value:");
  6832. values.dump_all_tokens();
  6833. }
  6834. return {};
  6835. };
  6836. auto is_n = [](ComponentValue const& value) -> bool {
  6837. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n"sv);
  6838. };
  6839. auto is_ndash = [](ComponentValue const& value) -> bool {
  6840. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n-"sv);
  6841. };
  6842. auto is_dashn = [](ComponentValue const& value) -> bool {
  6843. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n"sv);
  6844. };
  6845. auto is_dashndash = [](ComponentValue const& value) -> bool {
  6846. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n-"sv);
  6847. };
  6848. auto is_sign = [](ComponentValue const& value) -> bool {
  6849. return value.is(Token::Type::Delim) && (value.token().delim() == '+' || value.token().delim() == '-');
  6850. };
  6851. auto is_n_dimension = [](ComponentValue const& value) -> bool {
  6852. if (!value.is(Token::Type::Dimension))
  6853. return false;
  6854. if (!value.token().number().is_integer())
  6855. return false;
  6856. if (!value.token().dimension_unit().equals_ignoring_ascii_case("n"sv))
  6857. return false;
  6858. return true;
  6859. };
  6860. auto is_ndash_dimension = [](ComponentValue const& value) -> bool {
  6861. if (!value.is(Token::Type::Dimension))
  6862. return false;
  6863. if (!value.token().number().is_integer())
  6864. return false;
  6865. if (!value.token().dimension_unit().equals_ignoring_ascii_case("n-"sv))
  6866. return false;
  6867. return true;
  6868. };
  6869. auto is_ndashdigit_dimension = [](ComponentValue const& value) -> bool {
  6870. if (!value.is(Token::Type::Dimension))
  6871. return false;
  6872. if (!value.token().number().is_integer())
  6873. return false;
  6874. auto dimension_unit = value.token().dimension_unit();
  6875. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  6876. return false;
  6877. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  6878. if (!is_ascii_digit(dimension_unit[i]))
  6879. return false;
  6880. }
  6881. return true;
  6882. };
  6883. auto is_ndashdigit_ident = [](ComponentValue const& value) -> bool {
  6884. if (!value.is(Token::Type::Ident))
  6885. return false;
  6886. auto ident = value.token().ident();
  6887. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  6888. return false;
  6889. for (size_t i = 2; i < ident.length(); ++i) {
  6890. if (!is_ascii_digit(ident[i]))
  6891. return false;
  6892. }
  6893. return true;
  6894. };
  6895. auto is_dashndashdigit_ident = [](ComponentValue const& value) -> bool {
  6896. if (!value.is(Token::Type::Ident))
  6897. return false;
  6898. auto ident = value.token().ident();
  6899. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  6900. return false;
  6901. if (ident.length() == 3)
  6902. return false;
  6903. for (size_t i = 3; i < ident.length(); ++i) {
  6904. if (!is_ascii_digit(ident[i]))
  6905. return false;
  6906. }
  6907. return true;
  6908. };
  6909. auto is_integer = [](ComponentValue const& value) -> bool {
  6910. return value.is(Token::Type::Number) && value.token().number().is_integer();
  6911. };
  6912. auto is_signed_integer = [](ComponentValue const& value) -> bool {
  6913. return value.is(Token::Type::Number) && value.token().number().is_integer_with_explicit_sign();
  6914. };
  6915. auto is_signless_integer = [](ComponentValue const& value) -> bool {
  6916. return value.is(Token::Type::Number) && !value.token().number().is_integer_with_explicit_sign();
  6917. };
  6918. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  6919. // Unfortunately these can't be in the same order as in the spec.
  6920. values.skip_whitespace();
  6921. auto const& first_value = values.next_token();
  6922. // odd | even
  6923. if (first_value.is(Token::Type::Ident)) {
  6924. auto ident = first_value.token().ident();
  6925. if (ident.equals_ignoring_ascii_case("odd"sv)) {
  6926. transaction.commit();
  6927. return Selector::SimpleSelector::ANPlusBPattern { 2, 1 };
  6928. }
  6929. if (ident.equals_ignoring_ascii_case("even"sv)) {
  6930. transaction.commit();
  6931. return Selector::SimpleSelector::ANPlusBPattern { 2, 0 };
  6932. }
  6933. }
  6934. // <integer>
  6935. if (is_integer(first_value)) {
  6936. int b = first_value.token().to_integer();
  6937. transaction.commit();
  6938. return Selector::SimpleSelector::ANPlusBPattern { 0, b };
  6939. }
  6940. // <n-dimension>
  6941. // <n-dimension> <signed-integer>
  6942. // <n-dimension> ['+' | '-'] <signless-integer>
  6943. if (is_n_dimension(first_value)) {
  6944. int a = first_value.token().dimension_value_int();
  6945. values.skip_whitespace();
  6946. // <n-dimension> <signed-integer>
  6947. if (is_signed_integer(values.peek_token())) {
  6948. int b = values.next_token().token().to_integer();
  6949. transaction.commit();
  6950. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  6951. }
  6952. // <n-dimension> ['+' | '-'] <signless-integer>
  6953. {
  6954. auto child_transaction = transaction.create_child();
  6955. auto const& second_value = values.next_token();
  6956. values.skip_whitespace();
  6957. auto const& third_value = values.next_token();
  6958. if (is_sign(second_value) && is_signless_integer(third_value)) {
  6959. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  6960. child_transaction.commit();
  6961. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  6962. }
  6963. }
  6964. // <n-dimension>
  6965. transaction.commit();
  6966. return Selector::SimpleSelector::ANPlusBPattern { a, 0 };
  6967. }
  6968. // <ndash-dimension> <signless-integer>
  6969. if (is_ndash_dimension(first_value)) {
  6970. values.skip_whitespace();
  6971. auto const& second_value = values.next_token();
  6972. if (is_signless_integer(second_value)) {
  6973. int a = first_value.token().dimension_value_int();
  6974. int b = -second_value.token().to_integer();
  6975. transaction.commit();
  6976. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  6977. }
  6978. return syntax_error();
  6979. }
  6980. // <ndashdigit-dimension>
  6981. if (is_ndashdigit_dimension(first_value)) {
  6982. auto const& dimension = first_value.token();
  6983. int a = dimension.dimension_value_int();
  6984. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  6985. if (maybe_b.has_value()) {
  6986. transaction.commit();
  6987. return Selector::SimpleSelector::ANPlusBPattern { a, maybe_b.value() };
  6988. }
  6989. return syntax_error();
  6990. }
  6991. // <dashndashdigit-ident>
  6992. if (is_dashndashdigit_ident(first_value)) {
  6993. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  6994. if (maybe_b.has_value()) {
  6995. transaction.commit();
  6996. return Selector::SimpleSelector::ANPlusBPattern { -1, maybe_b.value() };
  6997. }
  6998. return syntax_error();
  6999. }
  7000. // -n
  7001. // -n <signed-integer>
  7002. // -n ['+' | '-'] <signless-integer>
  7003. if (is_dashn(first_value)) {
  7004. values.skip_whitespace();
  7005. // -n <signed-integer>
  7006. if (is_signed_integer(values.peek_token())) {
  7007. int b = values.next_token().token().to_integer();
  7008. transaction.commit();
  7009. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7010. }
  7011. // -n ['+' | '-'] <signless-integer>
  7012. {
  7013. auto child_transaction = transaction.create_child();
  7014. auto const& second_value = values.next_token();
  7015. values.skip_whitespace();
  7016. auto const& third_value = values.next_token();
  7017. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7018. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7019. child_transaction.commit();
  7020. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7021. }
  7022. }
  7023. // -n
  7024. transaction.commit();
  7025. return Selector::SimpleSelector::ANPlusBPattern { -1, 0 };
  7026. }
  7027. // -n- <signless-integer>
  7028. if (is_dashndash(first_value)) {
  7029. values.skip_whitespace();
  7030. auto const& second_value = values.next_token();
  7031. if (is_signless_integer(second_value)) {
  7032. int b = -second_value.token().to_integer();
  7033. transaction.commit();
  7034. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7035. }
  7036. return syntax_error();
  7037. }
  7038. // All that's left now are these:
  7039. // '+'?† n
  7040. // '+'?† n <signed-integer>
  7041. // '+'?† n ['+' | '-'] <signless-integer>
  7042. // '+'?† n- <signless-integer>
  7043. // '+'?† <ndashdigit-ident>
  7044. // In all of these cases, the + is optional, and has no effect.
  7045. // So, we just skip the +, and carry on.
  7046. if (!first_value.is_delim('+')) {
  7047. values.reconsume_current_input_token();
  7048. // We do *not* skip whitespace here.
  7049. }
  7050. auto const& first_after_plus = values.next_token();
  7051. // '+'?† n
  7052. // '+'?† n <signed-integer>
  7053. // '+'?† n ['+' | '-'] <signless-integer>
  7054. if (is_n(first_after_plus)) {
  7055. values.skip_whitespace();
  7056. // '+'?† n <signed-integer>
  7057. if (is_signed_integer(values.peek_token())) {
  7058. int b = values.next_token().token().to_integer();
  7059. transaction.commit();
  7060. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7061. }
  7062. // '+'?† n ['+' | '-'] <signless-integer>
  7063. {
  7064. auto child_transaction = transaction.create_child();
  7065. auto const& second_value = values.next_token();
  7066. values.skip_whitespace();
  7067. auto const& third_value = values.next_token();
  7068. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7069. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7070. child_transaction.commit();
  7071. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7072. }
  7073. }
  7074. // '+'?† n
  7075. transaction.commit();
  7076. return Selector::SimpleSelector::ANPlusBPattern { 1, 0 };
  7077. }
  7078. // '+'?† n- <signless-integer>
  7079. if (is_ndash(first_after_plus)) {
  7080. values.skip_whitespace();
  7081. auto const& second_value = values.next_token();
  7082. if (is_signless_integer(second_value)) {
  7083. int b = -second_value.token().to_integer();
  7084. transaction.commit();
  7085. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7086. }
  7087. return syntax_error();
  7088. }
  7089. // '+'?† <ndashdigit-ident>
  7090. if (is_ndashdigit_ident(first_after_plus)) {
  7091. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  7092. if (maybe_b.has_value()) {
  7093. transaction.commit();
  7094. return Selector::SimpleSelector::ANPlusBPattern { 1, maybe_b.value() };
  7095. }
  7096. return syntax_error();
  7097. }
  7098. return syntax_error();
  7099. }
  7100. class UnparsedCalculationNode final : public CalculationNode {
  7101. public:
  7102. static ErrorOr<NonnullOwnPtr<UnparsedCalculationNode>> create(ComponentValue component_value)
  7103. {
  7104. return adopt_nonnull_own_or_enomem(new (nothrow) UnparsedCalculationNode(move(component_value)));
  7105. }
  7106. virtual ~UnparsedCalculationNode() = default;
  7107. ComponentValue& component_value() { return m_component_value; }
  7108. virtual ErrorOr<String> to_string() const override { VERIFY_NOT_REACHED(); }
  7109. virtual Optional<CalculatedStyleValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  7110. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  7111. virtual CalculatedStyleValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  7112. virtual ErrorOr<void> dump(StringBuilder& builder, int indent) const override
  7113. {
  7114. return builder.try_appendff("{: >{}}UNPARSED({})\n", "", indent, TRY(m_component_value.to_debug_string()));
  7115. }
  7116. private:
  7117. UnparsedCalculationNode(ComponentValue component_value)
  7118. : CalculationNode(Type::Unparsed)
  7119. , m_component_value(move(component_value))
  7120. {
  7121. }
  7122. ComponentValue m_component_value;
  7123. };
  7124. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  7125. ErrorOr<OwnPtr<CalculationNode>> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  7126. {
  7127. // 1. Discard any <whitespace-token>s from values.
  7128. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  7129. struct Operator {
  7130. char delim;
  7131. };
  7132. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  7133. Vector<Value> values;
  7134. for (auto& value : original_values) {
  7135. if (value.is(Token::Type::Whitespace))
  7136. continue;
  7137. if (value.is(Token::Type::Delim)) {
  7138. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  7139. // NOTE: Sequential operators are invalid syntax.
  7140. if (!values.is_empty() && values.last().has<Operator>())
  7141. return nullptr;
  7142. TRY(values.try_append(Operator { static_cast<char>(value.token().delim()) }));
  7143. continue;
  7144. }
  7145. }
  7146. if (value.is(Token::Type::Number)) {
  7147. TRY(values.try_append({ TRY(NumericCalculationNode::create(value.token().number())) }));
  7148. continue;
  7149. }
  7150. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  7151. if (dimension->is_angle())
  7152. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->angle())) }));
  7153. else if (dimension->is_frequency())
  7154. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->frequency())) }));
  7155. else if (dimension->is_length())
  7156. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->length())) }));
  7157. else if (dimension->is_percentage())
  7158. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->percentage())) }));
  7159. // FIXME: Resolutions, once calc() supports them.
  7160. else if (dimension->is_time())
  7161. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->time())) }));
  7162. else
  7163. VERIFY_NOT_REACHED();
  7164. continue;
  7165. }
  7166. TRY(values.try_append({ TRY(UnparsedCalculationNode::create(value)) }));
  7167. }
  7168. // If we have no values, the syntax is invalid.
  7169. if (values.is_empty())
  7170. return nullptr;
  7171. // NOTE: If the first or last value is an operator, the syntax is invalid.
  7172. if (values.first().has<Operator>() || values.last().has<Operator>())
  7173. return nullptr;
  7174. // 3. Collect children into Product and Invert nodes.
  7175. // For every consecutive run of value items in values separated by "*" or "/" operators:
  7176. while (true) {
  7177. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  7178. return item.template has<Operator>()
  7179. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  7180. });
  7181. if (!first_product_operator.has_value())
  7182. break;
  7183. auto start_of_run = first_product_operator.value() - 1;
  7184. auto end_of_run = first_product_operator.value() + 1;
  7185. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  7186. auto& item = values[i];
  7187. if (!item.has<Operator>()) {
  7188. end_of_run = i - 1;
  7189. break;
  7190. }
  7191. auto delim = item.get<Operator>().delim;
  7192. if (!first_is_one_of(delim, '*', '/')) {
  7193. end_of_run = i - 1;
  7194. break;
  7195. }
  7196. }
  7197. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  7198. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  7199. TRY(run_values.try_append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>())));
  7200. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  7201. auto& operator_ = values[i].get<Operator>().delim;
  7202. auto& rhs = values[i + 1];
  7203. if (operator_ == '/') {
  7204. TRY(run_values.try_append(TRY(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())))));
  7205. continue;
  7206. }
  7207. VERIFY(operator_ == '*');
  7208. TRY(run_values.try_append(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7209. }
  7210. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  7211. auto product_node = TRY(ProductCalculationNode::create(move(run_values)));
  7212. values.remove(start_of_run, end_of_run - start_of_run + 1);
  7213. TRY(values.try_insert(start_of_run, { move(product_node) }));
  7214. }
  7215. // 4. Collect children into Sum and Negate nodes.
  7216. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  7217. {
  7218. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  7219. for (auto i = 0u; i < values.size(); ++i) {
  7220. auto& maybe_minus_operator = values[i];
  7221. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  7222. continue;
  7223. auto rhs_index = ++i;
  7224. auto& rhs = values[rhs_index];
  7225. NonnullOwnPtr<CalculationNode> negate_node = TRY(NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7226. values.remove(rhs_index);
  7227. values.insert(rhs_index, move(negate_node));
  7228. }
  7229. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  7230. if (values.size() == 1) {
  7231. TRY(values.first().visit(
  7232. [&](ComponentValue& component_value) -> ErrorOr<void> {
  7233. if (component_value.is_block() && component_value.block().is_paren())
  7234. single_value = TRY(UnparsedCalculationNode::create(component_value));
  7235. return {};
  7236. },
  7237. [&](NonnullOwnPtr<CalculationNode>& node) -> ErrorOr<void> {
  7238. if (node->type() == CalculationNode::Type::Product)
  7239. single_value = move(node);
  7240. return {};
  7241. },
  7242. [](auto&) -> ErrorOr<void> { return {}; }));
  7243. }
  7244. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  7245. if (!single_value.has_value()) {
  7246. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  7247. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  7248. TRY(value_items.try_ensure_capacity(values.size()));
  7249. for (auto& value : values) {
  7250. if (value.has<Operator>())
  7251. continue;
  7252. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  7253. }
  7254. single_value = TRY(SumCalculationNode::create(move(value_items)));
  7255. }
  7256. }
  7257. // 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.
  7258. // For every leaf node leaf in values:
  7259. bool parsing_failed_for_child_node = false;
  7260. TRY(single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) -> ErrorOr<void> {
  7261. if (node->type() != CalculationNode::Type::Unparsed)
  7262. return {};
  7263. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  7264. auto& component_value = unparsed_node.component_value();
  7265. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  7266. if (component_value.is_block() && component_value.block().is_paren()) {
  7267. auto leaf_calculation = TRY(parse_a_calculation(component_value.block().values()));
  7268. if (!leaf_calculation) {
  7269. parsing_failed_for_child_node = true;
  7270. return {};
  7271. }
  7272. node = leaf_calculation.release_nonnull();
  7273. return {};
  7274. }
  7275. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  7276. // NOTE: All function tokens at this point should be math functions.
  7277. else if (component_value.is_function()) {
  7278. auto& function = component_value.function();
  7279. auto leaf_calculation = TRY(parse_a_calc_function_node(function));
  7280. if (!leaf_calculation) {
  7281. parsing_failed_for_child_node = true;
  7282. return {};
  7283. }
  7284. node = leaf_calculation.release_nonnull();
  7285. return {};
  7286. }
  7287. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  7288. // So, the calc() is invalid.
  7289. 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());
  7290. parsing_failed_for_child_node = true;
  7291. return {};
  7292. }));
  7293. if (parsing_failed_for_child_node)
  7294. return nullptr;
  7295. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  7296. return single_value.release_value();
  7297. }
  7298. bool Parser::has_ignored_vendor_prefix(StringView string)
  7299. {
  7300. if (!string.starts_with('-'))
  7301. return false;
  7302. if (string.starts_with("--"sv))
  7303. return false;
  7304. if (string.starts_with("-libweb-"sv))
  7305. return false;
  7306. return true;
  7307. }
  7308. bool Parser::is_builtin(StringView name)
  7309. {
  7310. return name.equals_ignoring_ascii_case("inherit"sv)
  7311. || name.equals_ignoring_ascii_case("initial"sv)
  7312. || name.equals_ignoring_ascii_case("unset"sv);
  7313. }
  7314. ErrorOr<RefPtr<CalculatedStyleValue>> Parser::parse_calculated_value(Badge<StyleComputer>, ParsingContext const& context, Vector<ComponentValue> const& tokens)
  7315. {
  7316. if (tokens.is_empty())
  7317. return nullptr;
  7318. auto parser = TRY(Parser::create(context, ""sv));
  7319. return parser.parse_calculated_value(tokens);
  7320. }
  7321. ErrorOr<RefPtr<StyleValue>> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext const& context, PropertyID property_id, Vector<ComponentValue> const& tokens)
  7322. {
  7323. if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
  7324. return nullptr;
  7325. auto parser = TRY(Parser::create(context, ""sv));
  7326. TokenStream<ComponentValue> token_stream { tokens };
  7327. auto result = parser.parse_css_value(property_id, token_stream);
  7328. if (result.is_error())
  7329. return nullptr;
  7330. return result.release_value();
  7331. }
  7332. bool Parser::Dimension::is_angle() const
  7333. {
  7334. return m_value.has<Angle>();
  7335. }
  7336. Angle Parser::Dimension::angle() const
  7337. {
  7338. return m_value.get<Angle>();
  7339. }
  7340. bool Parser::Dimension::is_angle_percentage() const
  7341. {
  7342. return is_angle() || is_percentage();
  7343. }
  7344. AnglePercentage Parser::Dimension::angle_percentage() const
  7345. {
  7346. if (is_angle())
  7347. return angle();
  7348. if (is_percentage())
  7349. return percentage();
  7350. VERIFY_NOT_REACHED();
  7351. }
  7352. bool Parser::Dimension::is_frequency() const
  7353. {
  7354. return m_value.has<Frequency>();
  7355. }
  7356. Frequency Parser::Dimension::frequency() const
  7357. {
  7358. return m_value.get<Frequency>();
  7359. }
  7360. bool Parser::Dimension::is_frequency_percentage() const
  7361. {
  7362. return is_frequency() || is_percentage();
  7363. }
  7364. FrequencyPercentage Parser::Dimension::frequency_percentage() const
  7365. {
  7366. if (is_frequency())
  7367. return frequency();
  7368. if (is_percentage())
  7369. return percentage();
  7370. VERIFY_NOT_REACHED();
  7371. }
  7372. bool Parser::Dimension::is_length() const
  7373. {
  7374. return m_value.has<Length>();
  7375. }
  7376. Length Parser::Dimension::length() const
  7377. {
  7378. return m_value.get<Length>();
  7379. }
  7380. bool Parser::Dimension::is_length_percentage() const
  7381. {
  7382. return is_length() || is_percentage();
  7383. }
  7384. LengthPercentage Parser::Dimension::length_percentage() const
  7385. {
  7386. if (is_length())
  7387. return length();
  7388. if (is_percentage())
  7389. return percentage();
  7390. VERIFY_NOT_REACHED();
  7391. }
  7392. bool Parser::Dimension::is_percentage() const
  7393. {
  7394. return m_value.has<Percentage>();
  7395. }
  7396. Percentage Parser::Dimension::percentage() const
  7397. {
  7398. return m_value.get<Percentage>();
  7399. }
  7400. bool Parser::Dimension::is_resolution() const
  7401. {
  7402. return m_value.has<Resolution>();
  7403. }
  7404. Resolution Parser::Dimension::resolution() const
  7405. {
  7406. return m_value.get<Resolution>();
  7407. }
  7408. bool Parser::Dimension::is_time() const
  7409. {
  7410. return m_value.has<Time>();
  7411. }
  7412. Time Parser::Dimension::time() const
  7413. {
  7414. return m_value.get<Time>();
  7415. }
  7416. bool Parser::Dimension::is_time_percentage() const
  7417. {
  7418. return is_time() || is_percentage();
  7419. }
  7420. TimePercentage Parser::Dimension::time_percentage() const
  7421. {
  7422. if (is_time())
  7423. return time();
  7424. if (is_percentage())
  7425. return percentage();
  7426. VERIFY_NOT_REACHED();
  7427. }
  7428. }
  7429. namespace Web {
  7430. CSS::CSSStyleSheet* parse_css_stylesheet(CSS::Parser::ParsingContext const& context, StringView css, Optional<AK::URL> location)
  7431. {
  7432. if (css.is_empty()) {
  7433. auto rule_list = CSS::CSSRuleList::create_empty(context.realm()).release_value_but_fixme_should_propagate_errors();
  7434. auto media_list = CSS::MediaList::create(context.realm(), {}).release_value_but_fixme_should_propagate_errors();
  7435. return CSS::CSSStyleSheet::create(context.realm(), rule_list, media_list, location).release_value_but_fixme_should_propagate_errors();
  7436. }
  7437. auto parser = CSS::Parser::Parser::create(context, css).release_value_but_fixme_should_propagate_errors();
  7438. return parser.parse_as_css_stylesheet(location);
  7439. }
  7440. CSS::ElementInlineCSSStyleDeclaration* parse_css_style_attribute(CSS::Parser::ParsingContext const& context, StringView css, DOM::Element& element)
  7441. {
  7442. if (css.is_empty())
  7443. return CSS::ElementInlineCSSStyleDeclaration::create(element, {}, {}).release_value_but_fixme_should_propagate_errors();
  7444. auto parser = CSS::Parser::Parser::create(context, css).release_value_but_fixme_should_propagate_errors();
  7445. return parser.parse_as_style_attribute(element);
  7446. }
  7447. ErrorOr<RefPtr<CSS::StyleValue>> parse_css_value(CSS::Parser::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
  7448. {
  7449. if (string.is_empty())
  7450. return nullptr;
  7451. auto parser = TRY(CSS::Parser::Parser::create(context, string));
  7452. return parser.parse_as_css_value(property_id);
  7453. }
  7454. CSS::CSSRule* parse_css_rule(CSS::Parser::ParsingContext const& context, StringView css_text)
  7455. {
  7456. auto parser = CSS::Parser::Parser::create(context, css_text).release_value_but_fixme_should_propagate_errors();
  7457. return parser.parse_as_css_rule();
  7458. }
  7459. Optional<CSS::SelectorList> parse_selector(CSS::Parser::ParsingContext const& context, StringView selector_text)
  7460. {
  7461. auto parser = CSS::Parser::Parser::create(context, selector_text).release_value_but_fixme_should_propagate_errors();
  7462. return parser.parse_as_selector();
  7463. }
  7464. RefPtr<CSS::MediaQuery> parse_media_query(CSS::Parser::ParsingContext const& context, StringView string)
  7465. {
  7466. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7467. return parser.parse_as_media_query();
  7468. }
  7469. Vector<NonnullRefPtr<CSS::MediaQuery>> parse_media_query_list(CSS::Parser::ParsingContext const& context, StringView string)
  7470. {
  7471. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7472. return parser.parse_as_media_query_list();
  7473. }
  7474. RefPtr<CSS::Supports> parse_css_supports(CSS::Parser::ParsingContext const& context, StringView string)
  7475. {
  7476. if (string.is_empty())
  7477. return {};
  7478. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7479. return parser.parse_as_supports();
  7480. }
  7481. Optional<CSS::StyleProperty> parse_css_supports_condition(CSS::Parser::ParsingContext const& context, StringView string)
  7482. {
  7483. if (string.is_empty())
  7484. return {};
  7485. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7486. return parser.parse_as_supports_condition();
  7487. }
  7488. // https://html.spec.whatwg.org/multipage/images.html#parse-a-srcset-attribute
  7489. CSS::Length CSS::Parser::Parser::parse_as_sizes_attribute()
  7490. {
  7491. Optional<CSS::Length> size;
  7492. // When asked to parse a sizes attribute from an element,
  7493. // parse a comma-separated list of component values from the value of the element's sizes attribute
  7494. // (or the empty string, if the attribute is absent), and let unparsed sizes list be the result.
  7495. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  7496. // For each unparsed size in unparsed sizes list:
  7497. for (auto& unparsed_size : unparsed_sizes_list) {
  7498. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7499. // If unparsed size is now empty, that is a parse error; continue.
  7500. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  7501. unparsed_size.take_last();
  7502. if (unparsed_size.is_empty())
  7503. continue;
  7504. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  7505. // let size be its value and remove the component value from unparsed size.
  7506. // FIXME: Any CSS function other than the math functions is invalid.
  7507. // Otherwise, there is a parse error; continue.
  7508. auto length = parse_length(unparsed_size.last());
  7509. if (length.has_value() && length.value().raw_value() >= 0) {
  7510. size = length.value();
  7511. unparsed_size.take_last();
  7512. } else {
  7513. continue;
  7514. }
  7515. // 3. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7516. // If unparsed size is now empty, return size and exit this algorithm.
  7517. // If this was not the last item in unparsed sizes list, that is a parse error.
  7518. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  7519. unparsed_size.take_last();
  7520. if (unparsed_size.is_empty())
  7521. return size.value();
  7522. // 4. Parse the remaining component values in unparsed size as a <media-condition>.
  7523. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  7524. TokenStream<ComponentValue> token_stream { unparsed_size };
  7525. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  7526. if (media_condition && media_condition->evaluate(m_context.document()->window()) == CSS::MatchResult::True) {
  7527. return size.value();
  7528. } else {
  7529. continue;
  7530. }
  7531. }
  7532. return CSS::Length(100, CSS::Length::Type::Vw);
  7533. }
  7534. }