Parser.cpp 200 KB

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