Parser.cpp 337 KB

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