Parser.cpp 231 KB

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