Parser.cpp 232 KB

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