Parser.cpp 364 KB

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