Parser.cpp 341 KB

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