Parser.cpp 382 KB

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