Parser.cpp 232 KB

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