Parser.cpp 277 KB

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