Parser.cpp 239 KB

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