Parser.cpp 202 KB

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