Parser.cpp 231 KB

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