Parser.cpp 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303
  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_rule()
  1594. {
  1595. return parse_a_rule(m_token_stream);
  1596. }
  1597. template<typename T>
  1598. RefPtr<CSSRule> Parser::parse_a_rule(TokenStream<T>& tokens)
  1599. {
  1600. RefPtr<CSSRule> rule;
  1601. tokens.skip_whitespace();
  1602. auto& token = tokens.peek_token();
  1603. if (token.is(Token::Type::EndOfFile)) {
  1604. return {};
  1605. } else if (token.is(Token::Type::AtKeyword)) {
  1606. auto at_rule = consume_an_at_rule(m_token_stream);
  1607. rule = convert_to_rule(at_rule);
  1608. } else {
  1609. auto qualified_rule = consume_a_qualified_rule(tokens);
  1610. if (!qualified_rule)
  1611. return {};
  1612. rule = convert_to_rule(*qualified_rule);
  1613. }
  1614. tokens.skip_whitespace();
  1615. auto& maybe_eof = tokens.peek_token();
  1616. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1617. return rule;
  1618. }
  1619. return {};
  1620. }
  1621. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  1622. {
  1623. return parse_a_list_of_rules(m_token_stream);
  1624. }
  1625. template<typename T>
  1626. NonnullRefPtrVector<CSSRule> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  1627. {
  1628. auto parsed_rules = consume_a_list_of_rules(tokens, TopLevel::No);
  1629. NonnullRefPtrVector<CSSRule> rules;
  1630. for (auto& rule : parsed_rules) {
  1631. auto converted_rule = convert_to_rule(rule);
  1632. if (converted_rule)
  1633. rules.append(*converted_rule);
  1634. }
  1635. return rules;
  1636. }
  1637. Optional<StyleProperty> Parser::parse_as_declaration()
  1638. {
  1639. return parse_a_declaration(m_token_stream);
  1640. }
  1641. template<typename T>
  1642. Optional<StyleProperty> Parser::parse_a_declaration(TokenStream<T>& tokens)
  1643. {
  1644. tokens.skip_whitespace();
  1645. auto& token = tokens.peek_token();
  1646. if (!token.is(Token::Type::Ident)) {
  1647. return {};
  1648. }
  1649. auto declaration = consume_a_declaration(tokens);
  1650. if (declaration.has_value())
  1651. return convert_to_style_property(declaration.value());
  1652. return {};
  1653. }
  1654. Vector<DeclarationOrAtRule> Parser::parse_as_list_of_declarations()
  1655. {
  1656. return parse_a_list_of_declarations(m_token_stream);
  1657. }
  1658. // 5.3.8. Parse a list of declarations
  1659. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-declarations
  1660. template<typename T>
  1661. Vector<DeclarationOrAtRule> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  1662. {
  1663. // To parse a list of declarations from input:
  1664. // 1. Normalize input, and set input to the result.
  1665. // 2. Consume a list of declarations from input, and return the result.
  1666. return consume_a_list_of_declarations(tokens);
  1667. }
  1668. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  1669. {
  1670. return parse_a_component_value(m_token_stream);
  1671. }
  1672. template<typename T>
  1673. Optional<StyleComponentValueRule> Parser::parse_a_component_value(TokenStream<T>& tokens)
  1674. {
  1675. tokens.skip_whitespace();
  1676. auto& token = tokens.peek_token();
  1677. if (token.is(Token::Type::EndOfFile)) {
  1678. return {};
  1679. }
  1680. auto value = consume_a_component_value(tokens);
  1681. tokens.skip_whitespace();
  1682. auto& maybe_eof = tokens.peek_token();
  1683. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1684. return value;
  1685. }
  1686. return {};
  1687. }
  1688. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  1689. {
  1690. return parse_a_list_of_component_values(m_token_stream);
  1691. }
  1692. template<typename T>
  1693. Vector<StyleComponentValueRule> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  1694. {
  1695. Vector<StyleComponentValueRule> rules;
  1696. for (;;) {
  1697. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1698. break;
  1699. }
  1700. rules.append(consume_a_component_value(tokens));
  1701. }
  1702. return rules;
  1703. }
  1704. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  1705. {
  1706. return parse_a_comma_separated_list_of_component_values(m_token_stream);
  1707. }
  1708. template<typename T>
  1709. Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  1710. {
  1711. Vector<Vector<StyleComponentValueRule>> lists;
  1712. lists.append({});
  1713. for (;;) {
  1714. auto& next = tokens.next_token();
  1715. if (next.is(Token::Type::Comma)) {
  1716. lists.append({});
  1717. continue;
  1718. } else if (next.is(Token::Type::EndOfFile)) {
  1719. break;
  1720. }
  1721. tokens.reconsume_current_input_token();
  1722. auto component_value = consume_a_component_value(tokens);
  1723. lists.last().append(component_value);
  1724. }
  1725. return lists;
  1726. }
  1727. RefPtr<ElementInlineCSSStyleDeclaration> Parser::parse_as_style_attribute(DOM::Element& element)
  1728. {
  1729. auto declarations_and_at_rules = parse_a_list_of_declarations(m_token_stream);
  1730. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  1731. return ElementInlineCSSStyleDeclaration::create(element, move(properties), move(custom_properties));
  1732. }
  1733. Optional<AK::URL> Parser::parse_url_function(StyleComponentValueRule const& component_value, AllowedDataUrlType allowed_data_url_type)
  1734. {
  1735. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1736. // FIXME: Handle data: urls (RFC2397)
  1737. auto convert_string_to_url = [&](StringView& url_string) -> Optional<AK::URL> {
  1738. if (url_string.starts_with("data:", CaseSensitivity::CaseInsensitive)) {
  1739. auto data_url = AK::URL(url_string);
  1740. switch (allowed_data_url_type) {
  1741. case AllowedDataUrlType::Image:
  1742. if (data_url.data_mime_type().starts_with("image"sv, CaseSensitivity::CaseInsensitive))
  1743. return data_url;
  1744. break;
  1745. default:
  1746. break;
  1747. }
  1748. return {};
  1749. }
  1750. return m_context.complete_url(url_string);
  1751. };
  1752. if (component_value.is(Token::Type::Url)) {
  1753. auto url_string = component_value.token().url();
  1754. return convert_string_to_url(url_string);
  1755. }
  1756. if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) {
  1757. auto& function_values = component_value.function().values();
  1758. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  1759. for (size_t i = 0; i < function_values.size(); ++i) {
  1760. auto& value = function_values[i];
  1761. if (value.is(Token::Type::Whitespace))
  1762. continue;
  1763. if (value.is(Token::Type::String)) {
  1764. auto url_string = value.token().string();
  1765. return convert_string_to_url(url_string);
  1766. }
  1767. break;
  1768. }
  1769. }
  1770. return {};
  1771. }
  1772. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  1773. {
  1774. if (rule->m_type == StyleRule::Type::At) {
  1775. if (has_ignored_vendor_prefix(rule->m_name)) {
  1776. return {};
  1777. } else if (rule->m_name.equals_ignoring_case("font-face"sv)) {
  1778. if (rule->prelude().is_empty() || !rule->block()->is_curly()) {
  1779. dbgln_if(CSS_PARSER_DEBUG, "@font-face rule is malformed.");
  1780. return {};
  1781. }
  1782. TokenStream tokens { rule->block()->values() };
  1783. return parse_font_face_rule(tokens);
  1784. } else if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  1785. Optional<AK::URL> url;
  1786. for (auto& token : rule->prelude()) {
  1787. if (token.is(Token::Type::Whitespace))
  1788. continue;
  1789. if (token.is(Token::Type::String)) {
  1790. url = m_context.complete_url(token.token().string());
  1791. } else {
  1792. url = parse_url_function(token);
  1793. }
  1794. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1795. if (url.has_value())
  1796. break;
  1797. }
  1798. if (url.has_value())
  1799. return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document()));
  1800. else
  1801. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse url from @import rule");
  1802. } else if (rule->m_name.equals_ignoring_case("media"sv)) {
  1803. auto media_query_tokens = TokenStream { rule->prelude() };
  1804. auto media_query_list = parse_a_media_query_list(media_query_tokens);
  1805. if (media_query_list.is_empty() || !rule->block())
  1806. return {};
  1807. auto child_tokens = TokenStream { rule->block()->values() };
  1808. auto parser_rules = consume_a_list_of_rules(child_tokens, TopLevel::No);
  1809. NonnullRefPtrVector<CSSRule> child_rules;
  1810. for (auto& raw_rule : parser_rules) {
  1811. if (auto child_rule = convert_to_rule(raw_rule))
  1812. child_rules.append(*child_rule);
  1813. }
  1814. return CSSMediaRule::create(MediaList::create(move(media_query_list)), move(child_rules));
  1815. } else if (rule->m_name.equals_ignoring_case("supports"sv)) {
  1816. auto supports_tokens = TokenStream { rule->prelude() };
  1817. auto supports = parse_a_supports(supports_tokens);
  1818. if (!supports) {
  1819. if constexpr (CSS_PARSER_DEBUG) {
  1820. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @supports rule invalid; discarding.");
  1821. supports_tokens.dump_all_tokens();
  1822. }
  1823. return {};
  1824. }
  1825. if (!rule->block())
  1826. return {};
  1827. auto child_tokens = TokenStream { rule->block()->values() };
  1828. auto parser_rules = consume_a_list_of_rules(child_tokens, TopLevel::No);
  1829. NonnullRefPtrVector<CSSRule> child_rules;
  1830. for (auto& raw_rule : parser_rules) {
  1831. if (auto child_rule = convert_to_rule(raw_rule))
  1832. child_rules.append(*child_rule);
  1833. }
  1834. return CSSSupportsRule::create(supports.release_nonnull(), move(child_rules));
  1835. } else {
  1836. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS at-rule: @{}", rule->m_name);
  1837. }
  1838. // FIXME: More at rules!
  1839. } else {
  1840. auto prelude_stream = TokenStream(rule->m_prelude);
  1841. auto selectors = parse_a_selector_list(prelude_stream, SelectorType::Standalone);
  1842. if (selectors.is_error()) {
  1843. if (selectors.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1844. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule selectors invalid; discarding.");
  1845. if constexpr (CSS_PARSER_DEBUG) {
  1846. prelude_stream.dump_all_tokens();
  1847. }
  1848. }
  1849. return {};
  1850. }
  1851. if (selectors.value().is_empty()) {
  1852. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: empty selector; discarding.");
  1853. return {};
  1854. }
  1855. if (!rule->block()->is_curly())
  1856. return {};
  1857. auto stream = TokenStream(rule->block()->values());
  1858. auto declarations_and_at_rules = parse_a_list_of_declarations(stream);
  1859. auto declaration = convert_to_style_declaration(declarations_and_at_rules);
  1860. if (!declaration) {
  1861. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule declaration invalid; discarding.");
  1862. return {};
  1863. }
  1864. return CSSStyleRule::create(move(selectors.value()), move(*declaration));
  1865. }
  1866. return {};
  1867. }
  1868. auto Parser::extract_properties(Vector<DeclarationOrAtRule> const& declarations_and_at_rules) -> PropertiesAndCustomProperties
  1869. {
  1870. PropertiesAndCustomProperties result;
  1871. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  1872. if (declaration_or_at_rule.is_at_rule()) {
  1873. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  1874. continue;
  1875. }
  1876. auto const& declaration = declaration_or_at_rule.declaration();
  1877. if (auto maybe_property = convert_to_style_property(declaration); maybe_property.has_value()) {
  1878. auto property = maybe_property.release_value();
  1879. if (property.property_id == PropertyID::Custom) {
  1880. result.custom_properties.set(property.custom_name, property);
  1881. } else {
  1882. result.properties.append(move(property));
  1883. }
  1884. }
  1885. }
  1886. return result;
  1887. }
  1888. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::convert_to_style_declaration(Vector<DeclarationOrAtRule> declarations_and_at_rules)
  1889. {
  1890. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  1891. return PropertyOwningCSSStyleDeclaration::create(move(properties), move(custom_properties));
  1892. }
  1893. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule const& declaration)
  1894. {
  1895. auto& property_name = declaration.m_name;
  1896. auto property_id = property_id_from_string(property_name);
  1897. if (property_id == PropertyID::Invalid) {
  1898. if (property_name.starts_with("--")) {
  1899. property_id = PropertyID::Custom;
  1900. } else if (has_ignored_vendor_prefix(property_name)) {
  1901. return {};
  1902. } else if (!property_name.starts_with("-")) {
  1903. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS property '{}'", property_name);
  1904. return {};
  1905. }
  1906. }
  1907. auto value_token_stream = TokenStream(declaration.m_values);
  1908. auto value = parse_css_value(property_id, value_token_stream);
  1909. if (value.is_error()) {
  1910. if (value.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1911. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse value for CSS property '{}'.", property_name);
  1912. if constexpr (CSS_PARSER_DEBUG) {
  1913. value_token_stream.dump_all_tokens();
  1914. }
  1915. }
  1916. return {};
  1917. }
  1918. if (property_id == PropertyID::Custom) {
  1919. return StyleProperty { declaration.m_important, property_id, value.release_value(), declaration.m_name };
  1920. } else {
  1921. return StyleProperty { declaration.m_important, property_id, value.release_value(), {} };
  1922. }
  1923. }
  1924. RefPtr<StyleValue> Parser::parse_builtin_value(StyleComponentValueRule const& component_value)
  1925. {
  1926. if (component_value.is(Token::Type::Ident)) {
  1927. auto ident = component_value.token().ident();
  1928. if (ident.equals_ignoring_case("inherit"))
  1929. return InheritStyleValue::the();
  1930. if (ident.equals_ignoring_case("initial"))
  1931. return InitialStyleValue::the();
  1932. if (ident.equals_ignoring_case("unset"))
  1933. return UnsetStyleValue::the();
  1934. // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
  1935. }
  1936. return {};
  1937. }
  1938. RefPtr<StyleValue> Parser::parse_calculated_value(Vector<StyleComponentValueRule> const& component_values)
  1939. {
  1940. auto calc_expression = parse_calc_expression(component_values);
  1941. if (calc_expression == nullptr)
  1942. return nullptr;
  1943. auto calc_type = calc_expression->resolved_type();
  1944. if (!calc_type.has_value()) {
  1945. dbgln_if(CSS_PARSER_DEBUG, "calc() resolved as invalid!!!");
  1946. return nullptr;
  1947. }
  1948. [[maybe_unused]] auto to_string = [](CalculatedStyleValue::ResolvedType type) {
  1949. switch (type) {
  1950. case CalculatedStyleValue::ResolvedType::Angle:
  1951. return "Angle"sv;
  1952. case CalculatedStyleValue::ResolvedType::Frequency:
  1953. return "Frequency"sv;
  1954. case CalculatedStyleValue::ResolvedType::Integer:
  1955. return "Integer"sv;
  1956. case CalculatedStyleValue::ResolvedType::Length:
  1957. return "Length"sv;
  1958. case CalculatedStyleValue::ResolvedType::Number:
  1959. return "Number"sv;
  1960. case CalculatedStyleValue::ResolvedType::Percentage:
  1961. return "Percentage"sv;
  1962. case CalculatedStyleValue::ResolvedType::Time:
  1963. return "Time"sv;
  1964. }
  1965. VERIFY_NOT_REACHED();
  1966. };
  1967. dbgln_if(CSS_PARSER_DEBUG, "Deduced calc() resolved type as: {}", to_string(calc_type.value()));
  1968. return CalculatedStyleValue::create(calc_expression.release_nonnull(), calc_type.release_value());
  1969. }
  1970. RefPtr<StyleValue> Parser::parse_dynamic_value(StyleComponentValueRule const& component_value)
  1971. {
  1972. if (component_value.is_function()) {
  1973. auto& function = component_value.function();
  1974. if (function.name().equals_ignoring_case("calc"))
  1975. return parse_calculated_value(function.values());
  1976. if (function.name().equals_ignoring_case("var")) {
  1977. // Declarations using `var()` should already be parsed as an UnresolvedStyleValue before this point.
  1978. VERIFY_NOT_REACHED();
  1979. }
  1980. }
  1981. return {};
  1982. }
  1983. Optional<Parser::Dimension> Parser::parse_dimension(StyleComponentValueRule const& component_value)
  1984. {
  1985. if (component_value.is(Token::Type::Dimension)) {
  1986. float numeric_value = component_value.token().dimension_value();
  1987. auto unit_string = component_value.token().dimension_unit();
  1988. if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
  1989. return Length { numeric_value, length_type.release_value() };
  1990. if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
  1991. return Angle { numeric_value, angle_type.release_value() };
  1992. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  1993. return Frequency { numeric_value, frequency_type.release_value() };
  1994. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  1995. return Resolution { numeric_value, resolution_type.release_value() };
  1996. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  1997. return Time { numeric_value, time_type.release_value() };
  1998. }
  1999. if (component_value.is(Token::Type::Percentage))
  2000. return Percentage { static_cast<float>(component_value.token().percentage()) };
  2001. if (component_value.is(Token::Type::Number)) {
  2002. float numeric_value = component_value.token().number_value();
  2003. if (numeric_value == 0)
  2004. return Length::make_px(0);
  2005. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  2006. // https://quirks.spec.whatwg.org/#quirky-length-value
  2007. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  2008. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  2009. // expression, and must not be supported in the supports() static method of the CSS interface."
  2010. return Length::make_px(numeric_value);
  2011. }
  2012. }
  2013. return {};
  2014. }
  2015. Optional<Length> Parser::parse_length(StyleComponentValueRule const& component_value)
  2016. {
  2017. auto dimension = parse_dimension(component_value);
  2018. if (!dimension.has_value())
  2019. return {};
  2020. if (dimension->is_length())
  2021. return dimension->length();
  2022. // FIXME: auto isn't a length!
  2023. if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"))
  2024. return Length::make_auto();
  2025. return {};
  2026. }
  2027. Optional<Ratio> Parser::parse_ratio(TokenStream<StyleComponentValueRule>& tokens)
  2028. {
  2029. auto position = tokens.position();
  2030. tokens.skip_whitespace();
  2031. auto error = [&]() -> Optional<Ratio> {
  2032. tokens.rewind_to_position(position);
  2033. return {};
  2034. };
  2035. // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
  2036. // FIXME: I think either part is allowed to be calc(), which makes everything complicated.
  2037. auto first_number = tokens.next_token();
  2038. if (!first_number.is(Token::Type::Number) || first_number.token().number_value() < 0)
  2039. return error();
  2040. auto position_after_first_number = tokens.position();
  2041. tokens.skip_whitespace();
  2042. auto solidus = tokens.next_token();
  2043. tokens.skip_whitespace();
  2044. auto second_number = tokens.next_token();
  2045. if (solidus.is(Token::Type::Delim) && solidus.token().delim() == '/'
  2046. && second_number.is(Token::Type::Number) && second_number.token().number_value() > 0) {
  2047. // Two-value ratio
  2048. return Ratio { static_cast<float>(first_number.token().number_value()), static_cast<float>(second_number.token().number_value()) };
  2049. }
  2050. // Single-value ratio
  2051. tokens.rewind_to_position(position_after_first_number);
  2052. return Ratio { static_cast<float>(first_number.token().number_value()) };
  2053. }
  2054. RefPtr<StyleValue> Parser::parse_dimension_value(StyleComponentValueRule const& component_value)
  2055. {
  2056. // Numbers with no units can be lengths, in two situations:
  2057. // 1) We're in quirks mode, and it's an integer.
  2058. // 2) It's a 0.
  2059. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  2060. if (component_value.is(Token::Type::Number) && !(m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)))
  2061. return {};
  2062. if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"))
  2063. return LengthStyleValue::create(Length::make_auto());
  2064. auto dimension = parse_dimension(component_value);
  2065. if (!dimension.has_value())
  2066. return {};
  2067. if (dimension->is_angle())
  2068. return AngleStyleValue::create(dimension->angle());
  2069. if (dimension->is_frequency())
  2070. return FrequencyStyleValue::create(dimension->frequency());
  2071. if (dimension->is_length())
  2072. return LengthStyleValue::create(dimension->length());
  2073. if (dimension->is_percentage())
  2074. return PercentageStyleValue::create(dimension->percentage());
  2075. if (dimension->is_resolution())
  2076. return ResolutionStyleValue::create(dimension->resolution());
  2077. if (dimension->is_time())
  2078. return TimeStyleValue::create(dimension->time());
  2079. VERIFY_NOT_REACHED();
  2080. }
  2081. RefPtr<StyleValue> Parser::parse_numeric_value(StyleComponentValueRule const& component_value)
  2082. {
  2083. if (component_value.is(Token::Type::Number)) {
  2084. auto number = component_value.token();
  2085. if (number.number().is_integer()) {
  2086. return NumericStyleValue::create_integer(number.to_integer());
  2087. } else {
  2088. return NumericStyleValue::create_float(number.number_value());
  2089. }
  2090. }
  2091. return {};
  2092. }
  2093. RefPtr<StyleValue> Parser::parse_identifier_value(StyleComponentValueRule const& component_value)
  2094. {
  2095. if (component_value.is(Token::Type::Ident)) {
  2096. auto value_id = value_id_from_string(component_value.token().ident());
  2097. if (value_id != ValueID::Invalid)
  2098. return IdentifierStyleValue::create(value_id);
  2099. }
  2100. return {};
  2101. }
  2102. Optional<Color> Parser::parse_color(StyleComponentValueRule const& component_value)
  2103. {
  2104. // https://www.w3.org/TR/css-color-3/
  2105. if (component_value.is(Token::Type::Ident)) {
  2106. auto ident = component_value.token().ident();
  2107. auto color = Color::from_string(ident);
  2108. if (color.has_value())
  2109. return color;
  2110. } else if (component_value.is(Token::Type::Hash)) {
  2111. auto color = Color::from_string(String::formatted("#{}", component_value.token().hash_value()));
  2112. if (color.has_value())
  2113. return color;
  2114. return {};
  2115. } else if (component_value.is_function()) {
  2116. auto& function = component_value.function();
  2117. auto& values = function.values();
  2118. Vector<Token> params;
  2119. for (size_t i = 0; i < values.size(); ++i) {
  2120. auto& value = values.at(i);
  2121. if (value.is(Token::Type::Whitespace))
  2122. continue;
  2123. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  2124. params.append(value.token());
  2125. // Eat following comma and whitespace
  2126. while ((i + 1) < values.size()) {
  2127. auto& next = values.at(i + 1);
  2128. if (next.is(Token::Type::Whitespace))
  2129. i++;
  2130. else if (next.is(Token::Type::Comma))
  2131. break;
  2132. return {};
  2133. }
  2134. }
  2135. }
  2136. if (function.name().equals_ignoring_case("rgb")) {
  2137. if (params.size() != 3)
  2138. return {};
  2139. auto r_val = params[0];
  2140. auto g_val = params[1];
  2141. auto b_val = params[2];
  2142. if (r_val.is(Token::Type::Number) && r_val.number().is_integer()
  2143. && g_val.is(Token::Type::Number) && g_val.number().is_integer()
  2144. && b_val.is(Token::Type::Number) && b_val.number().is_integer()) {
  2145. auto r = r_val.to_integer();
  2146. auto g = g_val.to_integer();
  2147. auto b = b_val.to_integer();
  2148. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  2149. return Color(r, g, b);
  2150. } else if (r_val.is(Token::Type::Percentage)
  2151. && g_val.is(Token::Type::Percentage)
  2152. && b_val.is(Token::Type::Percentage)) {
  2153. u8 r = clamp(lroundf(r_val.percentage() * 2.55f), 0, 255);
  2154. u8 g = clamp(lroundf(g_val.percentage() * 2.55f), 0, 255);
  2155. u8 b = clamp(lroundf(b_val.percentage() * 2.55f), 0, 255);
  2156. return Color(r, g, b);
  2157. }
  2158. } else if (function.name().equals_ignoring_case("rgba")) {
  2159. if (params.size() != 4)
  2160. return {};
  2161. auto r_val = params[0];
  2162. auto g_val = params[1];
  2163. auto b_val = params[2];
  2164. auto a_val = params[3];
  2165. if (r_val.is(Token::Type::Number) && r_val.number().is_integer()
  2166. && g_val.is(Token::Type::Number) && g_val.number().is_integer()
  2167. && b_val.is(Token::Type::Number) && b_val.number().is_integer()
  2168. && a_val.is(Token::Type::Number)) {
  2169. auto r = r_val.to_integer();
  2170. auto g = g_val.to_integer();
  2171. auto b = b_val.to_integer();
  2172. auto a = clamp(lroundf(a_val.number_value() * 255.0f), 0, 255);
  2173. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  2174. return Color(r, g, b, a);
  2175. } else if (r_val.is(Token::Type::Percentage)
  2176. && g_val.is(Token::Type::Percentage)
  2177. && b_val.is(Token::Type::Percentage)
  2178. && a_val.is(Token::Type::Number)) {
  2179. auto r = r_val.percentage();
  2180. auto g = g_val.percentage();
  2181. auto b = b_val.percentage();
  2182. auto a = a_val.number_value();
  2183. u8 r_255 = clamp(lroundf(r * 2.55f), 0, 255);
  2184. u8 g_255 = clamp(lroundf(g * 2.55f), 0, 255);
  2185. u8 b_255 = clamp(lroundf(b * 2.55f), 0, 255);
  2186. u8 a_255 = clamp(lroundf(a * 255.0f), 0, 255);
  2187. return Color(r_255, g_255, b_255, a_255);
  2188. }
  2189. } else if (function.name().equals_ignoring_case("hsl")) {
  2190. if (params.size() != 3)
  2191. return {};
  2192. auto h_val = params[0];
  2193. auto s_val = params[1];
  2194. auto l_val = params[2];
  2195. if (h_val.is(Token::Type::Number)
  2196. && s_val.is(Token::Type::Percentage)
  2197. && l_val.is(Token::Type::Percentage)) {
  2198. auto h = h_val.number_value();
  2199. auto s = s_val.percentage() / 100.0f;
  2200. auto l = l_val.percentage() / 100.0f;
  2201. return Color::from_hsl(h, s, l);
  2202. }
  2203. } else if (function.name().equals_ignoring_case("hsla")) {
  2204. if (params.size() != 4)
  2205. return {};
  2206. auto h_val = params[0];
  2207. auto s_val = params[1];
  2208. auto l_val = params[2];
  2209. auto a_val = params[3];
  2210. if (h_val.is(Token::Type::Number)
  2211. && s_val.is(Token::Type::Percentage)
  2212. && l_val.is(Token::Type::Percentage)
  2213. && a_val.is(Token::Type::Number)) {
  2214. auto h = h_val.number_value();
  2215. auto s = s_val.percentage() / 100.0f;
  2216. auto l = l_val.percentage() / 100.0f;
  2217. auto a = a_val.number_value();
  2218. return Color::from_hsla(h, s, l, a);
  2219. }
  2220. }
  2221. return {};
  2222. }
  2223. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  2224. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  2225. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  2226. // aborting on the first step that returns a value:
  2227. // 1. Let cv be the component value.
  2228. auto& cv = component_value;
  2229. String serialization;
  2230. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  2231. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  2232. // 1. If cv’s type flag is not "integer", return an error.
  2233. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  2234. if (!cv.token().number().is_integer())
  2235. return {};
  2236. // 2. If cv’s value is less than zero, return an error.
  2237. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  2238. if (value < 0)
  2239. return {};
  2240. // 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.
  2241. StringBuilder serialization_builder;
  2242. serialization_builder.appendff("{}", value);
  2243. // 4. If cv is a <dimension-token>, append the unit to serialization.
  2244. if (cv.is(Token::Type::Dimension))
  2245. serialization_builder.append(cv.token().dimension_unit());
  2246. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  2247. serialization = serialization_builder.to_string();
  2248. if (serialization_builder.length() < 6) {
  2249. StringBuilder builder;
  2250. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  2251. builder.append('0');
  2252. builder.append(serialization_builder.string_view());
  2253. serialization = builder.to_string();
  2254. }
  2255. }
  2256. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  2257. else {
  2258. if (!cv.is(Token::Type::Ident))
  2259. return {};
  2260. serialization = cv.token().ident();
  2261. }
  2262. // 4. If serialization does not consist of three or six characters, return an error.
  2263. if (serialization.length() != 3 && serialization.length() != 6)
  2264. return {};
  2265. // 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.
  2266. for (auto c : serialization) {
  2267. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  2268. return {};
  2269. }
  2270. // 6. Return the concatenation of "#" (U+0023) and serialization.
  2271. String concatenation = String::formatted("#{}", serialization);
  2272. return Color::from_string(concatenation);
  2273. }
  2274. return {};
  2275. }
  2276. RefPtr<StyleValue> Parser::parse_color_value(StyleComponentValueRule const& component_value)
  2277. {
  2278. auto color = parse_color(component_value);
  2279. if (color.has_value())
  2280. return ColorStyleValue::create(color.value());
  2281. return {};
  2282. }
  2283. RefPtr<StyleValue> Parser::parse_string_value(StyleComponentValueRule const& component_value)
  2284. {
  2285. if (component_value.is(Token::Type::String))
  2286. return StringStyleValue::create(component_value.token().string());
  2287. return {};
  2288. }
  2289. RefPtr<StyleValue> Parser::parse_image_value(StyleComponentValueRule const& component_value)
  2290. {
  2291. auto url = parse_url_function(component_value, AllowedDataUrlType::Image);
  2292. if (url.has_value())
  2293. return ImageStyleValue::create(url.value());
  2294. // FIXME: Handle gradients.
  2295. return {};
  2296. }
  2297. template<typename ParseFunction>
  2298. RefPtr<StyleValue> Parser::parse_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values, ParseFunction parse_one_value)
  2299. {
  2300. auto tokens = TokenStream { component_values };
  2301. auto first = parse_one_value(tokens);
  2302. if (!first || !tokens.has_next_token())
  2303. return first;
  2304. NonnullRefPtrVector<StyleValue> values;
  2305. values.append(first.release_nonnull());
  2306. while (tokens.has_next_token()) {
  2307. if (!tokens.next_token().is(Token::Type::Comma))
  2308. return {};
  2309. if (auto maybe_value = parse_one_value(tokens)) {
  2310. values.append(maybe_value.release_nonnull());
  2311. continue;
  2312. }
  2313. return {};
  2314. }
  2315. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  2316. }
  2317. RefPtr<StyleValue> Parser::parse_simple_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values)
  2318. {
  2319. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> RefPtr<StyleValue> {
  2320. auto& token = tokens.next_token();
  2321. if (auto value = parse_css_value(token); value && property_accepts_value(m_context.current_property_id(), *value))
  2322. return value;
  2323. tokens.reconsume_current_input_token();
  2324. return nullptr;
  2325. });
  2326. }
  2327. RefPtr<StyleValue> Parser::parse_background_value(Vector<StyleComponentValueRule> const& component_values)
  2328. {
  2329. NonnullRefPtrVector<StyleValue> background_images;
  2330. NonnullRefPtrVector<StyleValue> background_positions;
  2331. NonnullRefPtrVector<StyleValue> background_sizes;
  2332. NonnullRefPtrVector<StyleValue> background_repeats;
  2333. NonnullRefPtrVector<StyleValue> background_attachments;
  2334. NonnullRefPtrVector<StyleValue> background_clips;
  2335. NonnullRefPtrVector<StyleValue> background_origins;
  2336. RefPtr<StyleValue> background_color;
  2337. // Per-layer values
  2338. RefPtr<StyleValue> background_image;
  2339. RefPtr<StyleValue> background_position;
  2340. RefPtr<StyleValue> background_size;
  2341. RefPtr<StyleValue> background_repeat;
  2342. RefPtr<StyleValue> background_attachment;
  2343. RefPtr<StyleValue> background_clip;
  2344. RefPtr<StyleValue> background_origin;
  2345. bool has_multiple_layers = false;
  2346. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  2347. if (allow_background_color) {
  2348. if (background_color)
  2349. return true;
  2350. } else {
  2351. if (background_color)
  2352. return false;
  2353. }
  2354. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  2355. };
  2356. auto complete_background_layer = [&]() {
  2357. background_images.append(background_image ? background_image.release_nonnull() : property_initial_value(PropertyID::BackgroundImage));
  2358. background_positions.append(background_position ? background_position.release_nonnull() : property_initial_value(PropertyID::BackgroundPosition));
  2359. background_sizes.append(background_size ? background_size.release_nonnull() : property_initial_value(PropertyID::BackgroundSize));
  2360. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : property_initial_value(PropertyID::BackgroundRepeat));
  2361. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : property_initial_value(PropertyID::BackgroundAttachment));
  2362. if (!background_origin && !background_clip) {
  2363. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  2364. background_clip = property_initial_value(PropertyID::BackgroundClip);
  2365. } else if (!background_clip) {
  2366. background_clip = background_origin;
  2367. }
  2368. background_origins.append(background_origin.release_nonnull());
  2369. background_clips.append(background_clip.release_nonnull());
  2370. background_image = nullptr;
  2371. background_position = nullptr;
  2372. background_size = nullptr;
  2373. background_repeat = nullptr;
  2374. background_attachment = nullptr;
  2375. background_clip = nullptr;
  2376. background_origin = nullptr;
  2377. };
  2378. auto tokens = TokenStream { component_values };
  2379. while (tokens.has_next_token()) {
  2380. auto& part = tokens.next_token();
  2381. if (part.is(Token::Type::Comma)) {
  2382. has_multiple_layers = true;
  2383. if (!background_layer_is_valid(false))
  2384. return nullptr;
  2385. complete_background_layer();
  2386. continue;
  2387. }
  2388. auto value = parse_css_value(part);
  2389. if (!value)
  2390. return nullptr;
  2391. if (property_accepts_value(PropertyID::BackgroundAttachment, *value)) {
  2392. if (background_attachment)
  2393. return nullptr;
  2394. background_attachment = value.release_nonnull();
  2395. continue;
  2396. }
  2397. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  2398. if (background_color)
  2399. return nullptr;
  2400. background_color = value.release_nonnull();
  2401. continue;
  2402. }
  2403. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  2404. if (background_image)
  2405. return nullptr;
  2406. background_image = value.release_nonnull();
  2407. continue;
  2408. }
  2409. if (property_accepts_value(PropertyID::BackgroundOrigin, *value)) {
  2410. // background-origin and background-clip accept the same values. From the spec:
  2411. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  2412. // If two values are present, then the first sets background-origin and the second background-clip."
  2413. // - https://www.w3.org/TR/css-backgrounds-3/#background
  2414. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  2415. // If we only get one, we copy the value before creating the BackgroundStyleValue.
  2416. if (!background_origin) {
  2417. background_origin = value.release_nonnull();
  2418. continue;
  2419. }
  2420. if (!background_clip) {
  2421. background_clip = value.release_nonnull();
  2422. continue;
  2423. }
  2424. return nullptr;
  2425. }
  2426. if (property_accepts_value(PropertyID::BackgroundPosition, *value)) {
  2427. if (background_position)
  2428. return nullptr;
  2429. tokens.reconsume_current_input_token();
  2430. if (auto maybe_background_position = parse_single_background_position_value(tokens)) {
  2431. background_position = maybe_background_position.release_nonnull();
  2432. // Attempt to parse `/ <background-size>`
  2433. auto before_slash = tokens.position();
  2434. auto& maybe_slash = tokens.next_token();
  2435. if (maybe_slash.is(Token::Type::Delim) && maybe_slash.token().delim() == '/') {
  2436. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  2437. background_size = maybe_background_size.release_nonnull();
  2438. continue;
  2439. }
  2440. return nullptr;
  2441. }
  2442. tokens.rewind_to_position(before_slash);
  2443. continue;
  2444. }
  2445. return nullptr;
  2446. }
  2447. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  2448. if (background_repeat)
  2449. return nullptr;
  2450. tokens.reconsume_current_input_token();
  2451. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  2452. background_repeat = maybe_repeat.release_nonnull();
  2453. continue;
  2454. }
  2455. return nullptr;
  2456. }
  2457. return nullptr;
  2458. }
  2459. if (!background_layer_is_valid(true))
  2460. return nullptr;
  2461. // We only need to create StyleValueLists if there are multiple layers.
  2462. // Otherwise, we can pass the single StyleValues directly.
  2463. if (has_multiple_layers) {
  2464. complete_background_layer();
  2465. if (!background_color)
  2466. background_color = property_initial_value(PropertyID::BackgroundColor);
  2467. return BackgroundStyleValue::create(
  2468. background_color.release_nonnull(),
  2469. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  2470. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  2471. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  2472. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  2473. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  2474. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  2475. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  2476. }
  2477. if (!background_color)
  2478. background_color = property_initial_value(PropertyID::BackgroundColor);
  2479. if (!background_image)
  2480. background_image = property_initial_value(PropertyID::BackgroundImage);
  2481. if (!background_position)
  2482. background_position = property_initial_value(PropertyID::BackgroundPosition);
  2483. if (!background_size)
  2484. background_size = property_initial_value(PropertyID::BackgroundSize);
  2485. if (!background_repeat)
  2486. background_repeat = property_initial_value(PropertyID::BackgroundRepeat);
  2487. if (!background_attachment)
  2488. background_attachment = property_initial_value(PropertyID::BackgroundAttachment);
  2489. if (!background_origin && !background_clip) {
  2490. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  2491. background_clip = property_initial_value(PropertyID::BackgroundClip);
  2492. } else if (!background_clip) {
  2493. background_clip = background_origin;
  2494. }
  2495. return BackgroundStyleValue::create(
  2496. background_color.release_nonnull(),
  2497. background_image.release_nonnull(),
  2498. background_position.release_nonnull(),
  2499. background_size.release_nonnull(),
  2500. background_repeat.release_nonnull(),
  2501. background_attachment.release_nonnull(),
  2502. background_origin.release_nonnull(),
  2503. background_clip.release_nonnull());
  2504. }
  2505. RefPtr<StyleValue> Parser::parse_single_background_position_value(TokenStream<StyleComponentValueRule>& tokens)
  2506. {
  2507. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  2508. // "Note: The background-position property also accepts a three-value syntax.
  2509. // This has been disallowed generically because it creates parsing ambiguities
  2510. // when combined with other length or percentage components in a property value."
  2511. // - https://www.w3.org/TR/css-values-4/#typedef-position
  2512. // So, we'll need a separate function to parse <position> later.
  2513. auto start_position = tokens.position();
  2514. auto error = [&]() {
  2515. tokens.rewind_to_position(start_position);
  2516. return nullptr;
  2517. };
  2518. auto to_edge = [](ValueID identifier) -> Optional<PositionEdge> {
  2519. switch (identifier) {
  2520. case ValueID::Top:
  2521. return PositionEdge::Top;
  2522. case ValueID::Bottom:
  2523. return PositionEdge::Bottom;
  2524. case ValueID::Left:
  2525. return PositionEdge::Left;
  2526. case ValueID::Right:
  2527. return PositionEdge::Right;
  2528. default:
  2529. return {};
  2530. }
  2531. };
  2532. auto is_horizontal = [](ValueID identifier) -> bool {
  2533. switch (identifier) {
  2534. case ValueID::Left:
  2535. case ValueID::Right:
  2536. return true;
  2537. default:
  2538. return false;
  2539. }
  2540. };
  2541. auto is_vertical = [](ValueID identifier) -> bool {
  2542. switch (identifier) {
  2543. case ValueID::Top:
  2544. case ValueID::Bottom:
  2545. return true;
  2546. default:
  2547. return false;
  2548. }
  2549. };
  2550. LengthPercentage zero_offset = Length::make_px(0);
  2551. LengthPercentage center_offset = Percentage { 50 };
  2552. struct EdgeOffset {
  2553. PositionEdge edge;
  2554. LengthPercentage offset;
  2555. bool edge_provided;
  2556. bool offset_provided;
  2557. };
  2558. Optional<EdgeOffset> horizontal;
  2559. Optional<EdgeOffset> vertical;
  2560. bool found_center = false;
  2561. while (tokens.has_next_token()) {
  2562. // Check if we're done
  2563. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  2564. if (seen_items == 2)
  2565. break;
  2566. auto& token = tokens.peek_token();
  2567. auto maybe_value = parse_css_value(token);
  2568. if (!maybe_value || !property_accepts_value(PropertyID::BackgroundPosition, *maybe_value))
  2569. break;
  2570. tokens.next_token();
  2571. auto value = maybe_value.release_nonnull();
  2572. if (value->is_percentage()) {
  2573. if (!horizontal.has_value()) {
  2574. horizontal = EdgeOffset { PositionEdge::Left, value->as_percentage().percentage(), false, true };
  2575. } else if (!vertical.has_value()) {
  2576. vertical = EdgeOffset { PositionEdge::Top, value->as_percentage().percentage(), false, true };
  2577. } else {
  2578. return error();
  2579. }
  2580. continue;
  2581. }
  2582. if (value->has_length()) {
  2583. if (!horizontal.has_value()) {
  2584. horizontal = EdgeOffset { PositionEdge::Left, value->to_length(), false, true };
  2585. } else if (!vertical.has_value()) {
  2586. vertical = EdgeOffset { PositionEdge::Top, value->to_length(), false, true };
  2587. } else {
  2588. return error();
  2589. }
  2590. continue;
  2591. }
  2592. if (value->has_identifier()) {
  2593. auto identifier = value->to_identifier();
  2594. if (is_horizontal(identifier)) {
  2595. LengthPercentage offset = zero_offset;
  2596. bool offset_provided = false;
  2597. if (tokens.has_next_token()) {
  2598. auto maybe_offset = parse_dimension(tokens.peek_token());
  2599. if (maybe_offset.has_value() && maybe_offset.value().is_length_percentage()) {
  2600. offset = maybe_offset.value().length_percentage();
  2601. offset_provided = true;
  2602. tokens.next_token();
  2603. }
  2604. }
  2605. horizontal = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2606. } else if (is_vertical(identifier)) {
  2607. LengthPercentage offset = zero_offset;
  2608. bool offset_provided = false;
  2609. if (tokens.has_next_token()) {
  2610. auto maybe_offset = parse_dimension(tokens.peek_token());
  2611. if (maybe_offset.has_value() && maybe_offset.value().is_length_percentage()) {
  2612. offset = maybe_offset.value().length_percentage();
  2613. offset_provided = true;
  2614. tokens.next_token();
  2615. }
  2616. }
  2617. vertical = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2618. } else if (identifier == ValueID::Center) {
  2619. found_center = true;
  2620. } else {
  2621. return error();
  2622. }
  2623. continue;
  2624. }
  2625. tokens.reconsume_current_input_token();
  2626. break;
  2627. }
  2628. if (found_center) {
  2629. if (horizontal.has_value() && vertical.has_value())
  2630. return error();
  2631. if (!horizontal.has_value())
  2632. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  2633. if (!vertical.has_value())
  2634. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  2635. }
  2636. if (!horizontal.has_value() && !vertical.has_value())
  2637. return error();
  2638. // Unpack `<edge> <length>`:
  2639. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  2640. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  2641. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  2642. // Split into `x y`
  2643. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  2644. horizontal->offset = zero_offset;
  2645. horizontal->offset_provided = false;
  2646. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  2647. // `y`, reconsume
  2648. vertical->offset = zero_offset;
  2649. vertical->offset_provided = false;
  2650. tokens.reconsume_current_input_token();
  2651. }
  2652. // If only one value is specified, the second value is assumed to be center.
  2653. if (!horizontal.has_value())
  2654. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  2655. if (!vertical.has_value())
  2656. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  2657. return PositionStyleValue::create(
  2658. horizontal->edge, horizontal->offset,
  2659. vertical->edge, vertical->offset);
  2660. }
  2661. RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<StyleComponentValueRule>& tokens)
  2662. {
  2663. auto start_position = tokens.position();
  2664. auto error = [&]() {
  2665. tokens.rewind_to_position(start_position);
  2666. return nullptr;
  2667. };
  2668. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2669. auto value_id = value.to_identifier();
  2670. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2671. };
  2672. auto as_repeat = [](ValueID identifier) {
  2673. switch (identifier) {
  2674. case ValueID::NoRepeat:
  2675. return Repeat::NoRepeat;
  2676. case ValueID::Repeat:
  2677. return Repeat::Repeat;
  2678. case ValueID::Round:
  2679. return Repeat::Round;
  2680. case ValueID::Space:
  2681. return Repeat::Space;
  2682. default:
  2683. VERIFY_NOT_REACHED();
  2684. }
  2685. };
  2686. auto& token = tokens.next_token();
  2687. auto maybe_x_value = parse_css_value(token);
  2688. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_x_value))
  2689. return error();
  2690. auto x_value = maybe_x_value.release_nonnull();
  2691. if (is_directional_repeat(*x_value)) {
  2692. auto value_id = x_value->to_identifier();
  2693. return BackgroundRepeatStyleValue::create(
  2694. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  2695. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  2696. }
  2697. // See if we have a second value for Y
  2698. auto& second_token = tokens.peek_token();
  2699. auto maybe_y_value = parse_css_value(second_token);
  2700. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_y_value)) {
  2701. // We don't have a second value, so use x for both
  2702. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(x_value->to_identifier()));
  2703. }
  2704. tokens.next_token();
  2705. auto y_value = maybe_y_value.release_nonnull();
  2706. if (is_directional_repeat(*y_value))
  2707. return error();
  2708. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(y_value->to_identifier()));
  2709. }
  2710. RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<StyleComponentValueRule>& tokens)
  2711. {
  2712. auto start_position = tokens.position();
  2713. auto error = [&]() {
  2714. tokens.rewind_to_position(start_position);
  2715. return nullptr;
  2716. };
  2717. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  2718. if (style_value.is_percentage())
  2719. return LengthPercentage { style_value.as_percentage().percentage() };
  2720. if (style_value.has_length())
  2721. return LengthPercentage { style_value.to_length() };
  2722. return {};
  2723. };
  2724. auto maybe_x_value = parse_css_value(tokens.next_token());
  2725. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_x_value))
  2726. return error();
  2727. auto x_value = maybe_x_value.release_nonnull();
  2728. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain)
  2729. return x_value;
  2730. auto maybe_y_value = parse_css_value(tokens.peek_token());
  2731. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_y_value)) {
  2732. auto x_size = get_length_percentage(*x_value);
  2733. if (!x_size.has_value())
  2734. return error();
  2735. return BackgroundSizeStyleValue::create(x_size.value(), x_size.value());
  2736. }
  2737. tokens.next_token();
  2738. auto y_value = maybe_y_value.release_nonnull();
  2739. auto x_size = get_length_percentage(*x_value);
  2740. auto y_size = get_length_percentage(*y_value);
  2741. if (x_size.has_value() && y_size.has_value())
  2742. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  2743. return error();
  2744. }
  2745. RefPtr<StyleValue> Parser::parse_border_value(Vector<StyleComponentValueRule> const& component_values)
  2746. {
  2747. if (component_values.size() > 3)
  2748. return nullptr;
  2749. RefPtr<StyleValue> border_width;
  2750. RefPtr<StyleValue> border_color;
  2751. RefPtr<StyleValue> border_style;
  2752. for (auto& part : component_values) {
  2753. auto value = parse_css_value(part);
  2754. if (!value)
  2755. return nullptr;
  2756. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  2757. if (border_width)
  2758. return nullptr;
  2759. border_width = value.release_nonnull();
  2760. continue;
  2761. }
  2762. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  2763. if (border_color)
  2764. return nullptr;
  2765. border_color = value.release_nonnull();
  2766. continue;
  2767. }
  2768. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  2769. if (border_style)
  2770. return nullptr;
  2771. border_style = value.release_nonnull();
  2772. continue;
  2773. }
  2774. return nullptr;
  2775. }
  2776. if (!border_width)
  2777. border_width = property_initial_value(PropertyID::BorderWidth);
  2778. if (!border_style)
  2779. border_style = property_initial_value(PropertyID::BorderStyle);
  2780. if (!border_color)
  2781. border_color = property_initial_value(PropertyID::BorderColor);
  2782. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  2783. }
  2784. RefPtr<StyleValue> Parser::parse_border_radius_value(Vector<StyleComponentValueRule> const& component_values)
  2785. {
  2786. if (component_values.size() == 2) {
  2787. auto horizontal = parse_dimension(component_values[0]);
  2788. auto vertical = parse_dimension(component_values[1]);
  2789. if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage())
  2790. return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());
  2791. return nullptr;
  2792. }
  2793. if (component_values.size() == 1) {
  2794. auto radius = parse_dimension(component_values[0]);
  2795. if (radius.has_value() && radius->is_length_percentage())
  2796. return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
  2797. return nullptr;
  2798. }
  2799. return nullptr;
  2800. }
  2801. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(Vector<StyleComponentValueRule> const& component_values)
  2802. {
  2803. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  2804. auto top_right = [&](Vector<LengthPercentage>& radii) {
  2805. switch (radii.size()) {
  2806. case 4:
  2807. case 3:
  2808. case 2:
  2809. return radii[1];
  2810. case 1:
  2811. return radii[0];
  2812. default:
  2813. VERIFY_NOT_REACHED();
  2814. }
  2815. };
  2816. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  2817. switch (radii.size()) {
  2818. case 4:
  2819. case 3:
  2820. return radii[2];
  2821. case 2:
  2822. case 1:
  2823. return radii[0];
  2824. default:
  2825. VERIFY_NOT_REACHED();
  2826. }
  2827. };
  2828. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  2829. switch (radii.size()) {
  2830. case 4:
  2831. return radii[3];
  2832. case 3:
  2833. case 2:
  2834. return radii[1];
  2835. case 1:
  2836. return radii[0];
  2837. default:
  2838. VERIFY_NOT_REACHED();
  2839. }
  2840. };
  2841. Vector<LengthPercentage> horizontal_radii;
  2842. Vector<LengthPercentage> vertical_radii;
  2843. bool reading_vertical = false;
  2844. for (auto& value : component_values) {
  2845. if (value.is(Token::Type::Delim) && value.token().delim() == '/') {
  2846. if (reading_vertical || horizontal_radii.is_empty())
  2847. return nullptr;
  2848. reading_vertical = true;
  2849. continue;
  2850. }
  2851. auto maybe_dimension = parse_dimension(value);
  2852. if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
  2853. return nullptr;
  2854. if (reading_vertical) {
  2855. vertical_radii.append(maybe_dimension->length_percentage());
  2856. } else {
  2857. horizontal_radii.append(maybe_dimension->length_percentage());
  2858. }
  2859. }
  2860. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2861. || horizontal_radii.is_empty()
  2862. || (reading_vertical && vertical_radii.is_empty()))
  2863. return nullptr;
  2864. NonnullRefPtrVector<StyleValue> border_radii;
  2865. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2866. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  2867. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2868. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  2869. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2870. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  2871. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2872. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  2873. return StyleValueList::create(move(border_radii), StyleValueList::Separator::Space);
  2874. }
  2875. RefPtr<StyleValue> Parser::parse_shadow_value(Vector<StyleComponentValueRule> const& component_values, AllowInsetKeyword allow_inset_keyword)
  2876. {
  2877. // "none"
  2878. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  2879. auto ident = parse_identifier_value(component_values.first());
  2880. if (ident && ident->to_identifier() == ValueID::None)
  2881. return ident;
  2882. }
  2883. return parse_comma_separated_value_list(component_values, [this, allow_inset_keyword](auto& tokens) {
  2884. return parse_single_shadow_value(tokens, allow_inset_keyword);
  2885. });
  2886. }
  2887. RefPtr<StyleValue> Parser::parse_single_shadow_value(TokenStream<StyleComponentValueRule>& tokens, AllowInsetKeyword allow_inset_keyword)
  2888. {
  2889. auto start_position = tokens.position();
  2890. auto error = [&]() {
  2891. tokens.rewind_to_position(start_position);
  2892. return nullptr;
  2893. };
  2894. Optional<Color> color;
  2895. Optional<Length> offset_x;
  2896. Optional<Length> offset_y;
  2897. Optional<Length> blur_radius;
  2898. Optional<Length> spread_distance;
  2899. Optional<ShadowPlacement> placement;
  2900. while (tokens.has_next_token()) {
  2901. auto& token = tokens.peek_token();
  2902. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  2903. if (color.has_value())
  2904. return error();
  2905. color = maybe_color.release_value();
  2906. tokens.next_token();
  2907. continue;
  2908. }
  2909. if (auto maybe_offset_x = parse_length(token); maybe_offset_x.has_value()) {
  2910. // horizontal offset
  2911. if (offset_x.has_value())
  2912. return error();
  2913. offset_x = maybe_offset_x.release_value();
  2914. tokens.next_token();
  2915. // vertical offset
  2916. if (!tokens.has_next_token())
  2917. return error();
  2918. auto maybe_offset_y = parse_length(tokens.peek_token());
  2919. if (!maybe_offset_y.has_value())
  2920. return error();
  2921. offset_y = maybe_offset_y.release_value();
  2922. tokens.next_token();
  2923. // blur radius (optional)
  2924. if (!tokens.has_next_token())
  2925. break;
  2926. auto maybe_blur_radius = parse_length(tokens.peek_token());
  2927. if (!maybe_blur_radius.has_value())
  2928. continue;
  2929. blur_radius = maybe_blur_radius.release_value();
  2930. tokens.next_token();
  2931. // spread distance (optional)
  2932. if (!tokens.has_next_token())
  2933. break;
  2934. auto maybe_spread_distance = parse_length(tokens.peek_token());
  2935. if (!maybe_spread_distance.has_value())
  2936. continue;
  2937. spread_distance = maybe_spread_distance.release_value();
  2938. tokens.next_token();
  2939. continue;
  2940. }
  2941. if (allow_inset_keyword == AllowInsetKeyword::Yes
  2942. && token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_case("inset"sv)) {
  2943. if (placement.has_value())
  2944. return error();
  2945. placement = ShadowPlacement::Inner;
  2946. tokens.next_token();
  2947. continue;
  2948. }
  2949. if (token.is(Token::Type::Comma))
  2950. break;
  2951. return error();
  2952. }
  2953. // FIXME: If color is absent, default to `currentColor`
  2954. if (!color.has_value())
  2955. color = Color::NamedColor::Black;
  2956. // x/y offsets are required
  2957. if (!offset_x.has_value() || !offset_y.has_value())
  2958. return error();
  2959. // Other lengths default to 0
  2960. if (!blur_radius.has_value())
  2961. blur_radius = Length::make_px(0);
  2962. if (!spread_distance.has_value())
  2963. spread_distance = Length::make_px(0);
  2964. // Placement is outer by default
  2965. if (!placement.has_value())
  2966. placement = ShadowPlacement::Outer;
  2967. 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());
  2968. }
  2969. RefPtr<StyleValue> Parser::parse_content_value(Vector<StyleComponentValueRule> const& component_values)
  2970. {
  2971. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  2972. auto is_single_value_identifier = [](ValueID identifier) -> bool {
  2973. switch (identifier) {
  2974. case ValueID::None:
  2975. case ValueID::Normal:
  2976. return true;
  2977. default:
  2978. return false;
  2979. }
  2980. };
  2981. if (component_values.size() == 1) {
  2982. if (auto identifier = parse_identifier_value(component_values.first())) {
  2983. if (is_single_value_identifier(identifier->to_identifier()))
  2984. return identifier;
  2985. }
  2986. }
  2987. NonnullRefPtrVector<StyleValue> content_values;
  2988. NonnullRefPtrVector<StyleValue> alt_text_values;
  2989. bool in_alt_text = false;
  2990. for (auto const& value : component_values) {
  2991. if (value.is(Token::Type::Delim) && value.token().delim() == '/') {
  2992. if (in_alt_text || content_values.is_empty())
  2993. return {};
  2994. in_alt_text = true;
  2995. continue;
  2996. }
  2997. auto style_value = parse_css_value(value);
  2998. if (style_value && property_accepts_value(PropertyID::Content, *style_value)) {
  2999. if (is_single_value_identifier(style_value->to_identifier()))
  3000. return {};
  3001. if (in_alt_text) {
  3002. alt_text_values.append(style_value.release_nonnull());
  3003. } else {
  3004. content_values.append(style_value.release_nonnull());
  3005. }
  3006. continue;
  3007. }
  3008. return {};
  3009. }
  3010. if (content_values.is_empty())
  3011. return {};
  3012. if (in_alt_text && alt_text_values.is_empty())
  3013. return {};
  3014. RefPtr<StyleValueList> alt_text;
  3015. if (!alt_text_values.is_empty())
  3016. alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);
  3017. return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
  3018. }
  3019. RefPtr<StyleValue> Parser::parse_flex_value(Vector<StyleComponentValueRule> const& component_values)
  3020. {
  3021. if (component_values.size() == 1) {
  3022. auto value = parse_css_value(component_values[0]);
  3023. if (!value)
  3024. return nullptr;
  3025. switch (value->to_identifier()) {
  3026. case ValueID::Auto: {
  3027. auto one = NumericStyleValue::create_integer(1);
  3028. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  3029. }
  3030. case ValueID::None: {
  3031. auto zero = NumericStyleValue::create_integer(0);
  3032. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  3033. }
  3034. default:
  3035. break;
  3036. }
  3037. }
  3038. RefPtr<StyleValue> flex_grow;
  3039. RefPtr<StyleValue> flex_shrink;
  3040. RefPtr<StyleValue> flex_basis;
  3041. for (size_t i = 0; i < component_values.size(); ++i) {
  3042. auto value = parse_css_value(component_values[i]);
  3043. if (!value)
  3044. return nullptr;
  3045. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  3046. if (value->has_number() && value->to_number() == 0) {
  3047. if (flex_grow && flex_shrink && !flex_basis) {
  3048. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  3049. continue;
  3050. }
  3051. }
  3052. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  3053. if (flex_grow)
  3054. return nullptr;
  3055. flex_grow = value.release_nonnull();
  3056. // Flex-shrink may optionally follow directly after.
  3057. if (i + 1 < component_values.size()) {
  3058. auto second_value = parse_css_value(component_values[i + 1]);
  3059. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  3060. flex_shrink = second_value.release_nonnull();
  3061. i++;
  3062. }
  3063. }
  3064. continue;
  3065. }
  3066. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  3067. if (flex_basis)
  3068. return nullptr;
  3069. flex_basis = value.release_nonnull();
  3070. continue;
  3071. }
  3072. return nullptr;
  3073. }
  3074. if (!flex_grow)
  3075. flex_grow = property_initial_value(PropertyID::FlexGrow);
  3076. if (!flex_shrink)
  3077. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  3078. if (!flex_basis)
  3079. flex_basis = property_initial_value(PropertyID::FlexBasis);
  3080. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  3081. }
  3082. RefPtr<StyleValue> Parser::parse_flex_flow_value(Vector<StyleComponentValueRule> const& component_values)
  3083. {
  3084. if (component_values.size() > 2)
  3085. return nullptr;
  3086. RefPtr<StyleValue> flex_direction;
  3087. RefPtr<StyleValue> flex_wrap;
  3088. for (auto& part : component_values) {
  3089. auto value = parse_css_value(part);
  3090. if (!value)
  3091. return nullptr;
  3092. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  3093. if (flex_direction)
  3094. return nullptr;
  3095. flex_direction = value.release_nonnull();
  3096. continue;
  3097. }
  3098. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  3099. if (flex_wrap)
  3100. return nullptr;
  3101. flex_wrap = value.release_nonnull();
  3102. continue;
  3103. }
  3104. }
  3105. if (!flex_direction)
  3106. flex_direction = property_initial_value(PropertyID::FlexDirection);
  3107. if (!flex_wrap)
  3108. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  3109. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  3110. }
  3111. static bool is_generic_font_family(ValueID identifier)
  3112. {
  3113. switch (identifier) {
  3114. case ValueID::Cursive:
  3115. case ValueID::Fantasy:
  3116. case ValueID::Monospace:
  3117. case ValueID::Serif:
  3118. case ValueID::SansSerif:
  3119. case ValueID::UiMonospace:
  3120. case ValueID::UiRounded:
  3121. case ValueID::UiSerif:
  3122. case ValueID::UiSansSerif:
  3123. return true;
  3124. default:
  3125. return false;
  3126. }
  3127. }
  3128. RefPtr<StyleValue> Parser::parse_font_value(Vector<StyleComponentValueRule> const& component_values)
  3129. {
  3130. RefPtr<StyleValue> font_style;
  3131. RefPtr<StyleValue> font_weight;
  3132. RefPtr<StyleValue> font_size;
  3133. RefPtr<StyleValue> line_height;
  3134. RefPtr<StyleValue> font_families;
  3135. RefPtr<StyleValue> font_variant;
  3136. // FIXME: Implement font-stretch.
  3137. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  3138. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  3139. // So, we have to handle that separately.
  3140. int normal_count = 0;
  3141. for (size_t i = 0; i < component_values.size(); ++i) {
  3142. auto value = parse_css_value(component_values[i]);
  3143. if (!value)
  3144. return nullptr;
  3145. if (value->to_identifier() == ValueID::Normal) {
  3146. normal_count++;
  3147. continue;
  3148. }
  3149. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  3150. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  3151. if (font_style)
  3152. return nullptr;
  3153. font_style = value.release_nonnull();
  3154. continue;
  3155. }
  3156. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  3157. if (font_weight)
  3158. return nullptr;
  3159. font_weight = value.release_nonnull();
  3160. continue;
  3161. }
  3162. if (property_accepts_value(PropertyID::FontVariant, *value)) {
  3163. if (font_variant)
  3164. return nullptr;
  3165. font_variant = value.release_nonnull();
  3166. continue;
  3167. }
  3168. if (property_accepts_value(PropertyID::FontSize, *value)) {
  3169. if (font_size)
  3170. return nullptr;
  3171. font_size = value.release_nonnull();
  3172. // Consume `/ line-height` if present
  3173. if (i + 2 < component_values.size()) {
  3174. auto maybe_solidus = component_values[i + 1];
  3175. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == '/') {
  3176. auto maybe_line_height = parse_css_value(component_values[i + 2]);
  3177. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  3178. return nullptr;
  3179. line_height = maybe_line_height.release_nonnull();
  3180. i += 2;
  3181. }
  3182. }
  3183. // Consume font-families
  3184. auto maybe_font_families = parse_font_family_value(component_values, i + 1);
  3185. if (!maybe_font_families)
  3186. return nullptr;
  3187. font_families = maybe_font_families.release_nonnull();
  3188. break;
  3189. }
  3190. return nullptr;
  3191. }
  3192. // Since normal is the default value for all the properties that can have it, we don't have to actually
  3193. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  3194. // We just need to make sure we were not given more normals than will fit.
  3195. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  3196. if (unset_value_count < normal_count)
  3197. return nullptr;
  3198. if (!font_size || !font_families)
  3199. return nullptr;
  3200. if (!font_style)
  3201. font_style = property_initial_value(PropertyID::FontStyle);
  3202. if (!font_weight)
  3203. font_weight = property_initial_value(PropertyID::FontWeight);
  3204. if (!line_height)
  3205. line_height = property_initial_value(PropertyID::LineHeight);
  3206. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  3207. }
  3208. RefPtr<StyleValue> Parser::parse_font_family_value(Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  3209. {
  3210. auto is_comma_or_eof = [&](size_t i) -> bool {
  3211. if (i < component_values.size()) {
  3212. auto& maybe_comma = component_values[i];
  3213. if (!maybe_comma.is(Token::Type::Comma))
  3214. return false;
  3215. }
  3216. return true;
  3217. };
  3218. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  3219. // eg, these are equivalent:
  3220. // font-family: my cool font\!, serif;
  3221. // font-family: "my cool font!", serif;
  3222. NonnullRefPtrVector<StyleValue> font_families;
  3223. Vector<String> current_name_parts;
  3224. for (size_t i = start_index; i < component_values.size(); ++i) {
  3225. auto& part = component_values[i];
  3226. if (part.is(Token::Type::String)) {
  3227. // `font-family: my cool "font";` is invalid.
  3228. if (!current_name_parts.is_empty())
  3229. return nullptr;
  3230. if (!is_comma_or_eof(i + 1))
  3231. return nullptr;
  3232. font_families.append(StringStyleValue::create(part.token().string()));
  3233. i++;
  3234. continue;
  3235. }
  3236. if (part.is(Token::Type::Ident)) {
  3237. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  3238. auto maybe_ident = parse_css_value(part);
  3239. if (maybe_ident) {
  3240. // CSS-wide keywords are not allowed
  3241. if (maybe_ident->is_builtin())
  3242. return nullptr;
  3243. if (is_generic_font_family(maybe_ident->to_identifier())) {
  3244. // Can't have a generic-font-name as a token in an unquoted font name.
  3245. if (!current_name_parts.is_empty())
  3246. return nullptr;
  3247. if (!is_comma_or_eof(i + 1))
  3248. return nullptr;
  3249. font_families.append(maybe_ident.release_nonnull());
  3250. i++;
  3251. continue;
  3252. }
  3253. }
  3254. current_name_parts.append(part.token().ident());
  3255. continue;
  3256. }
  3257. if (part.is(Token::Type::Comma)) {
  3258. if (current_name_parts.is_empty())
  3259. return nullptr;
  3260. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  3261. current_name_parts.clear();
  3262. // Can't have a trailing comma
  3263. if (i + 1 == component_values.size())
  3264. return nullptr;
  3265. continue;
  3266. }
  3267. }
  3268. if (!current_name_parts.is_empty()) {
  3269. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  3270. current_name_parts.clear();
  3271. }
  3272. if (font_families.is_empty())
  3273. return nullptr;
  3274. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  3275. }
  3276. RefPtr<CSSRule> Parser::parse_font_face_rule(TokenStream<StyleComponentValueRule>& tokens)
  3277. {
  3278. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  3279. Optional<FlyString> font_family;
  3280. Vector<FontFace::Source> src;
  3281. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  3282. if (declaration_or_at_rule.is_at_rule()) {
  3283. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-family; discarding.");
  3284. continue;
  3285. }
  3286. auto& declaration = declaration_or_at_rule.declaration();
  3287. if (declaration.m_name.equals_ignoring_case("font-family"sv)) {
  3288. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  3289. // Ideally they could share code.
  3290. Vector<String> font_family_parts;
  3291. bool had_syntax_error = false;
  3292. for (size_t i = 0; i < declaration.m_values.size(); ++i) {
  3293. auto& part = declaration.m_values[i];
  3294. if (part.is(Token::Type::Whitespace))
  3295. continue;
  3296. if (part.is(Token::Type::String)) {
  3297. if (!font_family_parts.is_empty()) {
  3298. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3299. had_syntax_error = true;
  3300. break;
  3301. }
  3302. font_family_parts.append(part.token().string());
  3303. continue;
  3304. }
  3305. if (part.is(Token::Type::Ident)) {
  3306. auto value_id = value_id_from_string(part.token().ident());
  3307. if (is_generic_font_family(value_id)) {
  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().ident());
  3313. continue;
  3314. }
  3315. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3316. had_syntax_error = true;
  3317. break;
  3318. }
  3319. if (had_syntax_error || font_family_parts.is_empty())
  3320. continue;
  3321. font_family = String::join(' ', font_family_parts);
  3322. continue;
  3323. }
  3324. if (declaration.m_name.equals_ignoring_case("src"sv)) {
  3325. Vector<FontFace::Source> supported_sources;
  3326. // FIXME: Implement `local()`.
  3327. // FIXME: Implement `format()`.
  3328. TokenStream token_stream { declaration.m_values };
  3329. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(token_stream);
  3330. for (auto const& source_token_list : list_of_source_token_lists) {
  3331. Optional<AK::URL> url;
  3332. bool had_syntax_error = false;
  3333. for (auto const& source_token : source_token_list) {
  3334. // FIXME: Allow data urls for fonts.
  3335. if (auto maybe_url = parse_url_function(source_token); maybe_url.has_value()) {
  3336. if (url.has_value()) {
  3337. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format invalid; discarding.");
  3338. had_syntax_error = true;
  3339. break;
  3340. }
  3341. url = maybe_url.release_value();
  3342. }
  3343. }
  3344. if (had_syntax_error)
  3345. continue;
  3346. if (!url.has_value())
  3347. continue;
  3348. supported_sources.empend(url.release_value());
  3349. }
  3350. if (supported_sources.is_empty())
  3351. continue;
  3352. src = move(supported_sources);
  3353. }
  3354. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-family; discarding.", declaration.m_name);
  3355. }
  3356. if (!font_family.has_value()) {
  3357. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  3358. return {};
  3359. }
  3360. return CSSFontFaceRule::create(FontFace { font_family.release_value(), move(src) });
  3361. }
  3362. RefPtr<StyleValue> Parser::parse_list_style_value(Vector<StyleComponentValueRule> const& component_values)
  3363. {
  3364. if (component_values.size() > 3)
  3365. return nullptr;
  3366. RefPtr<StyleValue> list_position;
  3367. RefPtr<StyleValue> list_image;
  3368. RefPtr<StyleValue> list_type;
  3369. int found_nones = 0;
  3370. for (auto& part : component_values) {
  3371. auto value = parse_css_value(part);
  3372. if (!value)
  3373. return nullptr;
  3374. if (value->to_identifier() == ValueID::None) {
  3375. found_nones++;
  3376. continue;
  3377. }
  3378. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  3379. if (list_position)
  3380. return nullptr;
  3381. list_position = value.release_nonnull();
  3382. continue;
  3383. }
  3384. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  3385. if (list_image)
  3386. return nullptr;
  3387. list_image = value.release_nonnull();
  3388. continue;
  3389. }
  3390. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  3391. if (list_type)
  3392. return nullptr;
  3393. list_type = value.release_nonnull();
  3394. continue;
  3395. }
  3396. }
  3397. if (found_nones > 2)
  3398. return nullptr;
  3399. if (found_nones == 2) {
  3400. if (list_image || list_type)
  3401. return nullptr;
  3402. auto none = IdentifierStyleValue::create(ValueID::None);
  3403. list_image = none;
  3404. list_type = none;
  3405. } else if (found_nones == 1) {
  3406. if (list_image && list_type)
  3407. return nullptr;
  3408. auto none = IdentifierStyleValue::create(ValueID::None);
  3409. if (!list_image)
  3410. list_image = none;
  3411. if (!list_type)
  3412. list_type = none;
  3413. }
  3414. if (!list_position)
  3415. list_position = property_initial_value(PropertyID::ListStylePosition);
  3416. if (!list_image)
  3417. list_image = property_initial_value(PropertyID::ListStyleImage);
  3418. if (!list_type)
  3419. list_type = property_initial_value(PropertyID::ListStyleType);
  3420. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  3421. }
  3422. RefPtr<StyleValue> Parser::parse_overflow_value(Vector<StyleComponentValueRule> const& component_values)
  3423. {
  3424. if (component_values.size() == 1) {
  3425. auto maybe_value = parse_css_value(component_values.first());
  3426. if (!maybe_value)
  3427. return nullptr;
  3428. auto value = maybe_value.release_nonnull();
  3429. if (property_accepts_value(PropertyID::Overflow, *value))
  3430. return OverflowStyleValue::create(value, value);
  3431. return nullptr;
  3432. }
  3433. if (component_values.size() == 2) {
  3434. auto maybe_x_value = parse_css_value(component_values[0]);
  3435. auto maybe_y_value = parse_css_value(component_values[1]);
  3436. if (!maybe_x_value || !maybe_y_value)
  3437. return nullptr;
  3438. auto x_value = maybe_x_value.release_nonnull();
  3439. auto y_value = maybe_y_value.release_nonnull();
  3440. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  3441. return nullptr;
  3442. }
  3443. return OverflowStyleValue::create(x_value, y_value);
  3444. }
  3445. return nullptr;
  3446. }
  3447. RefPtr<StyleValue> Parser::parse_text_decoration_value(Vector<StyleComponentValueRule> const& component_values)
  3448. {
  3449. if (component_values.size() > 4)
  3450. return nullptr;
  3451. RefPtr<StyleValue> decoration_line;
  3452. RefPtr<StyleValue> decoration_thickness;
  3453. RefPtr<StyleValue> decoration_style;
  3454. RefPtr<StyleValue> decoration_color;
  3455. for (auto& part : component_values) {
  3456. auto value = parse_css_value(part);
  3457. if (!value)
  3458. return nullptr;
  3459. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  3460. if (decoration_color)
  3461. return nullptr;
  3462. decoration_color = value.release_nonnull();
  3463. continue;
  3464. }
  3465. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  3466. if (decoration_line)
  3467. return nullptr;
  3468. decoration_line = value.release_nonnull();
  3469. continue;
  3470. }
  3471. if (property_accepts_value(PropertyID::TextDecorationThickness, *value)) {
  3472. if (decoration_thickness)
  3473. return nullptr;
  3474. decoration_thickness = value.release_nonnull();
  3475. continue;
  3476. }
  3477. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  3478. if (decoration_style)
  3479. return nullptr;
  3480. decoration_style = value.release_nonnull();
  3481. continue;
  3482. }
  3483. return nullptr;
  3484. }
  3485. if (!decoration_line)
  3486. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  3487. if (!decoration_thickness)
  3488. decoration_thickness = property_initial_value(PropertyID::TextDecorationThickness);
  3489. if (!decoration_style)
  3490. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  3491. if (!decoration_color)
  3492. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  3493. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  3494. }
  3495. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  3496. {
  3497. if (name == "matrix")
  3498. return CSS::TransformFunction::Matrix;
  3499. if (name == "translate")
  3500. return CSS::TransformFunction::Translate;
  3501. if (name == "translateX")
  3502. return CSS::TransformFunction::TranslateX;
  3503. if (name == "translateY")
  3504. return CSS::TransformFunction::TranslateY;
  3505. if (name == "scale")
  3506. return CSS::TransformFunction::Scale;
  3507. if (name == "scaleX")
  3508. return CSS::TransformFunction::ScaleX;
  3509. if (name == "scaleY")
  3510. return CSS::TransformFunction::ScaleY;
  3511. if (name == "rotate")
  3512. return CSS::TransformFunction::Rotate;
  3513. if (name == "skew")
  3514. return CSS::TransformFunction::Skew;
  3515. if (name == "skewX")
  3516. return CSS::TransformFunction::SkewX;
  3517. if (name == "skewY")
  3518. return CSS::TransformFunction::SkewY;
  3519. return {};
  3520. }
  3521. RefPtr<StyleValue> Parser::parse_transform_value(Vector<StyleComponentValueRule> const& component_values)
  3522. {
  3523. NonnullRefPtrVector<StyleValue> transformations;
  3524. for (auto& part : component_values) {
  3525. if (part.is(Token::Type::Whitespace))
  3526. continue;
  3527. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_case("none")) {
  3528. if (!transformations.is_empty())
  3529. return nullptr;
  3530. return IdentifierStyleValue::create(ValueID::None);
  3531. }
  3532. if (!part.is_function())
  3533. return nullptr;
  3534. auto maybe_function = parse_transform_function_name(part.function().name());
  3535. if (!maybe_function.has_value())
  3536. return nullptr;
  3537. bool expect_comma = false;
  3538. NonnullRefPtrVector<StyleValue> values;
  3539. for (auto& value : part.function().values()) {
  3540. if (value.is(Token::Type::Whitespace))
  3541. continue;
  3542. if (value.is(Token::Type::Comma)) {
  3543. if (!expect_comma)
  3544. return nullptr;
  3545. expect_comma = false;
  3546. continue;
  3547. } else if (expect_comma)
  3548. return nullptr;
  3549. if (value.is(Token::Type::Dimension)) {
  3550. auto dimension = parse_dimension(value);
  3551. if (!dimension.has_value())
  3552. return nullptr;
  3553. auto dimension_value = dimension.release_value();
  3554. if (dimension_value.is_length())
  3555. values.append(LengthStyleValue::create(dimension_value.length()));
  3556. else if (dimension_value.is_angle())
  3557. values.append(AngleStyleValue::create(dimension_value.angle()));
  3558. else
  3559. return nullptr;
  3560. } else if (value.is(Token::Type::Number)) {
  3561. auto number = parse_numeric_value(value);
  3562. values.append(number.release_nonnull());
  3563. } else if (value.is(Token::Type::Percentage)) {
  3564. auto percentage = parse_dimension_value(value);
  3565. if (!percentage || !percentage->is_percentage())
  3566. return nullptr;
  3567. values.append(percentage.release_nonnull());
  3568. } else {
  3569. dbgln_if(CSS_PARSER_DEBUG, "FIXME: Unsupported value type for transformation!");
  3570. return nullptr;
  3571. }
  3572. expect_comma = true;
  3573. }
  3574. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  3575. }
  3576. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  3577. }
  3578. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  3579. // FIXME: This only supports a 2D position
  3580. RefPtr<StyleValue> Parser::parse_transform_origin_value(Vector<StyleComponentValueRule> const& component_values)
  3581. {
  3582. enum class Axis {
  3583. None,
  3584. X,
  3585. Y,
  3586. };
  3587. struct AxisOffset {
  3588. Axis axis;
  3589. NonnullRefPtr<StyleValue> offset;
  3590. };
  3591. auto to_axis_offset = [](RefPtr<StyleValue> value) -> Optional<AxisOffset> {
  3592. if (value->is_percentage())
  3593. return AxisOffset { Axis::None, value->as_percentage() };
  3594. if (value->is_length())
  3595. return AxisOffset { Axis::None, value->as_length() };
  3596. if (value->has_length())
  3597. return AxisOffset { Axis::None, LengthStyleValue::create(value->to_length()) };
  3598. if (value->is_identifier()) {
  3599. switch (value->to_identifier()) {
  3600. case ValueID::Top:
  3601. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
  3602. case ValueID::Left:
  3603. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
  3604. case ValueID::Center:
  3605. return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
  3606. case ValueID::Bottom:
  3607. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
  3608. case ValueID::Right:
  3609. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
  3610. default:
  3611. return {};
  3612. }
  3613. }
  3614. return {};
  3615. };
  3616. auto make_list = [](NonnullRefPtr<StyleValue> x_value, NonnullRefPtr<StyleValue> y_value) -> NonnullRefPtr<StyleValueList> {
  3617. NonnullRefPtrVector<StyleValue> values;
  3618. values.append(x_value);
  3619. values.append(y_value);
  3620. return StyleValueList::create(move(values), StyleValueList::Separator::Space);
  3621. };
  3622. switch (component_values.size()) {
  3623. case 1: {
  3624. auto single_value = to_axis_offset(parse_css_value(component_values[0]));
  3625. if (!single_value.has_value())
  3626. return nullptr;
  3627. // If only one value is specified, the second value is assumed to be center.
  3628. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  3629. switch (single_value->axis) {
  3630. case Axis::None:
  3631. case Axis::X:
  3632. return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
  3633. case Axis::Y:
  3634. return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
  3635. }
  3636. VERIFY_NOT_REACHED();
  3637. }
  3638. case 2: {
  3639. auto first_value = to_axis_offset(parse_css_value(component_values[0]));
  3640. auto second_value = to_axis_offset(parse_css_value(component_values[1]));
  3641. if (!first_value.has_value() || !second_value.has_value())
  3642. return nullptr;
  3643. RefPtr<StyleValue> x_value;
  3644. RefPtr<StyleValue> y_value;
  3645. if (first_value->axis == Axis::X) {
  3646. x_value = first_value->offset;
  3647. } else if (first_value->axis == Axis::Y) {
  3648. y_value = first_value->offset;
  3649. }
  3650. if (second_value->axis == Axis::X) {
  3651. if (x_value)
  3652. return nullptr;
  3653. x_value = second_value->offset;
  3654. // Put the other in Y since its axis can't have been X
  3655. y_value = first_value->offset;
  3656. } else if (second_value->axis == Axis::Y) {
  3657. if (y_value)
  3658. return nullptr;
  3659. y_value = second_value->offset;
  3660. // Put the other in X since its axis can't have been Y
  3661. x_value = first_value->offset;
  3662. } else {
  3663. if (x_value) {
  3664. VERIFY(!y_value);
  3665. y_value = second_value->offset;
  3666. } else {
  3667. VERIFY(!x_value);
  3668. x_value = second_value->offset;
  3669. }
  3670. }
  3671. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  3672. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  3673. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  3674. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  3675. x_value = first_value->offset;
  3676. y_value = second_value->offset;
  3677. }
  3678. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  3679. }
  3680. }
  3681. return nullptr;
  3682. }
  3683. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  3684. {
  3685. auto component_values = parse_as_list_of_component_values();
  3686. auto tokens = TokenStream(component_values);
  3687. auto parsed_value = parse_css_value(property_id, tokens);
  3688. if (parsed_value.is_error())
  3689. return {};
  3690. return parsed_value.release_value();
  3691. }
  3692. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  3693. {
  3694. auto block_contains_var_or_attr = [](StyleBlockRule const& block, auto&& recurse) -> bool {
  3695. for (auto const& token : block.values()) {
  3696. if (token.is_function() && (token.function().name().equals_ignoring_case("var"sv) || token.function().name().equals_ignoring_case("attr"sv)))
  3697. return true;
  3698. if (token.is_block() && recurse(token.block(), recurse))
  3699. return true;
  3700. }
  3701. return false;
  3702. };
  3703. m_context.set_current_property_id(property_id);
  3704. Vector<StyleComponentValueRule> component_values;
  3705. bool contains_var_or_attr = false;
  3706. while (tokens.has_next_token()) {
  3707. auto& token = tokens.next_token();
  3708. if (token.is(Token::Type::Semicolon)) {
  3709. tokens.reconsume_current_input_token();
  3710. break;
  3711. }
  3712. if (property_id != PropertyID::Custom) {
  3713. if (token.is(Token::Type::Whitespace))
  3714. continue;
  3715. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  3716. return ParsingResult::IncludesIgnoredVendorPrefix;
  3717. }
  3718. if (!contains_var_or_attr) {
  3719. if (token.is_function() && (token.function().name().equals_ignoring_case("var"sv) || token.function().name().equals_ignoring_case("attr"sv)))
  3720. contains_var_or_attr = true;
  3721. else if (token.is_block() && block_contains_var_or_attr(token.block(), block_contains_var_or_attr))
  3722. contains_var_or_attr = true;
  3723. }
  3724. component_values.append(token);
  3725. }
  3726. if (property_id == PropertyID::Custom || contains_var_or_attr)
  3727. return { UnresolvedStyleValue::create(move(component_values), contains_var_or_attr) };
  3728. if (component_values.is_empty())
  3729. return ParsingResult::SyntaxError;
  3730. if (component_values.size() == 1) {
  3731. if (auto parsed_value = parse_builtin_value(component_values.first()))
  3732. return parsed_value.release_nonnull();
  3733. }
  3734. // Special-case property handling
  3735. switch (property_id) {
  3736. case PropertyID::Background:
  3737. if (auto parsed_value = parse_background_value(component_values))
  3738. return parsed_value.release_nonnull();
  3739. return ParsingResult::SyntaxError;
  3740. case PropertyID::BackgroundAttachment:
  3741. case PropertyID::BackgroundClip:
  3742. case PropertyID::BackgroundImage:
  3743. case PropertyID::BackgroundOrigin:
  3744. if (auto parsed_value = parse_simple_comma_separated_value_list(component_values))
  3745. return parsed_value.release_nonnull();
  3746. return ParsingResult::SyntaxError;
  3747. case PropertyID::BackgroundPosition:
  3748. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); }))
  3749. return parsed_value.release_nonnull();
  3750. return ParsingResult::SyntaxError;
  3751. case PropertyID::BackgroundRepeat:
  3752. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  3753. return parsed_value.release_nonnull();
  3754. return ParsingResult::SyntaxError;
  3755. case PropertyID::BackgroundSize:
  3756. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  3757. return parsed_value.release_nonnull();
  3758. return ParsingResult::SyntaxError;
  3759. case PropertyID::Border:
  3760. case PropertyID::BorderBottom:
  3761. case PropertyID::BorderLeft:
  3762. case PropertyID::BorderRight:
  3763. case PropertyID::BorderTop:
  3764. if (auto parsed_value = parse_border_value(component_values))
  3765. return parsed_value.release_nonnull();
  3766. return ParsingResult::SyntaxError;
  3767. case PropertyID::BorderTopLeftRadius:
  3768. case PropertyID::BorderTopRightRadius:
  3769. case PropertyID::BorderBottomRightRadius:
  3770. case PropertyID::BorderBottomLeftRadius:
  3771. if (auto parsed_value = parse_border_radius_value(component_values))
  3772. return parsed_value.release_nonnull();
  3773. return ParsingResult::SyntaxError;
  3774. case PropertyID::BorderRadius:
  3775. if (auto parsed_value = parse_border_radius_shorthand_value(component_values))
  3776. return parsed_value.release_nonnull();
  3777. return ParsingResult::SyntaxError;
  3778. case PropertyID::BoxShadow:
  3779. if (auto parsed_value = parse_shadow_value(component_values, AllowInsetKeyword::Yes))
  3780. return parsed_value.release_nonnull();
  3781. return ParsingResult::SyntaxError;
  3782. case PropertyID::Content:
  3783. if (auto parsed_value = parse_content_value(component_values))
  3784. return parsed_value.release_nonnull();
  3785. return ParsingResult::SyntaxError;
  3786. case PropertyID::Flex:
  3787. if (auto parsed_value = parse_flex_value(component_values))
  3788. return parsed_value.release_nonnull();
  3789. return ParsingResult::SyntaxError;
  3790. case PropertyID::FlexFlow:
  3791. if (auto parsed_value = parse_flex_flow_value(component_values))
  3792. return parsed_value.release_nonnull();
  3793. return ParsingResult::SyntaxError;
  3794. case PropertyID::Font:
  3795. if (auto parsed_value = parse_font_value(component_values))
  3796. return parsed_value.release_nonnull();
  3797. return ParsingResult::SyntaxError;
  3798. case PropertyID::FontFamily:
  3799. if (auto parsed_value = parse_font_family_value(component_values))
  3800. return parsed_value.release_nonnull();
  3801. return ParsingResult::SyntaxError;
  3802. case PropertyID::ListStyle:
  3803. if (auto parsed_value = parse_list_style_value(component_values))
  3804. return parsed_value.release_nonnull();
  3805. return ParsingResult::SyntaxError;
  3806. case PropertyID::Overflow:
  3807. if (auto parsed_value = parse_overflow_value(component_values))
  3808. return parsed_value.release_nonnull();
  3809. return ParsingResult::SyntaxError;
  3810. case PropertyID::TextDecoration:
  3811. if (auto parsed_value = parse_text_decoration_value(component_values))
  3812. return parsed_value.release_nonnull();
  3813. return ParsingResult::SyntaxError;
  3814. case PropertyID::TextShadow:
  3815. if (auto parsed_value = parse_shadow_value(component_values, AllowInsetKeyword::No))
  3816. return parsed_value.release_nonnull();
  3817. return ParsingResult::SyntaxError;
  3818. case PropertyID::Transform:
  3819. if (auto parsed_value = parse_transform_value(component_values))
  3820. return parsed_value.release_nonnull();
  3821. return ParsingResult::SyntaxError;
  3822. case PropertyID::TransformOrigin:
  3823. if (auto parse_value = parse_transform_origin_value(component_values))
  3824. return parse_value.release_nonnull();
  3825. return ParsingResult ::SyntaxError;
  3826. default:
  3827. break;
  3828. }
  3829. if (component_values.size() == 1) {
  3830. if (auto parsed_value = parse_css_value(component_values.first())) {
  3831. if (property_accepts_value(property_id, *parsed_value))
  3832. return parsed_value.release_nonnull();
  3833. }
  3834. return ParsingResult::SyntaxError;
  3835. }
  3836. // We have multiple values, so treat them as a StyleValueList.
  3837. if (property_maximum_value_count(property_id) > 1) {
  3838. NonnullRefPtrVector<StyleValue> parsed_values;
  3839. for (auto& component_value : component_values) {
  3840. auto parsed_value = parse_css_value(component_value);
  3841. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  3842. return ParsingResult::SyntaxError;
  3843. parsed_values.append(parsed_value.release_nonnull());
  3844. }
  3845. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  3846. return { StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space) };
  3847. }
  3848. return ParsingResult::SyntaxError;
  3849. }
  3850. RefPtr<StyleValue> Parser::parse_css_value(StyleComponentValueRule const& component_value)
  3851. {
  3852. if (auto builtin = parse_builtin_value(component_value))
  3853. return builtin;
  3854. if (auto dynamic = parse_dynamic_value(component_value))
  3855. return dynamic;
  3856. // We parse colors before numbers, to catch hashless hex colors.
  3857. if (auto color = parse_color_value(component_value))
  3858. return color;
  3859. if (auto dimension = parse_dimension_value(component_value))
  3860. return dimension;
  3861. if (auto numeric = parse_numeric_value(component_value))
  3862. return numeric;
  3863. if (auto identifier = parse_identifier_value(component_value))
  3864. return identifier;
  3865. if (auto string = parse_string_value(component_value))
  3866. return string;
  3867. if (auto image = parse_image_value(component_value))
  3868. return image;
  3869. return {};
  3870. }
  3871. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values, AllowTrailingTokens allow_trailing_tokens)
  3872. {
  3873. int a = 0;
  3874. int b = 0;
  3875. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3876. if constexpr (CSS_PARSER_DEBUG) {
  3877. dbgln_if(CSS_PARSER_DEBUG, "Invalid An+B value:");
  3878. values.dump_all_tokens();
  3879. }
  3880. return {};
  3881. };
  3882. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3883. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  3884. values.skip_whitespace();
  3885. if (values.has_next_token() && allow_trailing_tokens == AllowTrailingTokens::No) {
  3886. if constexpr (CSS_PARSER_DEBUG) {
  3887. dbgln_if(CSS_PARSER_DEBUG, "Extra tokens at end of An+B value:");
  3888. values.dump_all_tokens();
  3889. }
  3890. return syntax_error();
  3891. } else {
  3892. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  3893. }
  3894. };
  3895. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  3896. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  3897. };
  3898. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  3899. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  3900. };
  3901. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  3902. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  3903. };
  3904. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  3905. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  3906. };
  3907. auto is_delim = [](StyleComponentValueRule const& value, u32 delim) -> bool {
  3908. return value.is(Token::Type::Delim) && value.token().delim() == delim;
  3909. };
  3910. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  3911. if (!value.is(Token::Type::Dimension))
  3912. return false;
  3913. if (!value.token().number().is_integer())
  3914. return false;
  3915. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  3916. return false;
  3917. return true;
  3918. };
  3919. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  3920. if (!value.is(Token::Type::Dimension))
  3921. return false;
  3922. if (!value.token().number().is_integer())
  3923. return false;
  3924. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  3925. return false;
  3926. return true;
  3927. };
  3928. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  3929. if (!value.is(Token::Type::Dimension))
  3930. return false;
  3931. if (!value.token().number().is_integer())
  3932. return false;
  3933. auto dimension_unit = value.token().dimension_unit();
  3934. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3935. return false;
  3936. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  3937. if (!is_ascii_digit(dimension_unit[i]))
  3938. return false;
  3939. }
  3940. return true;
  3941. };
  3942. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3943. if (!value.is(Token::Type::Ident))
  3944. return false;
  3945. auto ident = value.token().ident();
  3946. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3947. return false;
  3948. for (size_t i = 2; i < ident.length(); ++i) {
  3949. if (!is_ascii_digit(ident[i]))
  3950. return false;
  3951. }
  3952. return true;
  3953. };
  3954. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3955. if (!value.is(Token::Type::Ident))
  3956. return false;
  3957. auto ident = value.token().ident();
  3958. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  3959. return false;
  3960. for (size_t i = 3; i < ident.length(); ++i) {
  3961. if (!is_ascii_digit(ident[i]))
  3962. return false;
  3963. }
  3964. return true;
  3965. };
  3966. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  3967. return value.is(Token::Type::Number) && value.token().number().is_integer();
  3968. };
  3969. auto is_signed_integer = [](StyleComponentValueRule const& value) -> bool {
  3970. return value.is(Token::Type::Number) && value.token().number().is_integer_with_explicit_sign();
  3971. };
  3972. auto is_signless_integer = [](StyleComponentValueRule const& value) -> bool {
  3973. return value.is(Token::Type::Number) && !value.token().number().is_integer_with_explicit_sign();
  3974. };
  3975. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  3976. // Unfortunately these can't be in the same order as in the spec.
  3977. values.skip_whitespace();
  3978. auto& first_value = values.next_token();
  3979. // odd | even
  3980. if (first_value.is(Token::Type::Ident)) {
  3981. auto ident = first_value.token().ident();
  3982. if (ident.equals_ignoring_case("odd")) {
  3983. a = 2;
  3984. b = 1;
  3985. return make_return_value();
  3986. } else if (ident.equals_ignoring_case("even")) {
  3987. a = 2;
  3988. return make_return_value();
  3989. }
  3990. }
  3991. // <integer>
  3992. if (is_integer(first_value)) {
  3993. b = first_value.token().to_integer();
  3994. return make_return_value();
  3995. }
  3996. // <n-dimension>
  3997. // <n-dimension> <signed-integer>
  3998. // <n-dimension> ['+' | '-'] <signless-integer>
  3999. if (is_n_dimension(first_value)) {
  4000. a = first_value.token().dimension_value_int();
  4001. if (!values.has_next_token() || values.peek_token().is(Token::Type::Whitespace)) {
  4002. // <n-dimension>
  4003. return make_return_value();
  4004. }
  4005. values.skip_whitespace();
  4006. auto& second_value = values.next_token();
  4007. if (is_signed_integer(second_value)) {
  4008. // <n-dimension> <signed-integer>
  4009. b = second_value.token().to_integer();
  4010. return make_return_value();
  4011. }
  4012. values.skip_whitespace();
  4013. auto& third_value = values.next_token();
  4014. if ((is_delim(second_value, '+') || is_delim(second_value, '-')) && is_signless_integer(third_value)) {
  4015. // <n-dimension> ['+' | '-'] <signless-integer>
  4016. b = third_value.token().to_integer() * (is_delim(second_value, '+') ? 1 : -1);
  4017. return make_return_value();
  4018. }
  4019. return syntax_error();
  4020. }
  4021. // <ndash-dimension> <signless-integer>
  4022. if (is_ndash_dimension(first_value)) {
  4023. values.skip_whitespace();
  4024. auto& second_value = values.next_token();
  4025. if (is_signless_integer(second_value)) {
  4026. a = first_value.token().dimension_value_int();
  4027. b = -second_value.token().to_integer();
  4028. return make_return_value();
  4029. }
  4030. return syntax_error();
  4031. }
  4032. // <ndashdigit-dimension>
  4033. if (is_ndashdigit_dimension(first_value)) {
  4034. auto& dimension = first_value.token();
  4035. a = dimension.dimension_value_int();
  4036. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  4037. if (maybe_b.has_value()) {
  4038. b = maybe_b.value();
  4039. return make_return_value();
  4040. }
  4041. return syntax_error();
  4042. }
  4043. // <dashndashdigit-ident>
  4044. if (is_dashndashdigit_ident(first_value)) {
  4045. a = -1;
  4046. auto maybe_b = first_value.token().ident().substring_view(2).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. // -n
  4054. // -n <signed-integer>
  4055. // -n ['+' | '-'] <signless-integer>
  4056. if (is_dashn(first_value)) {
  4057. a = -1;
  4058. if (!values.has_next_token() || values.peek_token().is(Token::Type::Whitespace)) {
  4059. // -n
  4060. return make_return_value();
  4061. }
  4062. values.skip_whitespace();
  4063. auto& second_value = values.next_token();
  4064. if (is_signed_integer(second_value)) {
  4065. // -n <signed-integer>
  4066. b = second_value.token().to_integer();
  4067. return make_return_value();
  4068. }
  4069. values.skip_whitespace();
  4070. auto& third_value = values.next_token();
  4071. if ((is_delim(second_value, '+') || is_delim(second_value, '-')) && is_signless_integer(third_value)) {
  4072. // -n ['+' | '-'] <signless-integer>
  4073. b = third_value.token().to_integer() * (is_delim(second_value, '+') ? 1 : -1);
  4074. return make_return_value();
  4075. }
  4076. return syntax_error();
  4077. }
  4078. // -n- <signless-integer>
  4079. if (is_dashndash(first_value)) {
  4080. values.skip_whitespace();
  4081. auto& second_value = values.next_token();
  4082. if (is_signless_integer(second_value)) {
  4083. a = -1;
  4084. b = -second_value.token().to_integer();
  4085. return make_return_value();
  4086. }
  4087. return syntax_error();
  4088. }
  4089. // All that's left now are these:
  4090. // '+'?† n
  4091. // '+'?† n <signed-integer>
  4092. // '+'?† n ['+' | '-'] <signless-integer>
  4093. // '+'?† n- <signless-integer>
  4094. // '+'?† <ndashdigit-ident>
  4095. // In all of these cases, the + is optional, and has no effect.
  4096. // So, we just skip the +, and carry on.
  4097. if (!is_delim(first_value, '+')) {
  4098. values.reconsume_current_input_token();
  4099. // We do *not* skip whitespace here.
  4100. }
  4101. auto& first_after_plus = values.next_token();
  4102. // '+'?† n
  4103. // '+'?† n <signed-integer>
  4104. // '+'?† n ['+' | '-'] <signless-integer>
  4105. if (is_n(first_after_plus)) {
  4106. a = 1;
  4107. if (!values.has_next_token() || values.peek_token().is(Token::Type::Whitespace)) {
  4108. // '+'?† n
  4109. return make_return_value();
  4110. }
  4111. values.skip_whitespace();
  4112. auto& second_value = values.next_token();
  4113. if (is_signed_integer(second_value)) {
  4114. // '+'?† n <signed-integer>
  4115. b = second_value.token().to_integer();
  4116. return make_return_value();
  4117. }
  4118. values.skip_whitespace();
  4119. auto& third_value = values.next_token();
  4120. if ((is_delim(second_value, '+') || is_delim(second_value, '-')) && is_signless_integer(third_value)) {
  4121. // '+'?† n ['+' | '-'] <signless-integer>
  4122. b = third_value.token().to_integer() * (is_delim(second_value, '+') ? 1 : -1);
  4123. return make_return_value();
  4124. }
  4125. return syntax_error();
  4126. }
  4127. // '+'?† n- <signless-integer>
  4128. if (is_ndash(first_after_plus)) {
  4129. values.skip_whitespace();
  4130. auto& second_value = values.next_token();
  4131. if (is_signless_integer(second_value)) {
  4132. a = 1;
  4133. b = -second_value.token().to_integer();
  4134. return make_return_value();
  4135. }
  4136. return syntax_error();
  4137. }
  4138. // '+'?† <ndashdigit-ident>
  4139. if (is_ndashdigit_ident(first_after_plus)) {
  4140. a = 1;
  4141. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  4142. if (maybe_b.has_value()) {
  4143. b = maybe_b.value();
  4144. return make_return_value();
  4145. }
  4146. return syntax_error();
  4147. }
  4148. return syntax_error();
  4149. }
  4150. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(Vector<StyleComponentValueRule> const& values)
  4151. {
  4152. auto tokens = TokenStream(values);
  4153. return parse_calc_sum(tokens);
  4154. }
  4155. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(TokenStream<StyleComponentValueRule>& tokens)
  4156. {
  4157. auto current_token = tokens.next_token();
  4158. if (current_token.is_block() && current_token.block().is_paren()) {
  4159. auto block_values = TokenStream(current_token.block().values());
  4160. auto parsed_calc_sum = parse_calc_sum(block_values);
  4161. if (!parsed_calc_sum)
  4162. return {};
  4163. return CalculatedStyleValue::CalcValue { parsed_calc_sum.release_nonnull() };
  4164. }
  4165. if (current_token.is(Token::Type::Number))
  4166. return CalculatedStyleValue::CalcValue { current_token.token().number() };
  4167. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  4168. auto maybe_dimension = parse_dimension(current_token);
  4169. if (!maybe_dimension.has_value())
  4170. return {};
  4171. auto& dimension = maybe_dimension.value();
  4172. if (dimension.is_angle())
  4173. return CalculatedStyleValue::CalcValue { dimension.angle() };
  4174. if (dimension.is_frequency())
  4175. return CalculatedStyleValue::CalcValue { dimension.frequency() };
  4176. if (dimension.is_length())
  4177. return CalculatedStyleValue::CalcValue { dimension.length() };
  4178. if (dimension.is_percentage())
  4179. return CalculatedStyleValue::CalcValue { dimension.percentage() };
  4180. if (dimension.is_resolution()) {
  4181. // Resolution is not allowed in calc()
  4182. return {};
  4183. }
  4184. if (dimension.is_time())
  4185. return CalculatedStyleValue::CalcValue { dimension.time() };
  4186. VERIFY_NOT_REACHED();
  4187. }
  4188. return {};
  4189. }
  4190. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  4191. {
  4192. // Note: The default value is not used or passed around.
  4193. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  4194. CalculatedStyleValue::ProductOperation::Multiply,
  4195. CalculatedStyleValue::CalcNumberValue { Number {} });
  4196. tokens.skip_whitespace();
  4197. auto& op_token = tokens.peek_token();
  4198. if (!op_token.is(Token::Type::Delim))
  4199. return nullptr;
  4200. auto op = op_token.token().delim();
  4201. if (op == '*') {
  4202. tokens.next_token();
  4203. tokens.skip_whitespace();
  4204. product_with_operator->op = CalculatedStyleValue::ProductOperation::Multiply;
  4205. auto parsed_calc_value = parse_calc_value(tokens);
  4206. if (!parsed_calc_value.has_value())
  4207. return nullptr;
  4208. product_with_operator->value = { parsed_calc_value.release_value() };
  4209. } else if (op == '/') {
  4210. // FIXME: Detect divide-by-zero if possible
  4211. tokens.next_token();
  4212. tokens.skip_whitespace();
  4213. product_with_operator->op = CalculatedStyleValue::ProductOperation::Divide;
  4214. auto parsed_calc_number_value = parse_calc_number_value(tokens);
  4215. if (!parsed_calc_number_value.has_value())
  4216. return nullptr;
  4217. product_with_operator->value = { parsed_calc_number_value.release_value() };
  4218. } else {
  4219. return nullptr;
  4220. }
  4221. return product_with_operator;
  4222. }
  4223. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  4224. {
  4225. // Note: The default value is not used or passed around.
  4226. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  4227. CalculatedStyleValue::ProductOperation::Multiply,
  4228. CalculatedStyleValue::CalcNumberValue { Number {} });
  4229. tokens.skip_whitespace();
  4230. auto& op_token = tokens.peek_token();
  4231. if (!op_token.is(Token::Type::Delim))
  4232. return nullptr;
  4233. auto op = op_token.token().delim();
  4234. if (op == '*') {
  4235. tokens.next_token();
  4236. tokens.skip_whitespace();
  4237. number_product_with_operator->op = CalculatedStyleValue::ProductOperation::Multiply;
  4238. } else if (op == '/') {
  4239. // FIXME: Detect divide-by-zero if possible
  4240. tokens.next_token();
  4241. tokens.skip_whitespace();
  4242. number_product_with_operator->op = CalculatedStyleValue::ProductOperation::Divide;
  4243. } else {
  4244. return nullptr;
  4245. }
  4246. auto parsed_calc_value = parse_calc_number_value(tokens);
  4247. if (!parsed_calc_value.has_value())
  4248. return nullptr;
  4249. number_product_with_operator->value = parsed_calc_value.release_value();
  4250. return number_product_with_operator;
  4251. }
  4252. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(TokenStream<StyleComponentValueRule>& tokens)
  4253. {
  4254. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  4255. CalculatedStyleValue::CalcNumberValue { Number {} },
  4256. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  4257. auto first_calc_number_value_or_error = parse_calc_number_value(tokens);
  4258. if (!first_calc_number_value_or_error.has_value())
  4259. return nullptr;
  4260. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  4261. while (tokens.has_next_token()) {
  4262. auto number_product_with_operator = parse_calc_number_product_part_with_operator(tokens);
  4263. if (!number_product_with_operator)
  4264. break;
  4265. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  4266. }
  4267. return calc_number_product;
  4268. }
  4269. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  4270. {
  4271. if (!(tokens.peek_token().is(Token::Type::Delim)
  4272. && (tokens.peek_token().token().delim() == '+' || tokens.peek_token().token().delim() == '-')
  4273. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  4274. return nullptr;
  4275. auto& token = tokens.next_token();
  4276. tokens.skip_whitespace();
  4277. CalculatedStyleValue::SumOperation op;
  4278. auto delim = token.token().delim();
  4279. if (delim == '+')
  4280. op = CalculatedStyleValue::SumOperation::Add;
  4281. else if (delim == '-')
  4282. op = CalculatedStyleValue::SumOperation::Subtract;
  4283. else
  4284. return nullptr;
  4285. auto calc_number_product = parse_calc_number_product(tokens);
  4286. if (!calc_number_product)
  4287. return nullptr;
  4288. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  4289. }
  4290. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(TokenStream<StyleComponentValueRule>& tokens)
  4291. {
  4292. auto first_calc_number_product_or_error = parse_calc_number_product(tokens);
  4293. if (!first_calc_number_product_or_error)
  4294. return nullptr;
  4295. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  4296. while (tokens.has_next_token()) {
  4297. auto calc_sum_part = parse_calc_number_sum_part_with_operator(tokens);
  4298. if (!calc_sum_part)
  4299. return nullptr;
  4300. additional.append(calc_sum_part.release_nonnull());
  4301. }
  4302. tokens.skip_whitespace();
  4303. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  4304. return calc_number_sum;
  4305. }
  4306. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(TokenStream<StyleComponentValueRule>& tokens)
  4307. {
  4308. auto& first = tokens.peek_token();
  4309. if (first.is_block() && first.block().is_paren()) {
  4310. tokens.next_token();
  4311. auto block_values = TokenStream(first.block().values());
  4312. auto calc_number_sum = parse_calc_number_sum(block_values);
  4313. if (calc_number_sum)
  4314. return CalculatedStyleValue::CalcNumberValue { calc_number_sum.release_nonnull() };
  4315. }
  4316. if (!first.is(Token::Type::Number))
  4317. return {};
  4318. tokens.next_token();
  4319. return CalculatedStyleValue::CalcNumberValue { first.token().number() };
  4320. }
  4321. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(TokenStream<StyleComponentValueRule>& tokens)
  4322. {
  4323. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  4324. CalculatedStyleValue::CalcValue { Number {} },
  4325. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  4326. auto first_calc_value_or_error = parse_calc_value(tokens);
  4327. if (!first_calc_value_or_error.has_value())
  4328. return nullptr;
  4329. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  4330. while (tokens.has_next_token()) {
  4331. auto product_with_operator = parse_calc_product_part_with_operator(tokens);
  4332. if (!product_with_operator)
  4333. break;
  4334. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  4335. }
  4336. return calc_product;
  4337. }
  4338. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  4339. {
  4340. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  4341. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  4342. if (!(tokens.peek_token().is(Token::Type::Delim)
  4343. && (tokens.peek_token().token().delim() == '+' || tokens.peek_token().token().delim() == '-')
  4344. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  4345. return nullptr;
  4346. auto& token = tokens.next_token();
  4347. tokens.skip_whitespace();
  4348. CalculatedStyleValue::SumOperation op;
  4349. auto delim = token.token().delim();
  4350. if (delim == '+')
  4351. op = CalculatedStyleValue::SumOperation::Add;
  4352. else if (delim == '-')
  4353. op = CalculatedStyleValue::SumOperation::Subtract;
  4354. else
  4355. return nullptr;
  4356. auto calc_product = parse_calc_product(tokens);
  4357. if (!calc_product)
  4358. return nullptr;
  4359. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  4360. };
  4361. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(TokenStream<StyleComponentValueRule>& tokens)
  4362. {
  4363. auto parsed_calc_product = parse_calc_product(tokens);
  4364. if (!parsed_calc_product)
  4365. return nullptr;
  4366. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  4367. while (tokens.has_next_token()) {
  4368. auto calc_sum_part = parse_calc_sum_part_with_operator(tokens);
  4369. if (!calc_sum_part)
  4370. return nullptr;
  4371. additional.append(calc_sum_part.release_nonnull());
  4372. }
  4373. tokens.skip_whitespace();
  4374. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  4375. }
  4376. bool Parser::has_ignored_vendor_prefix(StringView string)
  4377. {
  4378. if (!string.starts_with('-'))
  4379. return false;
  4380. if (string.starts_with("--"))
  4381. return false;
  4382. if (string.starts_with("-libweb-"))
  4383. return false;
  4384. return true;
  4385. }
  4386. bool Parser::is_builtin(StringView name)
  4387. {
  4388. return name.equals_ignoring_case("inherit"sv)
  4389. || name.equals_ignoring_case("initial"sv)
  4390. || name.equals_ignoring_case("unset"sv);
  4391. }
  4392. RefPtr<StyleValue> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext const& context, PropertyID property_id, Vector<StyleComponentValueRule> const& tokens)
  4393. {
  4394. if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
  4395. return {};
  4396. CSS::Parser parser(context, "");
  4397. CSS::TokenStream<CSS::StyleComponentValueRule> token_stream { tokens };
  4398. auto result = parser.parse_css_value(property_id, token_stream);
  4399. if (result.is_error())
  4400. return {};
  4401. return result.release_value();
  4402. }
  4403. bool Parser::Dimension::is_angle() const
  4404. {
  4405. return m_value.has<Angle>();
  4406. }
  4407. Angle Parser::Dimension::angle() const
  4408. {
  4409. return m_value.get<Angle>();
  4410. }
  4411. bool Parser::Dimension::is_angle_percentage() const
  4412. {
  4413. return is_angle() || is_percentage();
  4414. }
  4415. AnglePercentage Parser::Dimension::angle_percentage() const
  4416. {
  4417. if (is_angle())
  4418. return angle();
  4419. if (is_percentage())
  4420. return percentage();
  4421. VERIFY_NOT_REACHED();
  4422. }
  4423. bool Parser::Dimension::is_frequency() const
  4424. {
  4425. return m_value.has<Frequency>();
  4426. }
  4427. Frequency Parser::Dimension::frequency() const
  4428. {
  4429. return m_value.get<Frequency>();
  4430. }
  4431. bool Parser::Dimension::is_frequency_percentage() const
  4432. {
  4433. return is_frequency() || is_percentage();
  4434. }
  4435. FrequencyPercentage Parser::Dimension::frequency_percentage() const
  4436. {
  4437. if (is_frequency())
  4438. return frequency();
  4439. if (is_percentage())
  4440. return percentage();
  4441. VERIFY_NOT_REACHED();
  4442. }
  4443. bool Parser::Dimension::is_length() const
  4444. {
  4445. return m_value.has<Length>();
  4446. }
  4447. Length Parser::Dimension::length() const
  4448. {
  4449. return m_value.get<Length>();
  4450. }
  4451. bool Parser::Dimension::is_length_percentage() const
  4452. {
  4453. return is_length() || is_percentage();
  4454. }
  4455. LengthPercentage Parser::Dimension::length_percentage() const
  4456. {
  4457. if (is_length())
  4458. return length();
  4459. if (is_percentage())
  4460. return percentage();
  4461. VERIFY_NOT_REACHED();
  4462. }
  4463. bool Parser::Dimension::is_percentage() const
  4464. {
  4465. return m_value.has<Percentage>();
  4466. }
  4467. Percentage Parser::Dimension::percentage() const
  4468. {
  4469. return m_value.get<Percentage>();
  4470. }
  4471. bool Parser::Dimension::is_resolution() const
  4472. {
  4473. return m_value.has<Resolution>();
  4474. }
  4475. Resolution Parser::Dimension::resolution() const
  4476. {
  4477. return m_value.get<Resolution>();
  4478. }
  4479. bool Parser::Dimension::is_time() const
  4480. {
  4481. return m_value.has<Time>();
  4482. }
  4483. Time Parser::Dimension::time() const
  4484. {
  4485. return m_value.get<Time>();
  4486. }
  4487. bool Parser::Dimension::is_time_percentage() const
  4488. {
  4489. return is_time() || is_percentage();
  4490. }
  4491. TimePercentage Parser::Dimension::time_percentage() const
  4492. {
  4493. if (is_time())
  4494. return time();
  4495. if (is_percentage())
  4496. return percentage();
  4497. VERIFY_NOT_REACHED();
  4498. }
  4499. }
  4500. namespace Web {
  4501. RefPtr<CSS::CSSStyleSheet> parse_css_stylesheet(CSS::ParsingContext const& context, StringView css, Optional<AK::URL> location)
  4502. {
  4503. if (css.is_empty())
  4504. return CSS::CSSStyleSheet::create({}, location);
  4505. CSS::Parser parser(context, css);
  4506. return parser.parse_as_css_stylesheet(location);
  4507. }
  4508. RefPtr<CSS::ElementInlineCSSStyleDeclaration> parse_css_style_attribute(CSS::ParsingContext const& context, StringView css, DOM::Element& element)
  4509. {
  4510. if (css.is_empty())
  4511. return CSS::ElementInlineCSSStyleDeclaration::create(element, {}, {});
  4512. CSS::Parser parser(context, css);
  4513. return parser.parse_as_style_attribute(element);
  4514. }
  4515. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
  4516. {
  4517. if (string.is_empty())
  4518. return {};
  4519. CSS::Parser parser(context, string);
  4520. return parser.parse_as_css_value(property_id);
  4521. }
  4522. RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
  4523. {
  4524. CSS::Parser parser(context, css_text);
  4525. return parser.parse_as_rule();
  4526. }
  4527. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView selector_text)
  4528. {
  4529. CSS::Parser parser(context, selector_text);
  4530. return parser.parse_as_selector();
  4531. }
  4532. RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView string)
  4533. {
  4534. CSS::Parser parser(context, string);
  4535. return parser.parse_as_media_query();
  4536. }
  4537. NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView string)
  4538. {
  4539. CSS::Parser parser(context, string);
  4540. return parser.parse_as_media_query_list();
  4541. }
  4542. RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const& context, StringView string)
  4543. {
  4544. if (string.is_empty())
  4545. return {};
  4546. CSS::Parser parser(context, string);
  4547. return parser.parse_as_supports();
  4548. }
  4549. }