IDLGenerators.cpp 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2023, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  6. * Copyright (c) 2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "Namespaces.h"
  11. #include <AK/LexicalPath.h>
  12. #include <AK/Queue.h>
  13. #include <AK/QuickSort.h>
  14. #include <LibIDL/Types.h>
  15. Vector<StringView> s_header_search_paths;
  16. namespace IDL {
  17. // FIXME: Generate this automatically somehow.
  18. static bool is_platform_object(Type const& type)
  19. {
  20. // NOTE: This is a hand-curated subset of platform object types that are actually relevant
  21. // in places where this function is used. If you add IDL code and get compile errors, you
  22. // might simply need to add another type here.
  23. static constexpr Array types = {
  24. "AbortSignal"sv,
  25. "Attr"sv,
  26. "Blob"sv,
  27. "CanvasGradient"sv,
  28. "CanvasPattern"sv,
  29. "CanvasRenderingContext2D"sv,
  30. "Document"sv,
  31. "DocumentType"sv,
  32. "EventTarget"sv,
  33. "FileList"sv,
  34. "FormData"sv,
  35. "ImageData"sv,
  36. "Instance"sv,
  37. "Memory"sv,
  38. "Module"sv,
  39. "MutationRecord"sv,
  40. "NamedNodeMap"sv,
  41. "Node"sv,
  42. "Path2D"sv,
  43. "PerformanceEntry"sv,
  44. "PerformanceMark"sv,
  45. "Range"sv,
  46. "ReadableStream"sv,
  47. "Request"sv,
  48. "Selection"sv,
  49. "Table"sv,
  50. "Text"sv,
  51. "TextMetrics"sv,
  52. "URLSearchParams"sv,
  53. "WebGLRenderingContext"sv,
  54. "Window"sv,
  55. };
  56. if (type.name().ends_with("Element"sv))
  57. return true;
  58. if (type.name().ends_with("Event"sv))
  59. return true;
  60. if (types.span().contains_slow(type.name()))
  61. return true;
  62. return false;
  63. }
  64. // FIXME: Generate this automatically somehow.
  65. static bool is_javascript_builtin(Type const& type)
  66. {
  67. // NOTE: This is a hand-curated subset of JavaScript built-in types that are actually relevant
  68. // in places where this function is used. If you add IDL code and get compile errors, you
  69. // might simply need to add another type here.
  70. static constexpr Array types = {
  71. "ArrayBuffer"sv,
  72. };
  73. return types.span().contains_slow(type.name());
  74. }
  75. static StringView sequence_storage_type_to_cpp_storage_type_name(SequenceStorageType sequence_storage_type)
  76. {
  77. switch (sequence_storage_type) {
  78. case SequenceStorageType::Vector:
  79. return "Vector"sv;
  80. case SequenceStorageType::MarkedVector:
  81. return "JS::MarkedVector"sv;
  82. default:
  83. VERIFY_NOT_REACHED();
  84. }
  85. }
  86. CppType idl_type_name_to_cpp_type(Type const& type, Interface const& interface);
  87. static DeprecatedString union_type_to_variant(UnionType const& union_type, Interface const& interface)
  88. {
  89. StringBuilder builder;
  90. builder.append("Variant<"sv);
  91. auto flattened_types = union_type.flattened_member_types();
  92. for (size_t type_index = 0; type_index < flattened_types.size(); ++type_index) {
  93. auto& type = flattened_types.at(type_index);
  94. if (type_index > 0)
  95. builder.append(", "sv);
  96. auto cpp_type = idl_type_name_to_cpp_type(type, interface);
  97. builder.append(cpp_type.name);
  98. }
  99. if (union_type.includes_undefined())
  100. builder.append(", Empty"sv);
  101. builder.append('>');
  102. return builder.to_deprecated_string();
  103. }
  104. CppType idl_type_name_to_cpp_type(Type const& type, Interface const& interface)
  105. {
  106. if (is_platform_object(type))
  107. return { .name = DeprecatedString::formatted("JS::Handle<{}>", type.name()), .sequence_storage_type = SequenceStorageType::MarkedVector };
  108. if (type.is_string()) {
  109. if (interface.extended_attributes.contains("UseNewAKString"))
  110. return { .name = "String", .sequence_storage_type = SequenceStorageType::Vector };
  111. return { .name = "DeprecatedString", .sequence_storage_type = SequenceStorageType::Vector };
  112. }
  113. if (type.name() == "double" && !type.is_nullable())
  114. return { .name = "double", .sequence_storage_type = SequenceStorageType::Vector };
  115. if (type.name() == "float" && !type.is_nullable())
  116. return { .name = "float", .sequence_storage_type = SequenceStorageType::Vector };
  117. if (type.name() == "boolean" && !type.is_nullable())
  118. return { .name = "bool", .sequence_storage_type = SequenceStorageType::Vector };
  119. if (type.name() == "unsigned long" && !type.is_nullable())
  120. return { .name = "u32", .sequence_storage_type = SequenceStorageType::Vector };
  121. if (type.name() == "unsigned short" && !type.is_nullable())
  122. return { .name = "u16", .sequence_storage_type = SequenceStorageType::Vector };
  123. if (type.name() == "long long" && !type.is_nullable())
  124. return { .name = "i64", .sequence_storage_type = SequenceStorageType::Vector };
  125. if (type.name() == "unsigned long long" && !type.is_nullable())
  126. return { .name = "u64", .sequence_storage_type = SequenceStorageType::Vector };
  127. if (type.name() == "long" && !type.is_nullable())
  128. return { .name = "i32", .sequence_storage_type = SequenceStorageType::Vector };
  129. if (type.name() == "any" || type.name() == "undefined")
  130. return { .name = "JS::Value", .sequence_storage_type = SequenceStorageType::MarkedVector };
  131. if (type.name() == "object")
  132. return { .name = "JS::Handle<JS::Object>", .sequence_storage_type = SequenceStorageType::Vector };
  133. if (type.name() == "BufferSource")
  134. return { .name = "JS::Handle<JS::Object>", .sequence_storage_type = SequenceStorageType::MarkedVector };
  135. if (type.name() == "File")
  136. return { .name = "JS::Handle<FileAPI::File>", .sequence_storage_type = SequenceStorageType::MarkedVector };
  137. if (type.name() == "Function")
  138. return { .name = "JS::Handle<WebIDL::CallbackType>", .sequence_storage_type = SequenceStorageType::MarkedVector };
  139. if (type.name() == "sequence") {
  140. auto& parameterized_type = verify_cast<ParameterizedType>(type);
  141. auto& sequence_type = parameterized_type.parameters().first();
  142. auto sequence_cpp_type = idl_type_name_to_cpp_type(sequence_type, interface);
  143. auto storage_type_name = sequence_storage_type_to_cpp_storage_type_name(sequence_cpp_type.sequence_storage_type);
  144. if (sequence_cpp_type.sequence_storage_type == SequenceStorageType::MarkedVector)
  145. return { .name = storage_type_name, .sequence_storage_type = SequenceStorageType::Vector };
  146. return { .name = DeprecatedString::formatted("{}<{}>", storage_type_name, sequence_cpp_type.name), .sequence_storage_type = SequenceStorageType::Vector };
  147. }
  148. if (type.name() == "record") {
  149. auto& parameterized_type = verify_cast<ParameterizedType>(type);
  150. auto& record_key_type = parameterized_type.parameters()[0];
  151. auto& record_value_type = parameterized_type.parameters()[1];
  152. auto record_key_cpp_type = idl_type_name_to_cpp_type(record_key_type, interface);
  153. auto record_value_cpp_type = idl_type_name_to_cpp_type(record_value_type, interface);
  154. return { .name = DeprecatedString::formatted("OrderedHashMap<{}, {}>", record_key_cpp_type.name, record_value_cpp_type.name), .sequence_storage_type = SequenceStorageType::Vector };
  155. }
  156. if (is<UnionType>(type)) {
  157. auto& union_type = verify_cast<UnionType>(type);
  158. return { .name = union_type_to_variant(union_type, interface), .sequence_storage_type = SequenceStorageType::Vector };
  159. }
  160. if (!type.is_nullable()) {
  161. for (auto& dictionary : interface.dictionaries) {
  162. if (type.name() == dictionary.key)
  163. return { .name = type.name(), .sequence_storage_type = SequenceStorageType::Vector };
  164. }
  165. }
  166. dbgln("Unimplemented type for idl_type_name_to_cpp_type: {}{}", type.name(), type.is_nullable() ? "?" : "");
  167. TODO();
  168. }
  169. static DeprecatedString make_input_acceptable_cpp(DeprecatedString const& input)
  170. {
  171. if (input.is_one_of("class", "template", "for", "default", "char", "namespace", "delete", "inline")) {
  172. StringBuilder builder;
  173. builder.append(input);
  174. builder.append('_');
  175. return builder.to_deprecated_string();
  176. }
  177. return input.replace("-"sv, "_"sv, ReplaceMode::All);
  178. }
  179. static void generate_include_for_iterator(auto& generator, auto& iterator_path)
  180. {
  181. auto iterator_generator = generator.fork();
  182. iterator_generator.set("iterator_class.path", iterator_path);
  183. // FIXME: These may or may not exist, because REASONS.
  184. iterator_generator.append(R"~~~(
  185. //#if __has_include(<LibWeb/@iterator_class.path@.h>)
  186. # include <LibWeb/@iterator_class.path@.h>
  187. //#endif
  188. )~~~");
  189. }
  190. static void generate_include_for(auto& generator, auto& path)
  191. {
  192. auto forked_generator = generator.fork();
  193. auto path_string = path;
  194. for (auto& search_path : s_header_search_paths) {
  195. if (!path.starts_with(search_path))
  196. continue;
  197. auto relative_path = LexicalPath::relative_path(path, search_path);
  198. if (relative_path.length() < path_string.length())
  199. path_string = relative_path;
  200. }
  201. LexicalPath include_path { path_string };
  202. forked_generator.set("include.path", DeprecatedString::formatted("{}/{}.h", include_path.dirname(), include_path.title()));
  203. forked_generator.append(R"~~~(
  204. #include <@include.path@>
  205. )~~~");
  206. }
  207. static void emit_includes_for_all_imports(auto& interface, auto& generator, bool is_iterator = false)
  208. {
  209. Queue<RemoveCVReference<decltype(interface)> const*> interfaces;
  210. HashTable<DeprecatedString> paths_imported;
  211. interfaces.enqueue(&interface);
  212. while (!interfaces.is_empty()) {
  213. auto interface = interfaces.dequeue();
  214. if (paths_imported.contains(interface->module_own_path))
  215. continue;
  216. paths_imported.set(interface->module_own_path);
  217. for (auto& imported_interface : interface->imported_modules) {
  218. if (!paths_imported.contains(imported_interface.module_own_path))
  219. interfaces.enqueue(&imported_interface);
  220. }
  221. if (!interface->will_generate_code())
  222. continue;
  223. generate_include_for(generator, interface->module_own_path);
  224. }
  225. if (is_iterator) {
  226. auto iterator_path = DeprecatedString::formatted("{}Iterator", interface.fully_qualified_name.replace("::"sv, "/"sv, ReplaceMode::All));
  227. generate_include_for_iterator(generator, iterator_path);
  228. }
  229. }
  230. template<typename ParameterType>
  231. static void generate_to_deprecated_string(SourceGenerator& scoped_generator, ParameterType const& parameter, bool variadic, bool optional, Optional<DeprecatedString> const& optional_default_value)
  232. {
  233. if (variadic) {
  234. scoped_generator.append(R"~~~(
  235. Vector<DeprecatedString> @cpp_name@;
  236. if (vm.argument_count() > @js_suffix@) {
  237. TRY_OR_THROW_OOM(vm, @cpp_name@.try_ensure_capacity(vm.argument_count() - @js_suffix@));
  238. for (size_t i = @js_suffix@; i < vm.argument_count(); ++i) {
  239. auto to_string_result = TRY(vm.argument(i).to_deprecated_string(vm));
  240. @cpp_name@.unchecked_append(move(to_string_result));
  241. }
  242. }
  243. )~~~");
  244. } else if (!optional) {
  245. if (!parameter.type->is_nullable()) {
  246. scoped_generator.append(R"~~~(
  247. DeprecatedString @cpp_name@;
  248. if (@js_name@@js_suffix@.is_null() && @legacy_null_to_empty_string@) {
  249. @cpp_name@ = DeprecatedString::empty();
  250. } else {
  251. @cpp_name@ = TRY(@js_name@@js_suffix@.to_deprecated_string(vm));
  252. }
  253. )~~~");
  254. } else {
  255. scoped_generator.append(R"~~~(
  256. DeprecatedString @cpp_name@;
  257. if (!@js_name@@js_suffix@.is_nullish())
  258. @cpp_name@ = TRY(@js_name@@js_suffix@.to_deprecated_string(vm));
  259. )~~~");
  260. }
  261. } else {
  262. scoped_generator.append(R"~~~(
  263. DeprecatedString @cpp_name@;
  264. if (!@js_name@@js_suffix@.is_undefined()) {
  265. if (@js_name@@js_suffix@.is_null() && @legacy_null_to_empty_string@)
  266. @cpp_name@ = DeprecatedString::empty();
  267. else
  268. @cpp_name@ = TRY(@js_name@@js_suffix@.to_deprecated_string(vm));
  269. })~~~");
  270. if (optional_default_value.has_value() && (!parameter.type->is_nullable() || optional_default_value.value() != "null")) {
  271. scoped_generator.append(R"~~~( else {
  272. @cpp_name@ = @parameter.optional_default_value@;
  273. }
  274. )~~~");
  275. } else {
  276. scoped_generator.append(R"~~~(
  277. )~~~");
  278. }
  279. }
  280. }
  281. template<typename ParameterType>
  282. static void generate_to_new_string(SourceGenerator& scoped_generator, ParameterType const& parameter, bool variadic, bool optional, Optional<DeprecatedString> const& optional_default_value)
  283. {
  284. if (variadic) {
  285. scoped_generator.append(R"~~~(
  286. Vector<String> @cpp_name@;
  287. if (vm.argument_count() > @js_suffix@) {
  288. TRY_OR_THROW_OOM(vm, @cpp_name@.try_ensure_capacity(vm.argument_count() - @js_suffix@));
  289. for (size_t i = @js_suffix@; i < vm.argument_count(); ++i) {
  290. auto to_string_result = TRY(vm.argument(i).to_string(vm));
  291. @cpp_name@.unchecked_append(move(to_string_result));
  292. }
  293. }
  294. )~~~");
  295. } else if (!optional) {
  296. if (!parameter.type->is_nullable()) {
  297. scoped_generator.append(R"~~~(
  298. String @cpp_name@;
  299. if (!@legacy_null_to_empty_string@ || !@js_name@@js_suffix@.is_null()) {
  300. @cpp_name@ = TRY(@js_name@@js_suffix@.to_string(vm));
  301. }
  302. )~~~");
  303. } else {
  304. scoped_generator.append(R"~~~(
  305. Optional<String> @cpp_name@;
  306. if (!@js_name@@js_suffix@.is_nullish())
  307. @cpp_name@ = TRY(@js_name@@js_suffix@.to_string(vm));
  308. )~~~");
  309. }
  310. } else {
  311. scoped_generator.append(R"~~~(
  312. Optional<String> @cpp_name@;
  313. if (!@js_name@@js_suffix@.is_undefined()) {
  314. if (!@legacy_null_to_empty_string@ || !@js_name@@js_suffix@.is_null())
  315. @cpp_name@ = TRY(@js_name@@js_suffix@.to_string(vm));
  316. })~~~");
  317. if (optional_default_value.has_value() && (!parameter.type->is_nullable() || optional_default_value.value() != "null")) {
  318. scoped_generator.append(R"~~~( else {
  319. @cpp_name@ = TRY_OR_THROW_OOM(vm, String::from_utf8(@parameter.optional_default_value@sv));
  320. }
  321. )~~~");
  322. } else {
  323. scoped_generator.append(R"~~~(
  324. )~~~");
  325. }
  326. }
  327. }
  328. template<typename ParameterType>
  329. static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter, DeprecatedString const& js_name, DeprecatedString const& js_suffix, DeprecatedString const& cpp_name, IDL::Interface const& interface, bool legacy_null_to_empty_string = false, bool optional = false, Optional<DeprecatedString> optional_default_value = {}, bool variadic = false, size_t recursion_depth = 0)
  330. {
  331. auto scoped_generator = generator.fork();
  332. auto acceptable_cpp_name = make_input_acceptable_cpp(cpp_name);
  333. scoped_generator.set("cpp_name", acceptable_cpp_name);
  334. scoped_generator.set("js_name", js_name);
  335. scoped_generator.set("js_suffix", js_suffix);
  336. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  337. scoped_generator.set("parameter.type.name", parameter.type->name());
  338. if (optional_default_value.has_value())
  339. scoped_generator.set("parameter.optional_default_value", *optional_default_value);
  340. // FIXME: Add support for optional, variadic, nullable and default values to all types
  341. if (parameter.type->is_string()) {
  342. bool use_new_ak_string = interface.extended_attributes.contains("UseNewAKString");
  343. if (!use_new_ak_string)
  344. generate_to_deprecated_string(scoped_generator, parameter, variadic, optional, optional_default_value);
  345. else
  346. generate_to_new_string(scoped_generator, parameter, variadic, optional, optional_default_value);
  347. } else if (parameter.type->name().is_one_of("EventListener", "NodeFilter")) {
  348. // FIXME: Replace this with support for callback interfaces. https://webidl.spec.whatwg.org/#idl-callback-interface
  349. if (parameter.type->name() == "EventListener")
  350. scoped_generator.set("cpp_type", "IDLEventListener");
  351. else
  352. scoped_generator.set("cpp_type", parameter.type->name());
  353. if (parameter.type->is_nullable()) {
  354. scoped_generator.append(R"~~~(
  355. @cpp_type@* @cpp_name@ = nullptr;
  356. if (!@js_name@@js_suffix@.is_nullish()) {
  357. if (!@js_name@@js_suffix@.is_object())
  358. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, TRY_OR_THROW_OOM(vm, @js_name@@js_suffix@.to_string_without_side_effects()));
  359. auto callback_type = vm.heap().allocate_without_realm<WebIDL::CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
  360. @cpp_name@ = TRY(throw_dom_exception_if_needed(vm, [&] { return @cpp_type@::create(realm, *callback_type); }));
  361. }
  362. )~~~");
  363. } else {
  364. scoped_generator.append(R"~~~(
  365. if (!@js_name@@js_suffix@.is_object())
  366. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, TRY_OR_THROW_OOM(vm, @js_name@@js_suffix@.to_string_without_side_effects()));
  367. auto callback_type = vm.heap().allocate_without_realm<WebIDL::CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
  368. auto @cpp_name@ = adopt_ref(*new @cpp_type@(callback_type));
  369. )~~~");
  370. }
  371. } else if (IDL::is_platform_object(*parameter.type)) {
  372. if (!parameter.type->is_nullable()) {
  373. if (!optional) {
  374. scoped_generator.append(R"~~~(
  375. if (!@js_name@@js_suffix@.is_object() || !is<@parameter.type.name@>(@js_name@@js_suffix@.as_object()))
  376. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  377. auto& @cpp_name@ = static_cast<@parameter.type.name@&>(@js_name@@js_suffix@.as_object());
  378. )~~~");
  379. } else {
  380. scoped_generator.append(R"~~~(
  381. Optional<JS::NonnullGCPtr<@parameter.type.name@>> @cpp_name@;
  382. if (!@js_name@@js_suffix@.is_undefined()) {
  383. if (!@js_name@@js_suffix@.is_object() || !is<@parameter.type.name@>(@js_name@@js_suffix@.as_object()))
  384. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  385. @cpp_name@ = static_cast<@parameter.type.name@&>(@js_name@@js_suffix@.as_object());
  386. }
  387. )~~~");
  388. }
  389. } else {
  390. scoped_generator.append(R"~~~(
  391. @parameter.type.name@* @cpp_name@ = nullptr;
  392. if (!@js_name@@js_suffix@.is_nullish()) {
  393. if (!@js_name@@js_suffix@.is_object() || !is<@parameter.type.name@>(@js_name@@js_suffix@.as_object()))
  394. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  395. @cpp_name@ = &static_cast<@parameter.type.name@&>(@js_name@@js_suffix@.as_object());
  396. }
  397. )~~~");
  398. }
  399. } else if (parameter.type->name() == "double" || parameter.type->name() == "float") {
  400. if (!optional) {
  401. scoped_generator.append(R"~~~(
  402. @parameter.type.name@ @cpp_name@ = TRY(@js_name@@js_suffix@.to_double(vm));
  403. )~~~");
  404. } else {
  405. if (optional_default_value.has_value()) {
  406. scoped_generator.append(R"~~~(
  407. @parameter.type.name@ @cpp_name@;
  408. )~~~");
  409. } else {
  410. scoped_generator.append(R"~~~(
  411. Optional<@parameter.type.name@> @cpp_name@;
  412. )~~~");
  413. }
  414. scoped_generator.append(R"~~~(
  415. if (!@js_name@@js_suffix@.is_undefined())
  416. @cpp_name@ = TRY(@js_name@@js_suffix@.to_double(vm));
  417. )~~~");
  418. if (optional_default_value.has_value()) {
  419. scoped_generator.append(R"~~~(
  420. else
  421. @cpp_name@ = @parameter.optional_default_value@;
  422. )~~~");
  423. } else {
  424. scoped_generator.append(R"~~~(
  425. )~~~");
  426. }
  427. }
  428. } else if (parameter.type->name() == "boolean") {
  429. if (!optional || optional_default_value.has_value()) {
  430. scoped_generator.append(R"~~~(
  431. bool @cpp_name@;
  432. )~~~");
  433. } else {
  434. scoped_generator.append(R"~~~(
  435. Optional<bool> @cpp_name@;
  436. )~~~");
  437. }
  438. if (optional) {
  439. scoped_generator.append(R"~~~(
  440. if (!@js_name@@js_suffix@.is_undefined())
  441. )~~~");
  442. }
  443. scoped_generator.append(R"~~~(
  444. @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  445. )~~~");
  446. if (optional_default_value.has_value()) {
  447. scoped_generator.append(R"~~~(
  448. else
  449. @cpp_name@ = @parameter.optional_default_value@;
  450. )~~~");
  451. }
  452. } else if (parameter.type->name() == "unsigned long") {
  453. if (!optional || optional_default_value.has_value()) {
  454. scoped_generator.append(R"~~~(
  455. u32 @cpp_name@;
  456. )~~~");
  457. } else {
  458. scoped_generator.append(R"~~~(
  459. Optional<u32> @cpp_name@;
  460. )~~~");
  461. }
  462. if (optional) {
  463. scoped_generator.append(R"~~~(
  464. if (!@js_name@@js_suffix@.is_undefined())
  465. )~~~");
  466. }
  467. scoped_generator.append(R"~~~(
  468. @cpp_name@ = TRY(@js_name@@js_suffix@.to_u32(vm));
  469. )~~~");
  470. if (optional_default_value.has_value()) {
  471. scoped_generator.append(R"~~~(
  472. else
  473. @cpp_name@ = @parameter.optional_default_value@UL;
  474. )~~~");
  475. }
  476. } else if (parameter.type->name() == "unsigned short") {
  477. if (!optional || optional_default_value.has_value()) {
  478. scoped_generator.append(R"~~~(
  479. u16 @cpp_name@;
  480. )~~~");
  481. } else {
  482. scoped_generator.append(R"~~~(
  483. Optional<u16> @cpp_name@;
  484. )~~~");
  485. }
  486. if (optional) {
  487. scoped_generator.append(R"~~~(
  488. if (!@js_name@@js_suffix@.is_undefined())
  489. )~~~");
  490. }
  491. scoped_generator.append(R"~~~(
  492. @cpp_name@ = TRY(@js_name@@js_suffix@.to_u16(vm));
  493. )~~~");
  494. if (optional_default_value.has_value()) {
  495. scoped_generator.append(R"~~~(
  496. else
  497. @cpp_name@ = @parameter.optional_default_value@;
  498. )~~~");
  499. }
  500. } else if (parameter.type->name() == "long") {
  501. if (!optional || optional_default_value.has_value()) {
  502. scoped_generator.append(R"~~~(
  503. i32 @cpp_name@;
  504. )~~~");
  505. } else {
  506. scoped_generator.append(R"~~~(
  507. Optional<i32> @cpp_name@;
  508. )~~~");
  509. }
  510. if (optional) {
  511. scoped_generator.append(R"~~~(
  512. if (!@js_name@@js_suffix@.is_undefined())
  513. )~~~");
  514. }
  515. scoped_generator.append(R"~~~(
  516. @cpp_name@ = TRY(@js_name@@js_suffix@.to_i32(vm));
  517. )~~~");
  518. if (optional_default_value.has_value()) {
  519. scoped_generator.append(R"~~~(
  520. else
  521. @cpp_name@ = @parameter.optional_default_value@L;
  522. )~~~");
  523. }
  524. } else if (parameter.type->name() == "long long") {
  525. if (!optional || optional_default_value.has_value()) {
  526. scoped_generator.append(R"~~~(
  527. i64 @cpp_name@;
  528. )~~~");
  529. } else {
  530. scoped_generator.append(R"~~~(
  531. Optional<i64> @cpp_name@;
  532. )~~~");
  533. }
  534. if (optional) {
  535. scoped_generator.append(R"~~~(
  536. if (!@js_name@@js_suffix@.is_undefined())
  537. )~~~");
  538. }
  539. scoped_generator.append(R"~~~(
  540. @cpp_name@ = TRY(@js_name@@js_suffix@.to_bigint_int64(vm));
  541. )~~~");
  542. if (optional_default_value.has_value()) {
  543. scoped_generator.append(R"~~~(
  544. else
  545. @cpp_name@ = @parameter.optional_default_value@L;
  546. )~~~");
  547. }
  548. } else if (parameter.type->name() == "Promise") {
  549. // NOTE: It's not clear to me where the implicit wrapping of non-Promise values in a resolved
  550. // Promise is defined in the spec; https://webidl.spec.whatwg.org/#idl-promise doesn't say
  551. // anything of this sort. Both Gecko and Blink do it, however, so I'm sure it's correct.
  552. scoped_generator.append(R"~~~(
  553. if (!@js_name@@js_suffix@.is_object() || !is<JS::Promise>(@js_name@@js_suffix@.as_object())) {
  554. auto new_promise = JS::Promise::create(realm);
  555. new_promise->fulfill(@js_name@@js_suffix@);
  556. @js_name@@js_suffix@ = new_promise;
  557. }
  558. auto @cpp_name@ = JS::make_handle(&static_cast<JS::Promise&>(@js_name@@js_suffix@.as_object()));
  559. )~~~");
  560. } else if (parameter.type->name() == "object") {
  561. if (optional) {
  562. scoped_generator.append(R"~~~(
  563. Optional<JS::Handle<JS::Object>> @cpp_name@;
  564. if (!@js_name@@js_suffix@.is_undefined())
  565. @cpp_name@ = JS::make_handle(TRY(@js_name@@js_suffix@.to_object(vm)));
  566. )~~~");
  567. } else {
  568. scoped_generator.append(R"~~~(
  569. auto @cpp_name@ = JS::make_handle(TRY(@js_name@@js_suffix@.to_object(vm)));
  570. )~~~");
  571. }
  572. } else if (parameter.type->name() == "BufferSource") {
  573. scoped_generator.append(R"~~~(
  574. if (!@js_name@@js_suffix@.is_object() || !(is<JS::TypedArrayBase>(@js_name@@js_suffix@.as_object()) || is<JS::ArrayBuffer>(@js_name@@js_suffix@.as_object()) || is<JS::DataView>(@js_name@@js_suffix@.as_object())))
  575. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  576. // TODO: Should we make this a Variant?
  577. auto @cpp_name@ = JS::make_handle(&@js_name@@js_suffix@.as_object());
  578. )~~~");
  579. } else if (parameter.type->name() == "any") {
  580. if (variadic) {
  581. scoped_generator.append(R"~~~(
  582. JS::MarkedVector<JS::Value> @cpp_name@ { vm.heap() };
  583. if (vm.argument_count() > @js_suffix@) {
  584. TRY_OR_THROW_OOM(vm, @cpp_name@.try_ensure_capacity(vm.argument_count() - @js_suffix@));
  585. for (size_t i = @js_suffix@; i < vm.argument_count(); ++i)
  586. @cpp_name@.unchecked_append(vm.argument(i));
  587. }
  588. )~~~");
  589. } else if (!optional) {
  590. scoped_generator.append(R"~~~(
  591. auto @cpp_name@ = @js_name@@js_suffix@;
  592. )~~~");
  593. } else {
  594. scoped_generator.append(R"~~~(
  595. JS::Value @cpp_name@ = JS::js_undefined();
  596. if (!@js_name@@js_suffix@.is_undefined())
  597. @cpp_name@ = @js_name@@js_suffix@;
  598. )~~~");
  599. if (optional_default_value.has_value()) {
  600. if (optional_default_value == "null") {
  601. scoped_generator.append(R"~~~(
  602. else
  603. @cpp_name@ = JS::js_null();
  604. )~~~");
  605. } else if (optional_default_value->to_int().has_value() || optional_default_value->to_uint().has_value()) {
  606. scoped_generator.append(R"~~~(
  607. else
  608. @cpp_name@ = JS::Value(@parameter.optional_default_value@);
  609. )~~~");
  610. } else {
  611. TODO();
  612. }
  613. }
  614. }
  615. } else if (interface.enumerations.contains(parameter.type->name())) {
  616. auto enum_generator = scoped_generator.fork();
  617. auto& enumeration = interface.enumerations.find(parameter.type->name())->value;
  618. StringView enum_member_name;
  619. if (optional_default_value.has_value()) {
  620. VERIFY(optional_default_value->length() >= 2 && (*optional_default_value)[0] == '"' && (*optional_default_value)[optional_default_value->length() - 1] == '"');
  621. enum_member_name = optional_default_value->substring_view(1, optional_default_value->length() - 2);
  622. } else {
  623. enum_member_name = enumeration.first_member;
  624. }
  625. auto default_value_cpp_name = enumeration.translated_cpp_names.get(enum_member_name);
  626. VERIFY(default_value_cpp_name.has_value());
  627. enum_generator.set("enum.default.cpp_value", *default_value_cpp_name);
  628. enum_generator.set("js_name.as_string", DeprecatedString::formatted("{}{}_string", enum_generator.get("js_name"sv), enum_generator.get("js_suffix"sv)));
  629. enum_generator.append(R"~~~(
  630. @parameter.type.name@ @cpp_name@ { @parameter.type.name@::@enum.default.cpp_value@ };
  631. )~~~");
  632. if (optional) {
  633. enum_generator.append(R"~~~(
  634. if (!@js_name@@js_suffix@.is_undefined()) {
  635. )~~~");
  636. }
  637. enum_generator.append(R"~~~(
  638. auto @js_name.as_string@ = TRY(@js_name@@js_suffix@.to_string(vm));
  639. )~~~");
  640. auto first = true;
  641. VERIFY(enumeration.translated_cpp_names.size() >= 1);
  642. for (auto& it : enumeration.translated_cpp_names) {
  643. enum_generator.set("enum.alt.name", it.key);
  644. enum_generator.set("enum.alt.value", it.value);
  645. enum_generator.set("else", first ? "" : "else ");
  646. first = false;
  647. enum_generator.append(R"~~~(
  648. @else@if (@js_name.as_string@ == "@enum.alt.name@"sv)
  649. @cpp_name@ = @parameter.type.name@::@enum.alt.value@;
  650. )~~~");
  651. }
  652. // NOTE: Attribute setters return undefined instead of throwing when the string doesn't match an enum value.
  653. if constexpr (!IsSame<Attribute, RemoveConst<ParameterType>>) {
  654. enum_generator.append(R"~~~(
  655. else
  656. return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, @js_name.as_string@, "@parameter.type.name@");
  657. )~~~");
  658. } else {
  659. enum_generator.append(R"~~~(
  660. else
  661. return JS::js_undefined();
  662. )~~~");
  663. }
  664. if (optional) {
  665. enum_generator.append(R"~~~(
  666. }
  667. )~~~");
  668. }
  669. } else if (interface.dictionaries.contains(parameter.type->name())) {
  670. if (optional_default_value.has_value() && optional_default_value != "{}")
  671. TODO();
  672. auto dictionary_generator = scoped_generator.fork();
  673. dictionary_generator.append(R"~~~(
  674. if (!@js_name@@js_suffix@.is_nullish() && !@js_name@@js_suffix@.is_object())
  675. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  676. @parameter.type.name@ @cpp_name@ {};
  677. )~~~");
  678. auto* current_dictionary = &interface.dictionaries.find(parameter.type->name())->value;
  679. while (true) {
  680. for (auto& member : current_dictionary->members) {
  681. dictionary_generator.set("member_key", member.name);
  682. auto member_js_name = make_input_acceptable_cpp(member.name.to_snakecase());
  683. auto member_value_name = DeprecatedString::formatted("{}_value", member_js_name);
  684. auto member_property_value_name = DeprecatedString::formatted("{}_property_value", member_js_name);
  685. dictionary_generator.set("member_name", member_js_name);
  686. dictionary_generator.set("member_value_name", member_value_name);
  687. dictionary_generator.set("member_property_value_name", member_property_value_name);
  688. dictionary_generator.append(R"~~~(
  689. auto @member_property_value_name@ = JS::js_undefined();
  690. if (@js_name@@js_suffix@.is_object())
  691. @member_property_value_name@ = TRY(@js_name@@js_suffix@.as_object().get("@member_key@"));
  692. )~~~");
  693. if (member.required) {
  694. dictionary_generator.append(R"~~~(
  695. if (@member_property_value_name@.is_undefined())
  696. return vm.throw_completion<JS::TypeError>(JS::ErrorType::MissingRequiredProperty, "@member_key@");
  697. )~~~");
  698. } else if (!member.default_value.has_value()) {
  699. // Assume struct member is Optional<T> and _don't_ assign the generated default
  700. // value (e.g. first enum member) when the dictionary member is optional (i.e.
  701. // no `required` and doesn't have a default value).
  702. // This is needed so that "dictionary has member" checks work as expected.
  703. dictionary_generator.append(R"~~~(
  704. if (!@member_property_value_name@.is_undefined()) {
  705. )~~~");
  706. }
  707. generate_to_cpp(dictionary_generator, member, member_property_value_name, "", member_value_name, interface, member.extended_attributes.contains("LegacyNullToEmptyString"), !member.required, member.default_value);
  708. if (member.type->is_string() && optional && interface.extended_attributes.contains("UseNewAKString")) {
  709. dictionary_generator.append(R"~~~(
  710. if (@member_value_name@.has_value())
  711. @cpp_name@.@member_name@ = @member_value_name@.release_value();
  712. )~~~");
  713. } else {
  714. dictionary_generator.append(R"~~~(
  715. @cpp_name@.@member_name@ = @member_value_name@;
  716. )~~~");
  717. }
  718. if (!member.required && !member.default_value.has_value()) {
  719. dictionary_generator.append(R"~~~(
  720. }
  721. )~~~");
  722. }
  723. }
  724. if (current_dictionary->parent_name.is_null())
  725. break;
  726. VERIFY(interface.dictionaries.contains(current_dictionary->parent_name));
  727. current_dictionary = &interface.dictionaries.find(current_dictionary->parent_name)->value;
  728. }
  729. } else if (interface.callback_functions.contains(parameter.type->name())) {
  730. // https://webidl.spec.whatwg.org/#es-callback-function
  731. auto callback_function_generator = scoped_generator.fork();
  732. auto& callback_function = interface.callback_functions.find(parameter.type->name())->value;
  733. // An ECMAScript value V is converted to an IDL callback function type value by running the following algorithm:
  734. // 1. If the result of calling IsCallable(V) is false and the conversion to an IDL value is not being performed due to V being assigned to an attribute whose type is a nullable callback function that is annotated with [LegacyTreatNonObjectAsNull], then throw a TypeError.
  735. if (!callback_function.is_legacy_treat_non_object_as_null) {
  736. callback_function_generator.append(R"~~~(
  737. if (!@js_name@@js_suffix@.is_function())
  738. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, TRY_OR_THROW_OOM(vm, @js_name@@js_suffix@.to_string_without_side_effects()));
  739. )~~~");
  740. }
  741. // 2. Return the IDL callback function type value that represents a reference to the same object that V represents, with the incumbent settings object as the callback context.
  742. if (callback_function.is_legacy_treat_non_object_as_null) {
  743. callback_function_generator.append(R"~~~(
  744. WebIDL::CallbackType* @cpp_name@ = nullptr;
  745. if (@js_name@@js_suffix@.is_object())
  746. @cpp_name@ = vm.heap().allocate_without_realm<WebIDL::CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
  747. )~~~");
  748. } else {
  749. callback_function_generator.append(R"~~~(
  750. auto @cpp_name@ = vm.heap().allocate_without_realm<WebIDL::CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
  751. )~~~");
  752. }
  753. } else if (parameter.type->name() == "sequence") {
  754. // https://webidl.spec.whatwg.org/#es-sequence
  755. auto sequence_generator = scoped_generator.fork();
  756. auto& parameterized_type = verify_cast<IDL::ParameterizedType>(*parameter.type);
  757. sequence_generator.set("recursion_depth", DeprecatedString::number(recursion_depth));
  758. // An ECMAScript value V is converted to an IDL sequence<T> value as follows:
  759. // 1. If Type(V) is not Object, throw a TypeError.
  760. // 2. Let method be ? GetMethod(V, @@iterator).
  761. // 3. If method is undefined, throw a TypeError.
  762. // 4. Return the result of creating a sequence from V and method.
  763. if (optional) {
  764. auto sequence_cpp_type = idl_type_name_to_cpp_type(parameterized_type.parameters().first(), interface);
  765. sequence_generator.set("sequence.type", sequence_cpp_type.name);
  766. sequence_generator.set("sequence.storage_type", sequence_storage_type_to_cpp_storage_type_name(sequence_cpp_type.sequence_storage_type));
  767. if (!optional_default_value.has_value()) {
  768. if (sequence_cpp_type.sequence_storage_type == IDL::SequenceStorageType::Vector) {
  769. sequence_generator.append(R"~~~(
  770. Optional<@sequence.storage_type@<@sequence.type@>> @cpp_name@;
  771. )~~~");
  772. } else {
  773. sequence_generator.append(R"~~~(
  774. Optional<@sequence.storage_type@> @cpp_name@;
  775. )~~~");
  776. }
  777. } else {
  778. if (optional_default_value != "[]")
  779. TODO();
  780. if (sequence_cpp_type.sequence_storage_type == IDL::SequenceStorageType::Vector) {
  781. sequence_generator.append(R"~~~(
  782. @sequence.storage_type@<@sequence.type@> @cpp_name@;
  783. )~~~");
  784. } else {
  785. sequence_generator.append(R"~~~(
  786. @sequence.storage_type@ @cpp_name@ { global_object.heap() };
  787. )~~~");
  788. }
  789. }
  790. sequence_generator.append(R"~~~(
  791. if (!@js_name@@js_suffix@.is_undefined()) {
  792. )~~~");
  793. }
  794. sequence_generator.append(R"~~~(
  795. if (!@js_name@@js_suffix@.is_object())
  796. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, TRY_OR_THROW_OOM(vm, @js_name@@js_suffix@.to_string_without_side_effects()));
  797. auto* iterator_method@recursion_depth@ = TRY(@js_name@@js_suffix@.get_method(vm, *vm.well_known_symbol_iterator()));
  798. if (!iterator_method@recursion_depth@)
  799. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, @js_name@@js_suffix@.to_string_without_side_effects()));
  800. )~~~");
  801. parameterized_type.generate_sequence_from_iterable(sequence_generator, DeprecatedString::formatted("{}{}", acceptable_cpp_name, optional ? "_non_optional" : ""), DeprecatedString::formatted("{}{}", js_name, js_suffix), DeprecatedString::formatted("iterator_method{}", recursion_depth), interface, recursion_depth + 1);
  802. if (optional) {
  803. sequence_generator.append(R"~~~(
  804. @cpp_name@ = move(@cpp_name@_non_optional);
  805. }
  806. )~~~");
  807. }
  808. } else if (parameter.type->name() == "record") {
  809. // https://webidl.spec.whatwg.org/#es-record
  810. auto record_generator = scoped_generator.fork();
  811. auto& parameterized_type = verify_cast<IDL::ParameterizedType>(*parameter.type);
  812. record_generator.set("recursion_depth", DeprecatedString::number(recursion_depth));
  813. // A record can only have two types: key type and value type.
  814. VERIFY(parameterized_type.parameters().size() == 2);
  815. // A record only allows the key to be a string.
  816. VERIFY(parameterized_type.parameters()[0]->is_string());
  817. // An ECMAScript value O is converted to an IDL record<K, V> value as follows:
  818. // 1. If Type(O) is not Object, throw a TypeError.
  819. // 2. Let result be a new empty instance of record<K, V>.
  820. // 3. Let keys be ? O.[[OwnPropertyKeys]]().
  821. // 4. For each key of keys:
  822. // 1. Let desc be ? O.[[GetOwnProperty]](key).
  823. // 2. If desc is not undefined and desc.[[Enumerable]] is true:
  824. // 1. Let typedKey be key converted to an IDL value of type K.
  825. // 2. Let value be ? Get(O, key).
  826. // 3. Let typedValue be value converted to an IDL value of type V.
  827. // 4. Set result[typedKey] to typedValue.
  828. // 5. Return result.
  829. auto record_cpp_type = IDL::idl_type_name_to_cpp_type(parameterized_type, interface);
  830. record_generator.set("record.type", record_cpp_type.name);
  831. // If this is a recursive call to generate_to_cpp, assume that the caller has already handled converting the JS value to an object for us.
  832. // This affects record types in unions for example.
  833. if (recursion_depth == 0) {
  834. record_generator.append(R"~~~(
  835. if (!@js_name@@js_suffix@.is_object())
  836. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, TRY_OR_THROW_OOM(vm, @js_name@@js_suffix@.to_string_without_side_effects()));
  837. auto& @js_name@@js_suffix@_object = @js_name@@js_suffix@.as_object();
  838. )~~~");
  839. }
  840. record_generator.append(R"~~~(
  841. @record.type@ @cpp_name@;
  842. auto record_keys@recursion_depth@ = TRY(@js_name@@js_suffix@_object.internal_own_property_keys());
  843. for (auto& key@recursion_depth@ : record_keys@recursion_depth@) {
  844. auto property_key@recursion_depth@ = MUST(JS::PropertyKey::from_value(vm, key@recursion_depth@));
  845. auto descriptor@recursion_depth@ = TRY(@js_name@@js_suffix@_object.internal_get_own_property(property_key@recursion_depth@));
  846. if (!descriptor@recursion_depth@.has_value() || !descriptor@recursion_depth@->enumerable.has_value() || !descriptor@recursion_depth@->enumerable.value())
  847. continue;
  848. )~~~");
  849. IDL::Parameter key_parameter { .type = parameterized_type.parameters()[0], .name = acceptable_cpp_name, .optional_default_value = {}, .extended_attributes = {} };
  850. generate_to_cpp(record_generator, key_parameter, "key", DeprecatedString::number(recursion_depth), DeprecatedString::formatted("typed_key{}", recursion_depth), interface, false, false, {}, false, recursion_depth + 1);
  851. record_generator.append(R"~~~(
  852. auto value@recursion_depth@ = TRY(@js_name@@js_suffix@_object.get(property_key@recursion_depth@));
  853. )~~~");
  854. // FIXME: Record value types should be TypeWithExtendedAttributes, which would allow us to get [LegacyNullToEmptyString] here.
  855. IDL::Parameter value_parameter { .type = parameterized_type.parameters()[1], .name = acceptable_cpp_name, .optional_default_value = {}, .extended_attributes = {} };
  856. generate_to_cpp(record_generator, value_parameter, "value", DeprecatedString::number(recursion_depth), DeprecatedString::formatted("typed_value{}", recursion_depth), interface, false, false, {}, false, recursion_depth + 1);
  857. record_generator.append(R"~~~(
  858. @cpp_name@.set(typed_key@recursion_depth@, typed_value@recursion_depth@);
  859. }
  860. )~~~");
  861. } else if (is<IDL::UnionType>(*parameter.type)) {
  862. // https://webidl.spec.whatwg.org/#es-union
  863. auto union_generator = scoped_generator.fork();
  864. auto& union_type = verify_cast<IDL::UnionType>(*parameter.type);
  865. union_generator.set("union_type", union_type_to_variant(union_type, interface));
  866. union_generator.set("recursion_depth", DeprecatedString::number(recursion_depth));
  867. // NOTE: This is handled out here as we need the dictionary conversion code for the {} optional default value.
  868. // 3. Let types be the flattened member types of the union type.
  869. auto types = union_type.flattened_member_types();
  870. RefPtr<Type const> dictionary_type;
  871. for (auto& dictionary : interface.dictionaries) {
  872. for (auto& type : types) {
  873. if (type->name() == dictionary.key) {
  874. dictionary_type = type;
  875. break;
  876. }
  877. }
  878. if (dictionary_type)
  879. break;
  880. }
  881. if (dictionary_type) {
  882. auto dictionary_generator = union_generator.fork();
  883. dictionary_generator.set("dictionary.type", dictionary_type->name());
  884. // The lambda must take the JS::Value to convert as a parameter instead of capturing it in order to support union types being variadic.
  885. dictionary_generator.append(R"~~~(
  886. auto @js_name@@js_suffix@_to_dictionary = [&vm](JS::Value @js_name@@js_suffix@) -> JS::ThrowCompletionOr<@dictionary.type@> {
  887. )~~~");
  888. IDL::Parameter dictionary_parameter { .type = *dictionary_type, .name = acceptable_cpp_name, .optional_default_value = {}, .extended_attributes = {} };
  889. generate_to_cpp(dictionary_generator, dictionary_parameter, js_name, js_suffix, "dictionary_union_type"sv, interface, false, false, {}, false, recursion_depth + 1);
  890. dictionary_generator.append(R"~~~(
  891. return dictionary_union_type;
  892. };
  893. )~~~");
  894. }
  895. // A lambda is used because Variants without "Empty" can't easily be default initialized.
  896. // Plus, this would require the user of union types to always accept a Variant with an Empty type.
  897. // Additionally, it handles the case of unconditionally throwing a TypeError at the end if none of the types match.
  898. // This is because we cannot unconditionally throw in generate_to_cpp as generate_to_cpp is supposed to assign to a variable and then continue.
  899. // Note that all the other types only throw on a condition.
  900. // The lambda must take the JS::Value to convert as a parameter instead of capturing it in order to support union types being variadic.
  901. StringBuilder to_variant_captures;
  902. to_variant_captures.append("&vm, &realm"sv);
  903. if (dictionary_type)
  904. to_variant_captures.append(DeprecatedString::formatted(", &{}{}_to_dictionary", js_name, js_suffix));
  905. union_generator.set("to_variant_captures", to_variant_captures.to_deprecated_string());
  906. union_generator.append(R"~~~(
  907. auto @js_name@@js_suffix@_to_variant = [@to_variant_captures@](JS::Value @js_name@@js_suffix@) -> JS::ThrowCompletionOr<@union_type@> {
  908. // These might be unused.
  909. (void)vm;
  910. (void)realm;
  911. )~~~");
  912. // 1. If the union type includes undefined and V is undefined, then return the unique undefined value.
  913. if (union_type.includes_undefined()) {
  914. scoped_generator.append(R"~~~(
  915. if (@js_name@@js_suffix@.is_undefined())
  916. return Empty {};
  917. )~~~");
  918. }
  919. // FIXME: 2. If the union type includes a nullable type and V is null or undefined, then return the IDL value null.
  920. if (union_type.includes_nullable_type()) {
  921. // Implement me
  922. } else if (dictionary_type) {
  923. // 4. If V is null or undefined, then
  924. // 4.1 If types includes a dictionary type, then return the result of converting V to that dictionary type.
  925. union_generator.append(R"~~~(
  926. if (@js_name@@js_suffix@.is_nullish())
  927. return @union_type@ { TRY(@js_name@@js_suffix@_to_dictionary(@js_name@@js_suffix@)) };
  928. )~~~");
  929. }
  930. bool includes_object = false;
  931. for (auto& type : types) {
  932. if (type->name() == "object") {
  933. includes_object = true;
  934. break;
  935. }
  936. }
  937. // FIXME: Don't generate this if the union type doesn't include any object types.
  938. union_generator.append(R"~~~(
  939. if (@js_name@@js_suffix@.is_object()) {
  940. [[maybe_unused]] auto& @js_name@@js_suffix@_object = @js_name@@js_suffix@.as_object();
  941. )~~~");
  942. bool includes_platform_object = false;
  943. for (auto& type : types) {
  944. if (IDL::is_platform_object(type)) {
  945. includes_platform_object = true;
  946. break;
  947. }
  948. }
  949. if (includes_platform_object) {
  950. // 5. If V is a platform object, then:
  951. union_generator.append(R"~~~(
  952. if (is<PlatformObject>(@js_name@@js_suffix@_object)) {
  953. )~~~");
  954. // NOTE: This codegen assumes that all union types are cells or values we can create a handle for.
  955. // 1. If types includes an interface type that V implements, then return the IDL value that is a reference to the object V.
  956. for (auto& type : types) {
  957. if (!IDL::is_platform_object(type))
  958. continue;
  959. auto union_platform_object_type_generator = union_generator.fork();
  960. union_platform_object_type_generator.set("platform_object_type", type->name());
  961. union_platform_object_type_generator.append(R"~~~(
  962. if (is<@platform_object_type@>(@js_name@@js_suffix@_object))
  963. return JS::make_handle(static_cast<@platform_object_type@&>(@js_name@@js_suffix@_object));
  964. )~~~");
  965. }
  966. // 2. If types includes object, then return the IDL value that is a reference to the object V.
  967. if (includes_object) {
  968. union_generator.append(R"~~~(
  969. return JS::make_handle(@js_name@@js_suffix@_object);
  970. )~~~");
  971. }
  972. union_generator.append(R"~~~(
  973. }
  974. )~~~");
  975. }
  976. // 6. If Type(V) is Object and V has an [[ArrayBufferData]] internal slot, then
  977. // 1. If types includes ArrayBuffer, then return the result of converting V to ArrayBuffer.
  978. for (auto& type : types) {
  979. if (type->name() == "BufferSource") {
  980. union_generator.append(R"~~~(
  981. if (is<JS::ArrayBuffer>(@js_name@@js_suffix@_object))
  982. return JS::make_handle(@js_name@@js_suffix@_object);
  983. )~~~");
  984. }
  985. }
  986. // 2. If types includes object, then return the IDL value that is a reference to the object V.
  987. if (includes_object) {
  988. union_generator.append(R"~~~(
  989. return @js_name@@js_suffix@_object;
  990. )~~~");
  991. }
  992. // FIXME: 7. If Type(V) is Object and V has a [[DataView]] internal slot, then:
  993. // 1. If types includes DataView, then return the result of converting V to DataView.
  994. // 2. If types includes object, then return the IDL value that is a reference to the object V.
  995. // FIXME: 8. If Type(V) is Object and V has a [[TypedArrayName]] internal slot, then:
  996. // 1. If types includes a typed array type whose name is the value of V’s [[TypedArrayName]] internal slot, then return the result of converting V to that type.
  997. // 2. If types includes object, then return the IDL value that is a reference to the object V.
  998. // 9. If IsCallable(V) is true, then:
  999. // 1. If types includes a callback function type, then return the result of converting V to that callback function type.
  1000. // 2. If types includes object, then return the IDL value that is a reference to the object V.
  1001. bool includes_callable = false;
  1002. for (auto const& type : types) {
  1003. if (type->name() == "Function"sv) {
  1004. includes_callable = true;
  1005. break;
  1006. }
  1007. }
  1008. if (includes_callable) {
  1009. union_generator.append(R"~~~(
  1010. if (@js_name@@js_suffix@_object.is_function())
  1011. return JS::make_handle(vm.heap().allocate_without_realm<WebIDL::CallbackType>(@js_name@@js_suffix@.as_function(), HTML::incumbent_settings_object()));
  1012. )~~~");
  1013. }
  1014. // 10. If Type(V) is Object, then:
  1015. // 1. If types includes a sequence type, then:
  1016. RefPtr<IDL::ParameterizedType const> sequence_type;
  1017. for (auto& type : types) {
  1018. if (type->name() == "sequence") {
  1019. sequence_type = verify_cast<IDL::ParameterizedType>(*type);
  1020. break;
  1021. }
  1022. }
  1023. if (sequence_type) {
  1024. // 1. Let method be ? GetMethod(V, @@iterator).
  1025. union_generator.append(R"~~~(
  1026. auto* method = TRY(@js_name@@js_suffix@.get_method(vm, *vm.well_known_symbol_iterator()));
  1027. )~~~");
  1028. // 2. If method is not undefined, return the result of creating a sequence of that type from V and method.
  1029. union_generator.append(R"~~~(
  1030. if (method) {
  1031. )~~~");
  1032. sequence_type->generate_sequence_from_iterable(union_generator, acceptable_cpp_name, DeprecatedString::formatted("{}{}", js_name, js_suffix), "method", interface, recursion_depth + 1);
  1033. union_generator.append(R"~~~(
  1034. return @cpp_name@;
  1035. }
  1036. )~~~");
  1037. }
  1038. // FIXME: 2. If types includes a frozen array type, then
  1039. // 1. Let method be ? GetMethod(V, @@iterator).
  1040. // 2. If method is not undefined, return the result of creating a frozen array of that type from V and method.
  1041. // 3. If types includes a dictionary type, then return the result of converting V to that dictionary type.
  1042. if (dictionary_type) {
  1043. union_generator.append(R"~~~(
  1044. return @union_type@ { TRY(@js_name@@js_suffix@_to_dictionary(@js_name@@js_suffix@)) };
  1045. )~~~");
  1046. }
  1047. // 4. If types includes a record type, then return the result of converting V to that record type.
  1048. RefPtr<IDL::ParameterizedType const> record_type;
  1049. for (auto& type : types) {
  1050. if (type->name() == "record") {
  1051. record_type = verify_cast<IDL::ParameterizedType>(*type);
  1052. break;
  1053. }
  1054. }
  1055. if (record_type) {
  1056. IDL::Parameter record_parameter { .type = *record_type, .name = acceptable_cpp_name, .optional_default_value = {}, .extended_attributes = {} };
  1057. generate_to_cpp(union_generator, record_parameter, js_name, js_suffix, "record_union_type"sv, interface, false, false, {}, false, recursion_depth + 1);
  1058. union_generator.append(R"~~~(
  1059. return record_union_type;
  1060. )~~~");
  1061. }
  1062. // FIXME: 5. If types includes a callback interface type, then return the result of converting V to that callback interface type.
  1063. // 6. If types includes object, then return the IDL value that is a reference to the object V.
  1064. if (includes_object) {
  1065. union_generator.append(R"~~~(
  1066. return @js_name@@js_suffix@_object;
  1067. )~~~");
  1068. }
  1069. // End of is_object.
  1070. union_generator.append(R"~~~(
  1071. }
  1072. )~~~");
  1073. // 11. If Type(V) is Boolean, then:
  1074. // 1. If types includes boolean, then return the result of converting V to boolean.
  1075. bool includes_boolean = false;
  1076. for (auto& type : types) {
  1077. if (type->name() == "boolean") {
  1078. includes_boolean = true;
  1079. break;
  1080. }
  1081. }
  1082. if (includes_boolean) {
  1083. union_generator.append(R"~~~(
  1084. if (@js_name@@js_suffix@.is_boolean())
  1085. return @union_type@ { @js_name@@js_suffix@.as_bool() };
  1086. )~~~");
  1087. }
  1088. RefPtr<IDL::Type const> numeric_type;
  1089. for (auto& type : types) {
  1090. if (type->is_numeric()) {
  1091. numeric_type = type;
  1092. break;
  1093. }
  1094. }
  1095. // 12. If Type(V) is Number, then:
  1096. // 1. If types includes a numeric type, then return the result of converting V to that numeric type.
  1097. if (numeric_type) {
  1098. union_generator.append(R"~~~(
  1099. if (@js_name@@js_suffix@.is_number()) {
  1100. )~~~");
  1101. // NOTE: generate_to_cpp doesn't use the parameter name.
  1102. // NOTE: generate_to_cpp will use to_{u32,etc.} which uses to_number internally and will thus use TRY, but it cannot throw as we know we are dealing with a number.
  1103. IDL::Parameter parameter { .type = *numeric_type, .name = DeprecatedString::empty(), .optional_default_value = {}, .extended_attributes = {} };
  1104. generate_to_cpp(union_generator, parameter, js_name, js_suffix, DeprecatedString::formatted("{}{}_number", js_name, js_suffix), interface, false, false, {}, false, recursion_depth + 1);
  1105. union_generator.append(R"~~~(
  1106. return @js_name@@js_suffix@_number;
  1107. }
  1108. )~~~");
  1109. }
  1110. // 13. If Type(V) is BigInt, then:
  1111. // 1. If types includes bigint, then return the result of converting V to bigint
  1112. bool includes_bigint = false;
  1113. for (auto& type : types) {
  1114. if (type->name() == "bigint") {
  1115. includes_bigint = true;
  1116. break;
  1117. }
  1118. }
  1119. if (includes_bigint) {
  1120. union_generator.append(R"~~~(
  1121. if (@js_name@@js_suffix@.is_bigint())
  1122. return @js_name@@js_suffix@.as_bigint();
  1123. )~~~");
  1124. }
  1125. bool includes_string = false;
  1126. for (auto& type : types) {
  1127. if (type->is_string()) {
  1128. includes_string = true;
  1129. break;
  1130. }
  1131. }
  1132. if (includes_string) {
  1133. // 14. If types includes a string type, then return the result of converting V to that type.
  1134. // NOTE: Currently all string types are converted to String.
  1135. if (interface.extended_attributes.contains("UseNewAKString")) {
  1136. union_generator.append(R"~~~(
  1137. return TRY(@js_name@@js_suffix@.to_string(vm));
  1138. )~~~");
  1139. } else {
  1140. union_generator.append(R"~~~(
  1141. return TRY(@js_name@@js_suffix@.to_deprecated_string(vm));
  1142. )~~~");
  1143. }
  1144. } else if (numeric_type && includes_bigint) {
  1145. // 15. If types includes a numeric type and bigint, then return the result of converting V to either that numeric type or bigint.
  1146. // https://webidl.spec.whatwg.org/#converted-to-a-numeric-type-or-bigint
  1147. // NOTE: This algorithm is only used here.
  1148. // An ECMAScript value V is converted to an IDL numeric type T or bigint value by running the following algorithm:
  1149. // 1. Let x be ? ToNumeric(V).
  1150. // 2. If Type(x) is BigInt, then
  1151. // 1. Return the IDL bigint value that represents the same numeric value as x.
  1152. // 3. Assert: Type(x) is Number.
  1153. // 4. Return the result of converting x to T.
  1154. auto union_numeric_type_generator = union_generator.fork();
  1155. auto cpp_type = IDL::idl_type_name_to_cpp_type(*numeric_type, interface);
  1156. union_numeric_type_generator.set("numeric_type", cpp_type.name);
  1157. union_numeric_type_generator.append(R"~~~(
  1158. auto x = TRY(@js_name@@js_suffix@.to_numeric(vm));
  1159. if (x.is_bigint())
  1160. return x.as_bigint();
  1161. VERIFY(x.is_number());
  1162. )~~~");
  1163. // NOTE: generate_to_cpp doesn't use the parameter name.
  1164. // NOTE: generate_to_cpp will use to_{u32,etc.} which uses to_number internally and will thus use TRY, but it cannot throw as we know we are dealing with a number.
  1165. IDL::Parameter parameter { .type = *numeric_type, .name = DeprecatedString::empty(), .optional_default_value = {}, .extended_attributes = {} };
  1166. generate_to_cpp(union_numeric_type_generator, parameter, "x", DeprecatedString::empty(), "x_number", interface, false, false, {}, false, recursion_depth + 1);
  1167. union_numeric_type_generator.append(R"~~~(
  1168. return x_number;
  1169. )~~~");
  1170. } else if (numeric_type) {
  1171. // 16. If types includes a numeric type, then return the result of converting V to that numeric type.
  1172. // NOTE: generate_to_cpp doesn't use the parameter name.
  1173. // NOTE: generate_to_cpp will use to_{u32,etc.} which uses to_number internally and will thus use TRY, but it cannot throw as we know we are dealing with a number.
  1174. IDL::Parameter parameter { .type = *numeric_type, .name = DeprecatedString::empty(), .optional_default_value = {}, .extended_attributes = {} };
  1175. generate_to_cpp(union_generator, parameter, js_name, js_suffix, DeprecatedString::formatted("{}{}_number", js_name, js_suffix), interface, false, false, {}, false, recursion_depth + 1);
  1176. union_generator.append(R"~~~(
  1177. return @js_name@@js_suffix@_number;
  1178. )~~~");
  1179. } else if (includes_boolean) {
  1180. // 17. If types includes boolean, then return the result of converting V to boolean.
  1181. union_generator.append(R"~~~(
  1182. return @union_type@ { @js_name@@js_suffix@.to_boolean() };
  1183. )~~~");
  1184. } else if (includes_bigint) {
  1185. // 18. If types includes bigint, then return the result of converting V to bigint.
  1186. union_generator.append(R"~~~(
  1187. return TRY(@js_name@@js_suffix@.to_bigint(vm));
  1188. )~~~");
  1189. } else {
  1190. // 19. Throw a TypeError.
  1191. // FIXME: Replace the error message with something more descriptive.
  1192. union_generator.append(R"~~~(
  1193. return vm.throw_completion<JS::TypeError>("No union types matched"sv);
  1194. )~~~");
  1195. }
  1196. // Close the lambda and then perform the conversion.
  1197. union_generator.append(R"~~~(
  1198. };
  1199. )~~~");
  1200. if (!variadic) {
  1201. if (!optional) {
  1202. union_generator.append(R"~~~(
  1203. @union_type@ @cpp_name@ = TRY(@js_name@@js_suffix@_to_variant(@js_name@@js_suffix@));
  1204. )~~~");
  1205. } else {
  1206. if (!optional_default_value.has_value() || optional_default_value == "null"sv) {
  1207. union_generator.append(R"~~~(
  1208. Optional<@union_type@> @cpp_name@;
  1209. if (!@js_name@@js_suffix@.is_nullish())
  1210. @cpp_name@ = TRY(@js_name@@js_suffix@_to_variant(@js_name@@js_suffix@));
  1211. )~~~");
  1212. } else {
  1213. if (optional_default_value == "\"\"") {
  1214. if (!interface.extended_attributes.contains("UseNewAKString")) {
  1215. union_generator.append(R"~~~(
  1216. @union_type@ @cpp_name@ = @js_name@@js_suffix@.is_undefined() ? DeprecatedString::empty() : TRY(@js_name@@js_suffix@_to_variant(@js_name@@js_suffix@));
  1217. )~~~");
  1218. } else {
  1219. union_generator.append(R"~~~(
  1220. @union_type@ @cpp_name@ = @js_name@@js_suffix@.is_undefined() ? String {} : TRY(@js_name@@js_suffix@_to_variant(@js_name@@js_suffix@));
  1221. )~~~");
  1222. }
  1223. } else if (optional_default_value == "{}") {
  1224. VERIFY(dictionary_type);
  1225. union_generator.append(R"~~~(
  1226. @union_type@ @cpp_name@ = @js_name@@js_suffix@.is_undefined() ? TRY(@js_name@@js_suffix@_to_dictionary(@js_name@@js_suffix@)) : TRY(@js_name@@js_suffix@_to_variant(@js_name@@js_suffix@));
  1227. )~~~");
  1228. } else if (optional_default_value->to_int().has_value() || optional_default_value->to_uint().has_value()) {
  1229. union_generator.append(R"~~~(
  1230. @union_type@ @cpp_name@ = @js_name@@js_suffix@.is_undefined() ? @parameter.optional_default_value@ : TRY(@js_name@@js_suffix@_to_variant(@js_name@@js_suffix@));
  1231. )~~~");
  1232. } else {
  1233. TODO();
  1234. }
  1235. }
  1236. }
  1237. } else {
  1238. union_generator.append(R"~~~(
  1239. Vector<@union_type@> @cpp_name@;
  1240. if (vm.argument_count() > @js_suffix@) {
  1241. TRY_OR_THROW_OOM(vm, @cpp_name@.try_ensure_capacity(vm.argument_count() - @js_suffix@));
  1242. for (size_t i = @js_suffix@; i < vm.argument_count(); ++i) {
  1243. auto result = TRY(@js_name@@js_suffix@_to_variant(vm.argument(i)));
  1244. @cpp_name@.unchecked_append(move(result));
  1245. }
  1246. }
  1247. )~~~");
  1248. }
  1249. } else {
  1250. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type->name());
  1251. VERIFY_NOT_REACHED();
  1252. }
  1253. }
  1254. static void generate_argument_count_check(SourceGenerator& generator, DeprecatedString const& function_name, size_t argument_count)
  1255. {
  1256. if (argument_count == 0)
  1257. return;
  1258. auto argument_count_check_generator = generator.fork();
  1259. argument_count_check_generator.set("function.name", function_name);
  1260. argument_count_check_generator.set("function.nargs", DeprecatedString::number(argument_count));
  1261. if (argument_count == 1) {
  1262. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  1263. argument_count_check_generator.set(".arg_count_suffix", "");
  1264. } else {
  1265. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  1266. argument_count_check_generator.set(".arg_count_suffix", DeprecatedString::formatted(", \"{}\"", argument_count));
  1267. }
  1268. argument_count_check_generator.append(R"~~~(
  1269. if (vm.argument_count() < @function.nargs@)
  1270. return vm.throw_completion<JS::TypeError>(@.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  1271. )~~~");
  1272. }
  1273. static void generate_arguments(SourceGenerator& generator, Vector<IDL::Parameter> const& parameters, StringBuilder& arguments_builder, IDL::Interface const& interface)
  1274. {
  1275. auto arguments_generator = generator.fork();
  1276. Vector<DeprecatedString> parameter_names;
  1277. size_t argument_index = 0;
  1278. for (auto& parameter : parameters) {
  1279. auto parameter_name = make_input_acceptable_cpp(parameter.name.to_snakecase());
  1280. if (parameter.variadic) {
  1281. // JS::MarkedVector is non-copyable, and the implementations likely want ownership of the
  1282. // list, so we move() it into the parameter list.
  1283. parameter_names.append(DeprecatedString::formatted("move({})", parameter_name));
  1284. } else {
  1285. parameter_names.append(move(parameter_name));
  1286. arguments_generator.set("argument.index", DeprecatedString::number(argument_index));
  1287. arguments_generator.append(R"~~~(
  1288. auto arg@argument.index@ = vm.argument(@argument.index@);
  1289. )~~~");
  1290. }
  1291. bool legacy_null_to_empty_string = parameter.extended_attributes.contains("LegacyNullToEmptyString");
  1292. generate_to_cpp(generator, parameter, "arg", DeprecatedString::number(argument_index), parameter.name.to_snakecase(), interface, legacy_null_to_empty_string, parameter.optional, parameter.optional_default_value, parameter.variadic, 0);
  1293. ++argument_index;
  1294. }
  1295. arguments_builder.join(", "sv, parameter_names);
  1296. }
  1297. // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
  1298. void IDL::ParameterizedType::generate_sequence_from_iterable(SourceGenerator& generator, DeprecatedString const& cpp_name, DeprecatedString const& iterable_cpp_name, DeprecatedString const& iterator_method_cpp_name, IDL::Interface const& interface, size_t recursion_depth) const
  1299. {
  1300. auto sequence_generator = generator.fork();
  1301. sequence_generator.set("cpp_name", cpp_name);
  1302. sequence_generator.set("iterable_cpp_name", iterable_cpp_name);
  1303. sequence_generator.set("iterator_method_cpp_name", iterator_method_cpp_name);
  1304. sequence_generator.set("recursion_depth", DeprecatedString::number(recursion_depth));
  1305. auto sequence_cpp_type = idl_type_name_to_cpp_type(parameters().first(), interface);
  1306. sequence_generator.set("sequence.type", sequence_cpp_type.name);
  1307. sequence_generator.set("sequence.storage_type", sequence_storage_type_to_cpp_storage_type_name(sequence_cpp_type.sequence_storage_type));
  1308. // To create an IDL value of type sequence<T> given an iterable iterable and an iterator getter method, perform the following steps:
  1309. // 1. Let iter be ? GetIterator(iterable, sync, method).
  1310. // 2. Initialize i to be 0.
  1311. // 3. Repeat
  1312. // 1. Let next be ? IteratorStep(iter).
  1313. // 2. If next is false, then return an IDL sequence value of type sequence<T> of length i, where the value of the element at index j is Sj.
  1314. // 3. Let nextItem be ? IteratorValue(next).
  1315. // 4. Initialize Si to the result of converting nextItem to an IDL value of type T.
  1316. // 5. Set i to i + 1.
  1317. sequence_generator.append(R"~~~(
  1318. auto iterator@recursion_depth@ = TRY(JS::get_iterator(vm, @iterable_cpp_name@, JS::IteratorHint::Sync, @iterator_method_cpp_name@));
  1319. )~~~");
  1320. if (sequence_cpp_type.sequence_storage_type == SequenceStorageType::Vector) {
  1321. sequence_generator.append(R"~~~(
  1322. @sequence.storage_type@<@sequence.type@> @cpp_name@;
  1323. )~~~");
  1324. } else {
  1325. sequence_generator.append(R"~~~(
  1326. @sequence.storage_type@ @cpp_name@ { vm.heap() };
  1327. )~~~");
  1328. }
  1329. sequence_generator.append(R"~~~(
  1330. for (;;) {
  1331. auto* next@recursion_depth@ = TRY(JS::iterator_step(vm, iterator@recursion_depth@));
  1332. if (!next@recursion_depth@)
  1333. break;
  1334. auto next_item@recursion_depth@ = TRY(JS::iterator_value(vm, *next@recursion_depth@));
  1335. )~~~");
  1336. // FIXME: Sequences types should be TypeWithExtendedAttributes, which would allow us to get [LegacyNullToEmptyString] here.
  1337. IDL::Parameter parameter { .type = parameters().first(), .name = iterable_cpp_name, .optional_default_value = {}, .extended_attributes = {} };
  1338. generate_to_cpp(sequence_generator, parameter, "next_item", DeprecatedString::number(recursion_depth), DeprecatedString::formatted("sequence_item{}", recursion_depth), interface, false, false, {}, false, recursion_depth);
  1339. sequence_generator.append(R"~~~(
  1340. @cpp_name@.append(sequence_item@recursion_depth@);
  1341. }
  1342. )~~~");
  1343. }
  1344. enum class WrappingReference {
  1345. No,
  1346. Yes,
  1347. };
  1348. static void generate_wrap_statement(SourceGenerator& generator, DeprecatedString const& value, IDL::Type const& type, IDL::Interface const& interface, StringView result_expression, WrappingReference wrapping_reference = WrappingReference::No, size_t recursion_depth = 0)
  1349. {
  1350. auto scoped_generator = generator.fork();
  1351. scoped_generator.set("value", value);
  1352. if (!libweb_interface_namespaces.span().contains_slow(type.name())) {
  1353. if (is_javascript_builtin(type))
  1354. scoped_generator.set("type", DeprecatedString::formatted("JS::{}", type.name()));
  1355. else
  1356. scoped_generator.set("type", type.name());
  1357. } else {
  1358. // e.g. Document.getSelection which returns Selection, which is in the Selection namespace.
  1359. StringBuilder builder;
  1360. builder.append(type.name());
  1361. builder.append("::"sv);
  1362. builder.append(type.name());
  1363. scoped_generator.set("type", builder.to_deprecated_string());
  1364. }
  1365. scoped_generator.set("result_expression", result_expression);
  1366. scoped_generator.set("recursion_depth", DeprecatedString::number(recursion_depth));
  1367. if (type.name() == "undefined") {
  1368. scoped_generator.append(R"~~~(
  1369. @result_expression@ JS::js_undefined();
  1370. )~~~");
  1371. return;
  1372. }
  1373. if (type.is_nullable() && !is<UnionType>(type)) {
  1374. if (type.is_string()) {
  1375. if (!interface.extended_attributes.contains("UseNewAKString")) {
  1376. scoped_generator.append(R"~~~(
  1377. if (@value@.is_null()) {
  1378. @result_expression@ JS::js_null();
  1379. } else {
  1380. )~~~");
  1381. } else {
  1382. scoped_generator.append(R"~~~(
  1383. if (!@value@.has_value()) {
  1384. @result_expression@ JS::js_null();
  1385. } else {
  1386. )~~~");
  1387. }
  1388. } else if (type.name() == "sequence") {
  1389. scoped_generator.append(R"~~~(
  1390. if (!@value@.has_value()) {
  1391. @result_expression@ JS::js_null();
  1392. } else {
  1393. )~~~");
  1394. } else if (type.is_primitive()) {
  1395. scoped_generator.append(R"~~~(
  1396. if (!@value@.has_value()) {
  1397. @result_expression@ JS::js_null();
  1398. } else {
  1399. )~~~");
  1400. } else {
  1401. scoped_generator.append(R"~~~(
  1402. if (!@value@) {
  1403. @result_expression@ JS::js_null();
  1404. } else {
  1405. )~~~");
  1406. }
  1407. }
  1408. if (type.is_string()) {
  1409. if (type.is_nullable() && interface.extended_attributes.contains("UseNewAKString")) {
  1410. scoped_generator.append(R"~~~(
  1411. @result_expression@ JS::PrimitiveString::create(vm, @value@.release_value());
  1412. )~~~");
  1413. } else {
  1414. scoped_generator.append(R"~~~(
  1415. @result_expression@ JS::PrimitiveString::create(vm, @value@);
  1416. )~~~");
  1417. }
  1418. } else if (type.name() == "sequence") {
  1419. // https://webidl.spec.whatwg.org/#es-sequence
  1420. auto& sequence_generic_type = verify_cast<IDL::ParameterizedType>(type);
  1421. scoped_generator.append(R"~~~(
  1422. auto new_array@recursion_depth@ = MUST(JS::Array::create(realm, 0));
  1423. )~~~");
  1424. if (!type.is_nullable()) {
  1425. scoped_generator.append(R"~~~(
  1426. for (size_t i@recursion_depth@ = 0; i@recursion_depth@ < @value@.size(); ++i@recursion_depth@) {
  1427. auto& element@recursion_depth@ = @value@.at(i@recursion_depth@);
  1428. )~~~");
  1429. } else {
  1430. scoped_generator.append(R"~~~(
  1431. auto& @value@_non_optional = @value@.value();
  1432. for (size_t i@recursion_depth@ = 0; i@recursion_depth@ < @value@_non_optional.size(); ++i@recursion_depth@) {
  1433. auto& element@recursion_depth@ = @value@_non_optional.at(i@recursion_depth@);
  1434. )~~~");
  1435. }
  1436. // If the type is a platform object we currently return a Vector<JS::Handle<T>> from the
  1437. // C++ implementation, thus allowing us to unwrap the element (a handle) like below.
  1438. // This might need to change if we switch to a MarkedVector.
  1439. if (is_platform_object(sequence_generic_type.parameters().first())) {
  1440. scoped_generator.append(R"~~~(
  1441. auto* wrapped_element@recursion_depth@ = &(*element@recursion_depth@);
  1442. )~~~");
  1443. } else {
  1444. generate_wrap_statement(scoped_generator, DeprecatedString::formatted("element{}", recursion_depth), sequence_generic_type.parameters().first(), interface, DeprecatedString::formatted("auto wrapped_element{} =", recursion_depth), WrappingReference::Yes, recursion_depth + 1);
  1445. }
  1446. scoped_generator.append(R"~~~(
  1447. auto property_index@recursion_depth@ = JS::PropertyKey { i@recursion_depth@ };
  1448. MUST(new_array@recursion_depth@->create_data_property(property_index@recursion_depth@, wrapped_element@recursion_depth@));
  1449. }
  1450. @result_expression@ new_array@recursion_depth@;
  1451. )~~~");
  1452. } else if (type.name() == "boolean" || type.name() == "double" || type.name() == "float") {
  1453. if (type.is_nullable()) {
  1454. scoped_generator.append(R"~~~(
  1455. @result_expression@ JS::Value(@value@.release_value());
  1456. )~~~");
  1457. } else {
  1458. scoped_generator.append(R"~~~(
  1459. @result_expression@ JS::Value(@value@);
  1460. )~~~");
  1461. }
  1462. } else if (type.name() == "short" || type.name() == "long" || type.name() == "unsigned short") {
  1463. scoped_generator.append(R"~~~(
  1464. @result_expression@ JS::Value((i32)@value@);
  1465. )~~~");
  1466. } else if (type.name() == "unsigned long") {
  1467. scoped_generator.append(R"~~~(
  1468. @result_expression@ JS::Value((u32)@value@);
  1469. )~~~");
  1470. } else if (type.name() == "long long") {
  1471. scoped_generator.append(R"~~~(
  1472. @result_expression@ JS::Value((double)@value@);
  1473. )~~~");
  1474. } else if (type.name() == "unsigned long long") {
  1475. scoped_generator.append(R"~~~(
  1476. @result_expression@ JS::Value((double)@value@);
  1477. )~~~");
  1478. } else if (type.name() == "Location" || type.name() == "Promise" || type.name() == "Uint8Array" || type.name() == "Uint8ClampedArray" || type.name() == "any") {
  1479. scoped_generator.append(R"~~~(
  1480. @result_expression@ @value@;
  1481. )~~~");
  1482. } else if (is<IDL::UnionType>(type)) {
  1483. auto& union_type = verify_cast<IDL::UnionType>(type);
  1484. auto union_types = union_type.flattened_member_types();
  1485. auto union_generator = scoped_generator.fork();
  1486. union_generator.append(R"~~~(
  1487. @result_expression@ @value@.visit(
  1488. )~~~");
  1489. for (size_t current_union_type_index = 0; current_union_type_index < union_types.size(); ++current_union_type_index) {
  1490. auto& current_union_type = union_types.at(current_union_type_index);
  1491. auto cpp_type = IDL::idl_type_name_to_cpp_type(current_union_type, interface);
  1492. union_generator.set("current_type", cpp_type.name);
  1493. union_generator.append(R"~~~(
  1494. [&vm, &realm]([[maybe_unused]] @current_type@ const& visited_union_value@recursion_depth@) -> JS::Value {
  1495. // These may be unused.
  1496. (void)vm;
  1497. (void)realm;
  1498. )~~~");
  1499. // NOTE: While we are using const&, the underlying type for wrappable types in unions is (Nonnull)RefPtr, which are not references.
  1500. generate_wrap_statement(union_generator, DeprecatedString::formatted("visited_union_value{}", recursion_depth), current_union_type, interface, "return"sv, WrappingReference::No, recursion_depth + 1);
  1501. // End of current visit lambda.
  1502. // The last lambda cannot have a trailing comma on the closing brace, unless the type is nullable, where an extra lambda will be generated for the Empty case.
  1503. if (current_union_type_index != union_types.size() - 1 || type.is_nullable()) {
  1504. union_generator.append(R"~~~(
  1505. },
  1506. )~~~");
  1507. } else {
  1508. union_generator.append(R"~~~(
  1509. }
  1510. )~~~");
  1511. }
  1512. }
  1513. if (type.is_nullable()) {
  1514. union_generator.append(R"~~~(
  1515. [](Empty) -> JS::Value {
  1516. return JS::js_null();
  1517. }
  1518. )~~~");
  1519. }
  1520. // End of visit.
  1521. union_generator.append(R"~~~(
  1522. );
  1523. )~~~");
  1524. } else if (interface.enumerations.contains(type.name())) {
  1525. if (!interface.extended_attributes.contains("UseNewAKString")) {
  1526. scoped_generator.append(R"~~~(
  1527. @result_expression@ JS::PrimitiveString::create(vm, Bindings::idl_enum_to_deprecated_string(@value@));
  1528. )~~~");
  1529. } else {
  1530. scoped_generator.append(R"~~~(
  1531. @result_expression@ JS::PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, Bindings::idl_enum_to_string(@value@)));
  1532. )~~~");
  1533. }
  1534. } else if (interface.callback_functions.contains(type.name())) {
  1535. // https://webidl.spec.whatwg.org/#es-callback-function
  1536. auto& callback_function = interface.callback_functions.find(type.name())->value;
  1537. // The result of converting an IDL callback function type value to an ECMAScript value is a reference to the same object that the IDL callback function type value represents.
  1538. if (callback_function.is_legacy_treat_non_object_as_null && !type.is_nullable()) {
  1539. scoped_generator.append(R"~~~(
  1540. if (!@value@) {
  1541. @result_expression@ JS::js_null();
  1542. } else {
  1543. @result_expression@ @value@->callback;
  1544. }
  1545. )~~~");
  1546. } else {
  1547. scoped_generator.append(R"~~~(
  1548. @result_expression@ @value@->callback;
  1549. )~~~");
  1550. }
  1551. } else if (interface.dictionaries.contains(type.name())) {
  1552. // https://webidl.spec.whatwg.org/#es-dictionary
  1553. auto dictionary_generator = scoped_generator.fork();
  1554. dictionary_generator.append(R"~~~(
  1555. auto dictionary_object@recursion_depth@ = JS::Object::create(realm, realm.intrinsics().object_prototype());
  1556. )~~~");
  1557. auto* current_dictionary = &interface.dictionaries.find(type.name())->value;
  1558. while (true) {
  1559. for (auto& member : current_dictionary->members) {
  1560. dictionary_generator.set("member_key", member.name);
  1561. auto member_key_js_name = DeprecatedString::formatted("{}{}", make_input_acceptable_cpp(member.name.to_snakecase()), recursion_depth);
  1562. dictionary_generator.set("member_name", member_key_js_name);
  1563. auto member_value_js_name = DeprecatedString::formatted("{}_value", member_key_js_name);
  1564. dictionary_generator.set("member_value", member_value_js_name);
  1565. auto wrapped_value_name = DeprecatedString::formatted("auto wrapped_{}", member_value_js_name);
  1566. dictionary_generator.set("wrapped_value_name", wrapped_value_name);
  1567. generate_wrap_statement(dictionary_generator, DeprecatedString::formatted("{}.{}", value, member.name), member.type, interface, wrapped_value_name, WrappingReference::No, recursion_depth + 1);
  1568. dictionary_generator.append(R"~~~(
  1569. MUST(dictionary_object@recursion_depth@->create_data_property("@member_key@", @wrapped_value_name@));
  1570. )~~~");
  1571. }
  1572. if (current_dictionary->parent_name.is_null())
  1573. break;
  1574. VERIFY(interface.dictionaries.contains(current_dictionary->parent_name));
  1575. current_dictionary = &interface.dictionaries.find(current_dictionary->parent_name)->value;
  1576. }
  1577. dictionary_generator.append(R"~~~(
  1578. @result_expression@ dictionary_object@recursion_depth@;
  1579. )~~~");
  1580. } else if (type.name() == "object") {
  1581. scoped_generator.append(R"~~~(
  1582. @result_expression@ JS::Value(const_cast<JS::Object*>(@value@));
  1583. )~~~");
  1584. } else {
  1585. if (wrapping_reference == WrappingReference::No) {
  1586. scoped_generator.append(R"~~~(
  1587. @result_expression@ &const_cast<@type@&>(*@value@);
  1588. )~~~");
  1589. } else {
  1590. scoped_generator.append(R"~~~(
  1591. @result_expression@ &const_cast<@type@&>(@value@);
  1592. )~~~");
  1593. }
  1594. }
  1595. if (type.is_nullable() && !is<UnionType>(type)) {
  1596. scoped_generator.append(R"~~~(
  1597. }
  1598. )~~~");
  1599. }
  1600. }
  1601. enum class StaticFunction {
  1602. No,
  1603. Yes,
  1604. };
  1605. static void generate_return_statement(SourceGenerator& generator, IDL::Type const& return_type, IDL::Interface const& interface)
  1606. {
  1607. return generate_wrap_statement(generator, "retval", return_type, interface, "return"sv);
  1608. }
  1609. static void generate_variable_statement(SourceGenerator& generator, DeprecatedString const& variable_name, IDL::Type const& value_type, DeprecatedString const& value_name, IDL::Interface const& interface)
  1610. {
  1611. auto variable_generator = generator.fork();
  1612. variable_generator.set("variable_name", variable_name);
  1613. variable_generator.append(R"~~~(
  1614. JS::Value @variable_name@;
  1615. )~~~");
  1616. return generate_wrap_statement(generator, value_name, value_type, interface, DeprecatedString::formatted("{} = ", variable_name));
  1617. }
  1618. static void generate_function(SourceGenerator& generator, IDL::Function const& function, StaticFunction is_static_function, DeprecatedString const& class_name, DeprecatedString const& interface_fully_qualified_name, IDL::Interface const& interface)
  1619. {
  1620. auto function_generator = generator.fork();
  1621. function_generator.set("class_name", class_name);
  1622. function_generator.set("interface_fully_qualified_name", interface_fully_qualified_name);
  1623. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1624. function_generator.set("overload_suffix", function.is_overloaded ? DeprecatedString::number(function.overload_index) : DeprecatedString::empty());
  1625. if (function.extended_attributes.contains("ImplementedAs")) {
  1626. auto implemented_as = function.extended_attributes.get("ImplementedAs").value();
  1627. function_generator.set("function.cpp_name", implemented_as);
  1628. } else {
  1629. function_generator.set("function.cpp_name", make_input_acceptable_cpp(function.name.to_snakecase()));
  1630. }
  1631. function_generator.append(R"~~~(
  1632. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@function.name:snakecase@@overload_suffix@)
  1633. {
  1634. [[maybe_unused]] auto& realm = *vm.current_realm();
  1635. )~~~");
  1636. if (is_static_function == StaticFunction::No) {
  1637. function_generator.append(R"~~~(
  1638. auto* impl = TRY(impl_from(vm));
  1639. )~~~");
  1640. }
  1641. // Optimization: overloaded functions' arguments count is checked by the overload arbiter
  1642. if (!function.is_overloaded)
  1643. generate_argument_count_check(generator, function.name, function.shortest_length());
  1644. StringBuilder arguments_builder;
  1645. generate_arguments(generator, function.parameters, arguments_builder, interface);
  1646. function_generator.set(".arguments", arguments_builder.string_view());
  1647. if (is_static_function == StaticFunction::No) {
  1648. function_generator.append(R"~~~(
  1649. [[maybe_unused]] auto retval = TRY(throw_dom_exception_if_needed(vm, [&] { return impl->@function.cpp_name@(@.arguments@); }));
  1650. )~~~");
  1651. } else {
  1652. // Make sure first argument for static functions is the Realm.
  1653. if (arguments_builder.is_empty())
  1654. function_generator.set(".arguments", "vm");
  1655. else
  1656. function_generator.set(".arguments", DeprecatedString::formatted("vm, {}", arguments_builder.string_view()));
  1657. function_generator.append(R"~~~(
  1658. [[maybe_unused]] auto retval = TRY(throw_dom_exception_if_needed(vm, [&] { return @interface_fully_qualified_name@::@function.cpp_name@(@.arguments@); }));
  1659. )~~~");
  1660. }
  1661. generate_return_statement(generator, *function.return_type, interface);
  1662. function_generator.append(R"~~~(
  1663. }
  1664. )~~~");
  1665. }
  1666. // https://webidl.spec.whatwg.org/#compute-the-effective-overload-set
  1667. static EffectiveOverloadSet compute_the_effective_overload_set(auto const& overload_set)
  1668. {
  1669. // 1. Let S be an ordered set.
  1670. Vector<EffectiveOverloadSet::Item> overloads;
  1671. // 2. Let F be an ordered set with items as follows, according to the kind of effective overload set:
  1672. // Note: This is determined by the caller of generate_overload_arbiter()
  1673. // 3. Let maxarg be the maximum number of arguments the operations, legacy factory functions, or
  1674. // callback functions in F are declared to take. For variadic operations and legacy factory functions,
  1675. // the argument on which the ellipsis appears counts as a single argument.
  1676. auto overloaded_functions = overload_set.value;
  1677. auto maximum_arguments = 0;
  1678. for (auto const& function : overloaded_functions)
  1679. maximum_arguments = max(maximum_arguments, static_cast<int>(function.parameters.size()));
  1680. // 4. Let max be max(maxarg, N).
  1681. // NOTE: We don't do this step. `N` is a runtime value, so we just use `maxarg` here instead.
  1682. // Later, `generate_overload_arbiter()` produces individual overload sets for each possible N.
  1683. // 5. For each operation or extended attribute X in F:
  1684. auto overload_id = 0;
  1685. for (auto const& overload : overloaded_functions) {
  1686. // 1. Let arguments be the list of arguments X is declared to take.
  1687. auto const& arguments = overload.parameters;
  1688. // 2. Let n be the size of arguments.
  1689. int argument_count = (int)arguments.size();
  1690. // 3. Let types be a type list.
  1691. Vector<NonnullRefPtr<Type const>> types;
  1692. // 4. Let optionalityValues be an optionality list.
  1693. Vector<Optionality> optionality_values;
  1694. bool overload_is_variadic = false;
  1695. // 5. For each argument in arguments:
  1696. for (auto const& argument : arguments) {
  1697. // 1. Append the type of argument to types.
  1698. types.append(argument.type);
  1699. // 2. Append "variadic" to optionalityValues if argument is a final, variadic argument, "optional" if argument is optional, and "required" otherwise.
  1700. if (argument.variadic) {
  1701. optionality_values.append(Optionality::Variadic);
  1702. overload_is_variadic = true;
  1703. } else if (argument.optional) {
  1704. optionality_values.append(Optionality::Optional);
  1705. } else {
  1706. optionality_values.append(Optionality::Required);
  1707. }
  1708. }
  1709. // 6. Append the tuple (X, types, optionalityValues) to S.
  1710. overloads.empend(overload_id, types, optionality_values);
  1711. // 7. If X is declared to be variadic, then:
  1712. if (overload_is_variadic) {
  1713. // 1. For each i in the range n to max − 1, inclusive:
  1714. for (auto i = argument_count; i < maximum_arguments; ++i) {
  1715. // 1. Let t be a type list.
  1716. // 2. Let o be an optionality list.
  1717. // NOTE: We hold both of these in an Item instead.
  1718. EffectiveOverloadSet::Item item;
  1719. item.callable_id = overload_id;
  1720. // 3. For each j in the range 0 to n − 1, inclusive:
  1721. for (auto j = 0; j < argument_count; ++j) {
  1722. // 1. Append types[j] to t.
  1723. item.types.append(types[j]);
  1724. // 2. Append optionalityValues[j] to o.
  1725. item.optionality_values.append(optionality_values[j]);
  1726. }
  1727. // 4. For each j in the range n to i, inclusive:
  1728. for (auto j = argument_count; j <= i; ++j) {
  1729. // 1. Append types[n − 1] to t.
  1730. item.types.append(types[argument_count - 1]);
  1731. // 2. Append "variadic" to o.
  1732. item.optionality_values.append(Optionality::Variadic);
  1733. }
  1734. // 5. Append the tuple (X, t, o) to S.
  1735. overloads.append(move(item));
  1736. }
  1737. }
  1738. // 8. Let i be n − 1.
  1739. auto i = argument_count - 1;
  1740. // 9. While i ≥ 0:
  1741. while (i >= 0) {
  1742. // 1. If arguments[i] is not optional (i.e., it is not marked as "optional" and is not a final, variadic argument), then break.
  1743. if (!arguments[i].optional && !arguments[i].variadic)
  1744. break;
  1745. // 2. Let t be a type list.
  1746. // 3. Let o be an optionality list.
  1747. // NOTE: We hold both of these in an Item instead.
  1748. EffectiveOverloadSet::Item item;
  1749. item.callable_id = overload_id;
  1750. // 4. For each j in the range 0 to i − 1, inclusive:
  1751. for (auto j = 0; j < i; ++j) {
  1752. // 1. Append types[j] to t.
  1753. item.types.append(types[j]);
  1754. // 2. Append optionalityValues[j] to o.
  1755. item.optionality_values.append(optionality_values[j]);
  1756. }
  1757. // 5. Append the tuple (X, t, o) to S.
  1758. overloads.append(move(item));
  1759. // 6. Set i to i − 1.
  1760. --i;
  1761. }
  1762. overload_id++;
  1763. }
  1764. return EffectiveOverloadSet { move(overloads) };
  1765. }
  1766. static DeprecatedString generate_constructor_for_idl_type(Type const& type)
  1767. {
  1768. auto append_type_list = [](auto& builder, auto const& type_list) {
  1769. bool first = true;
  1770. for (auto const& child_type : type_list) {
  1771. if (first) {
  1772. first = false;
  1773. } else {
  1774. builder.append(", "sv);
  1775. }
  1776. builder.append(generate_constructor_for_idl_type(child_type));
  1777. }
  1778. };
  1779. switch (type.kind()) {
  1780. case Type::Kind::Plain:
  1781. return DeprecatedString::formatted("make_ref_counted<IDL::Type>(\"{}\", {})", type.name(), type.is_nullable());
  1782. case Type::Kind::Parameterized: {
  1783. auto const& parameterized_type = type.as_parameterized();
  1784. StringBuilder builder;
  1785. builder.appendff("make_ref_counted<IDL::ParameterizedTypeType>(\"{}\", {}, Vector<NonnullRefPtr<IDL::Type const>> {{", type.name(), type.is_nullable());
  1786. append_type_list(builder, parameterized_type.parameters());
  1787. builder.append("})"sv);
  1788. return builder.to_deprecated_string();
  1789. }
  1790. case Type::Kind::Union: {
  1791. auto const& union_type = type.as_union();
  1792. StringBuilder builder;
  1793. builder.appendff("make_ref_counted<IDL::UnionType>(\"{}\", {}, Vector<NonnullRefPtr<IDL::Type const>> {{", type.name(), type.is_nullable());
  1794. append_type_list(builder, union_type.member_types());
  1795. builder.append("})"sv);
  1796. return builder.to_deprecated_string();
  1797. }
  1798. }
  1799. VERIFY_NOT_REACHED();
  1800. }
  1801. static void generate_overload_arbiter(SourceGenerator& generator, auto const& overload_set, DeprecatedString const& class_name)
  1802. {
  1803. auto function_generator = generator.fork();
  1804. function_generator.set("class_name", class_name);
  1805. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(overload_set.key.to_snakecase()));
  1806. function_generator.append(R"~~~(
  1807. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@function.name:snakecase@)
  1808. {
  1809. Optional<IDL::EffectiveOverloadSet> effective_overload_set;
  1810. )~~~");
  1811. auto all_possible_effective_overloads = compute_the_effective_overload_set(overload_set);
  1812. auto overloads_set = all_possible_effective_overloads.items();
  1813. auto maximum_argument_count = 0u;
  1814. for (auto const& overload : overloads_set)
  1815. maximum_argument_count = max(maximum_argument_count, overload.types.size());
  1816. function_generator.set("max_argument_count", DeprecatedString::number(maximum_argument_count));
  1817. function_generator.appendln(" switch (min(@max_argument_count@, vm.argument_count())) {");
  1818. // Generate the effective overload set for each argument count.
  1819. // This skips part of the Overload Resolution Algorithm https://webidl.spec.whatwg.org/#es-overloads
  1820. // Namely, since that discards any overloads that don't have the exact number of arguments that were given,
  1821. // we simply only provide the overloads that do have that number of arguments.
  1822. for (auto argument_count = 0u; argument_count <= maximum_argument_count; ++argument_count) {
  1823. // FIXME: Calculate the distinguishing argument index now instead of at runtime.
  1824. auto effective_overload_count = 0;
  1825. for (auto const& overload : overloads_set) {
  1826. if (overload.types.size() == argument_count)
  1827. effective_overload_count++;
  1828. }
  1829. if (effective_overload_count == 0)
  1830. continue;
  1831. function_generator.set("current_argument_count", DeprecatedString::number(argument_count));
  1832. function_generator.set("overload_count", DeprecatedString::number(effective_overload_count));
  1833. function_generator.appendln(R"~~~(
  1834. case @current_argument_count@: {
  1835. Vector<IDL::EffectiveOverloadSet::Item> overloads;
  1836. overloads.ensure_capacity(@overload_count@);
  1837. )~~~");
  1838. for (auto& overload : overloads_set) {
  1839. if (overload.types.size() != argument_count)
  1840. continue;
  1841. StringBuilder types_builder;
  1842. types_builder.append("Vector<NonnullRefPtr<IDL::Type const>> { "sv);
  1843. StringBuilder optionality_builder;
  1844. optionality_builder.append("Vector<IDL::Optionality> { "sv);
  1845. for (auto i = 0u; i < overload.types.size(); ++i) {
  1846. if (i > 0) {
  1847. types_builder.append(", "sv);
  1848. optionality_builder.append(", "sv);
  1849. }
  1850. types_builder.append(generate_constructor_for_idl_type(overload.types[i]));
  1851. optionality_builder.append("IDL::Optionality::"sv);
  1852. switch (overload.optionality_values[i]) {
  1853. case Optionality::Required:
  1854. optionality_builder.append("Required"sv);
  1855. break;
  1856. case Optionality::Optional:
  1857. optionality_builder.append("Optional"sv);
  1858. break;
  1859. case Optionality::Variadic:
  1860. optionality_builder.append("Variadic"sv);
  1861. break;
  1862. }
  1863. }
  1864. types_builder.append("}"sv);
  1865. optionality_builder.append("}"sv);
  1866. function_generator.set("overload.callable_id", DeprecatedString::number(overload.callable_id));
  1867. function_generator.set("overload.types", types_builder.to_deprecated_string());
  1868. function_generator.set("overload.optionality_values", optionality_builder.to_deprecated_string());
  1869. function_generator.appendln(" overloads.empend(@overload.callable_id@, @overload.types@, @overload.optionality_values@);");
  1870. }
  1871. function_generator.append(R"~~~(
  1872. effective_overload_set.emplace(move(overloads));
  1873. break;
  1874. }
  1875. )~~~");
  1876. }
  1877. function_generator.append(R"~~~(
  1878. }
  1879. if (!effective_overload_set.has_value())
  1880. return vm.throw_completion<JS::TypeError>(JS::ErrorType::OverloadResolutionFailed);
  1881. auto chosen_overload = TRY(WebIDL::resolve_overload(vm, effective_overload_set.value()));
  1882. switch (chosen_overload.callable_id) {
  1883. )~~~");
  1884. for (auto i = 0u; i < overload_set.value.size(); ++i) {
  1885. function_generator.set("overload_id", DeprecatedString::number(i));
  1886. function_generator.append(R"~~~(
  1887. case @overload_id@:
  1888. return @function.name:snakecase@@overload_id@(vm);
  1889. )~~~");
  1890. }
  1891. function_generator.append(R"~~~(
  1892. default:
  1893. VERIFY_NOT_REACHED();
  1894. }
  1895. }
  1896. )~~~");
  1897. }
  1898. static void generate_prototype_or_global_mixin_declarations(IDL::Interface const& interface, StringBuilder& builder)
  1899. {
  1900. SourceGenerator generator { builder };
  1901. for (auto const& overload_set : interface.overload_sets) {
  1902. auto function_generator = generator.fork();
  1903. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(overload_set.key.to_snakecase()));
  1904. function_generator.append(R"~~~(
  1905. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1906. )~~~");
  1907. if (overload_set.value.size() > 1) {
  1908. for (auto i = 0u; i < overload_set.value.size(); ++i) {
  1909. function_generator.set("overload_suffix", DeprecatedString::number(i));
  1910. function_generator.append(R"~~~(
  1911. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@@overload_suffix@);
  1912. )~~~");
  1913. }
  1914. }
  1915. }
  1916. if (interface.has_stringifier) {
  1917. auto stringifier_generator = generator.fork();
  1918. stringifier_generator.append(R"~~~(
  1919. JS_DECLARE_NATIVE_FUNCTION(to_string);
  1920. )~~~");
  1921. }
  1922. if (interface.pair_iterator_types.has_value()) {
  1923. auto iterator_generator = generator.fork();
  1924. iterator_generator.append(R"~~~(
  1925. JS_DECLARE_NATIVE_FUNCTION(entries);
  1926. JS_DECLARE_NATIVE_FUNCTION(for_each);
  1927. JS_DECLARE_NATIVE_FUNCTION(keys);
  1928. JS_DECLARE_NATIVE_FUNCTION(values);
  1929. )~~~");
  1930. }
  1931. for (auto& attribute : interface.attributes) {
  1932. auto attribute_generator = generator.fork();
  1933. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1934. attribute_generator.append(R"~~~(
  1935. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_getter);
  1936. )~~~");
  1937. if (!attribute.readonly || attribute.extended_attributes.contains("Replaceable"sv) || attribute.extended_attributes.contains("PutForwards"sv)) {
  1938. attribute_generator.append(R"~~~(
  1939. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_setter);
  1940. )~~~");
  1941. }
  1942. }
  1943. generator.append(R"~~~(
  1944. };
  1945. )~~~");
  1946. for (auto& it : interface.enumerations) {
  1947. if (!it.value.is_original_definition)
  1948. continue;
  1949. auto enum_generator = generator.fork();
  1950. enum_generator.set("enum.type.name", it.key);
  1951. enum_generator.append(R"~~~(
  1952. enum class @enum.type.name@ {
  1953. )~~~");
  1954. for (auto& entry : it.value.translated_cpp_names) {
  1955. enum_generator.set("enum.entry", entry.value);
  1956. enum_generator.append(R"~~~(
  1957. @enum.entry@,
  1958. )~~~");
  1959. }
  1960. enum_generator.append(R"~~~(
  1961. };
  1962. )~~~");
  1963. if (!interface.extended_attributes.contains("UseNewAKString")) {
  1964. enum_generator.append(R"~~~(
  1965. inline DeprecatedString idl_enum_to_deprecated_string(@enum.type.name@ value) {
  1966. switch(value) {
  1967. )~~~");
  1968. for (auto& entry : it.value.translated_cpp_names) {
  1969. enum_generator.set("enum.entry", entry.value);
  1970. enum_generator.set("enum.string", entry.key);
  1971. enum_generator.append(R"~~~(
  1972. case @enum.type.name@::@enum.entry@: return "@enum.string@";
  1973. )~~~");
  1974. }
  1975. enum_generator.append(R"~~~(
  1976. default: return "<unknown>";
  1977. };
  1978. }
  1979. )~~~");
  1980. } else {
  1981. enum_generator.append(R"~~~(
  1982. inline ErrorOr<String> idl_enum_to_string(@enum.type.name@ value) {
  1983. switch(value) {
  1984. )~~~");
  1985. for (auto& entry : it.value.translated_cpp_names) {
  1986. enum_generator.set("enum.entry", entry.value);
  1987. enum_generator.set("enum.string", entry.key);
  1988. enum_generator.append(R"~~~(
  1989. case @enum.type.name@::@enum.entry@: return "@enum.string@"_string;
  1990. )~~~");
  1991. }
  1992. enum_generator.append(R"~~~(
  1993. default: return "<unknown>"_string;
  1994. };
  1995. }
  1996. )~~~");
  1997. }
  1998. }
  1999. }
  2000. // https://webidl.spec.whatwg.org/#create-an-inheritance-stack
  2001. static Vector<Interface const&> create_an_inheritance_stack(IDL::Interface const& start_interface)
  2002. {
  2003. // 1. Let stack be a new stack.
  2004. Vector<Interface const&> inheritance_chain;
  2005. // 2. Push I onto stack.
  2006. inheritance_chain.append(start_interface);
  2007. // 3. While I inherits from an interface,
  2008. auto const* current_interface = &start_interface;
  2009. while (current_interface && !current_interface->parent_name.is_empty()) {
  2010. // 1. Let I be that interface.
  2011. auto imported_interface_iterator = start_interface.imported_modules.find_if([&current_interface](IDL::Interface const& imported_interface) {
  2012. return imported_interface.name == current_interface->parent_name;
  2013. });
  2014. // Inherited interfaces must have their IDL files imported.
  2015. VERIFY(imported_interface_iterator != start_interface.imported_modules.end());
  2016. // 2. Push I onto stack.
  2017. inheritance_chain.append(*imported_interface_iterator);
  2018. }
  2019. // 4. Return stack.
  2020. return inheritance_chain;
  2021. }
  2022. // https://webidl.spec.whatwg.org/#collect-attribute-values-of-an-inheritance-stack
  2023. static void collect_attribute_values_of_an_inheritance_stack(SourceGenerator& function_generator, Vector<Interface const&> const& inheritance_chain)
  2024. {
  2025. // 1. Let I be the result of popping from stack.
  2026. // 3. If stack is not empty, then invoke collect attribute values of an inheritance stack given object, stack, and map.
  2027. for (auto const& interface_in_chain : inheritance_chain.in_reverse()) {
  2028. // 2. Invoke collect attribute values given object, I, and map.
  2029. // https://webidl.spec.whatwg.org/#collect-attribute-values
  2030. // 1. If a toJSON operation with a [Default] extended attribute is declared on I, then for each exposed regular attribute attr that is an interface member of I, in order:
  2031. auto to_json_iterator = interface_in_chain.functions.find_if([](IDL::Function const& function) {
  2032. return function.name == "toJSON" && function.extended_attributes.contains("Default");
  2033. });
  2034. if (to_json_iterator == interface_in_chain.functions.end())
  2035. continue;
  2036. // FIXME: Check if the attributes are exposed.
  2037. // 1. Let id be the identifier of attr.
  2038. // 2. Let value be the result of running the getter steps of attr with object as this.
  2039. // 3. If value is a JSON type, then set map[id] to value.
  2040. // Since we are flatly generating the attributes, the consequent is replaced with these steps from "default toJSON steps":
  2041. // 5. For each key → value of map,
  2042. // 1. Let k be key converted to an ECMAScript value.
  2043. // 2. Let v be value converted to an ECMAScript value.
  2044. // 3. Perform ! CreateDataProperty(result, k, v).
  2045. // NOTE: Functions, constructors and static functions cannot be JSON types, so they're not checked here.
  2046. for (auto& attribute : interface_in_chain.attributes) {
  2047. if (!attribute.type->is_json(interface_in_chain))
  2048. continue;
  2049. auto attribute_generator = function_generator.fork();
  2050. auto return_value_name = DeprecatedString::formatted("{}_retval", attribute.name.to_snakecase());
  2051. attribute_generator.set("attribute.name", attribute.name);
  2052. attribute_generator.set("attribute.return_value_name", return_value_name);
  2053. if (attribute.extended_attributes.contains("ImplementedAs")) {
  2054. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  2055. attribute_generator.set("attribute.cpp_name", implemented_as);
  2056. } else {
  2057. attribute_generator.set("attribute.cpp_name", attribute.name.to_snakecase());
  2058. }
  2059. if (attribute.extended_attributes.contains("Reflect")) {
  2060. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  2061. if (attribute_name.is_null())
  2062. attribute_name = attribute.name;
  2063. attribute_name = make_input_acceptable_cpp(attribute_name);
  2064. attribute_generator.set("attribute.reflect_name", attribute_name);
  2065. } else {
  2066. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  2067. }
  2068. if (attribute.extended_attributes.contains("Reflect")) {
  2069. if (attribute.type->name() != "boolean") {
  2070. attribute_generator.append(R"~~~(
  2071. auto @attribute.return_value_name@ = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  2072. )~~~");
  2073. } else {
  2074. attribute_generator.append(R"~~~(
  2075. auto @attribute.return_value_name@ = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  2076. )~~~");
  2077. }
  2078. } else {
  2079. attribute_generator.append(R"~~~(
  2080. auto @attribute.return_value_name@ = TRY(throw_dom_exception_if_needed(vm, [&] { return impl->@attribute.cpp_name@(); }));
  2081. )~~~");
  2082. }
  2083. generate_wrap_statement(attribute_generator, return_value_name, attribute.type, interface_in_chain, DeprecatedString::formatted("auto {}_wrapped =", return_value_name));
  2084. attribute_generator.append(R"~~~(
  2085. MUST_OR_THROW_OOM(result->create_data_property("@attribute.name@", @attribute.return_value_name@_wrapped));
  2086. )~~~");
  2087. }
  2088. for (auto& constant : interface_in_chain.constants) {
  2089. auto constant_generator = function_generator.fork();
  2090. constant_generator.set("constant.name", constant.name);
  2091. generate_wrap_statement(constant_generator, constant.value, constant.type, interface_in_chain, DeprecatedString::formatted("auto constant_{}_value =", constant.name));
  2092. constant_generator.append(R"~~~(
  2093. MUST_OR_THROW_OOM(result->create_data_property("@constant.name@", constant_@constant.name@_value));
  2094. )~~~");
  2095. }
  2096. }
  2097. }
  2098. // https://webidl.spec.whatwg.org/#default-tojson-steps
  2099. static void generate_default_to_json_function(SourceGenerator& generator, DeprecatedString const& class_name, IDL::Interface const& start_interface)
  2100. {
  2101. // NOTE: This is done heavily out of order since the spec mixes parse time and run time type information together.
  2102. auto function_generator = generator.fork();
  2103. function_generator.set("class_name", class_name);
  2104. // 4. Let result be OrdinaryObjectCreate(%Object.prototype%).
  2105. function_generator.append(R"~~~(
  2106. JS_DEFINE_NATIVE_FUNCTION(@class_name@::to_json)
  2107. {
  2108. auto& realm = *vm.current_realm();
  2109. auto* impl = TRY(impl_from(vm));
  2110. auto result = JS::Object::create(realm, realm.intrinsics().object_prototype());
  2111. )~~~");
  2112. // 1. Let map be a new ordered map.
  2113. // NOTE: Instead of making a map, we flatly generate the attributes.
  2114. // 2. Let stack be the result of creating an inheritance stack for interface I.
  2115. auto inheritance_chain = create_an_inheritance_stack(start_interface);
  2116. // 3. Invoke collect attribute values of an inheritance stack given this, stack, and map.
  2117. collect_attribute_values_of_an_inheritance_stack(function_generator, inheritance_chain);
  2118. // NOTE: Step 5 is done as part of collect_attribute_values_of_an_inheritance_stack, due to us flatly generating the attributes.
  2119. // 6. Return result.
  2120. function_generator.append(R"~~~(
  2121. return result;
  2122. }
  2123. )~~~");
  2124. }
  2125. static void generate_prototype_or_global_mixin_definitions(IDL::Interface const& interface, StringBuilder& builder)
  2126. {
  2127. SourceGenerator generator { builder };
  2128. auto is_global_interface = interface.extended_attributes.contains("Global");
  2129. auto class_name = is_global_interface ? interface.global_mixin_class : interface.prototype_class;
  2130. generator.set("name", interface.name);
  2131. generator.set("namespaced_name", interface.namespaced_name);
  2132. generator.set("class_name", class_name);
  2133. generator.set("fully_qualified_name", interface.fully_qualified_name);
  2134. if (interface.pair_iterator_types.has_value()) {
  2135. generator.set("iterator_name", DeprecatedString::formatted("{}Iterator", interface.name));
  2136. }
  2137. if (is_global_interface) {
  2138. // Doing this with macros is not super nice, but simplifies codegen a lot.
  2139. generator.append(R"~~~(
  2140. #define define_direct_property (object.define_direct_property)
  2141. #define define_native_accessor (object.define_native_accessor)
  2142. #define define_native_function (object.define_native_function)
  2143. JS::ThrowCompletionOr<void> @class_name@::initialize(JS::Realm& realm, JS::Object& object)
  2144. {
  2145. )~~~");
  2146. } else {
  2147. generator.append(R"~~~(
  2148. JS::ThrowCompletionOr<void> @class_name@::initialize(JS::Realm& realm)
  2149. {
  2150. )~~~");
  2151. }
  2152. // FIXME: Currently almost everything gets default_attributes but it should be configurable per attribute.
  2153. // See the spec links for details
  2154. generator.append(R"~~~(
  2155. [[maybe_unused]] auto& vm = realm.vm();
  2156. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;
  2157. )~~~");
  2158. if (interface.has_unscopable_member) {
  2159. generator.append(R"~~~(
  2160. auto unscopable_object = JS::Object::create(realm, nullptr);
  2161. )~~~");
  2162. }
  2163. // https://webidl.spec.whatwg.org/#es-attributes
  2164. for (auto& attribute : interface.attributes) {
  2165. auto attribute_generator = generator.fork();
  2166. attribute_generator.set("attribute.name", attribute.name);
  2167. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  2168. if (!attribute.readonly || attribute.extended_attributes.contains("Replaceable"sv) || attribute.extended_attributes.contains("PutForwards"sv))
  2169. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  2170. else
  2171. attribute_generator.set("attribute.setter_callback", "nullptr");
  2172. if (attribute.extended_attributes.contains("Unscopable")) {
  2173. attribute_generator.append(R"~~~(
  2174. MUST(unscopable_object->create_data_property("@attribute.name@", JS::Value(true)));
  2175. )~~~");
  2176. }
  2177. attribute_generator.append(R"~~~(
  2178. define_native_accessor(realm, "@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  2179. )~~~");
  2180. }
  2181. // https://webidl.spec.whatwg.org/#es-constants
  2182. for (auto& constant : interface.constants) {
  2183. // FIXME: Do constants need to be added to the unscopable list?
  2184. auto constant_generator = generator.fork();
  2185. constant_generator.set("constant.name", constant.name);
  2186. generate_wrap_statement(constant_generator, constant.value, constant.type, interface, DeprecatedString::formatted("auto constant_{}_value =", constant.name));
  2187. constant_generator.append(R"~~~(
  2188. define_direct_property("@constant.name@", constant_@constant.name@_value, JS::Attribute::Enumerable);
  2189. )~~~");
  2190. }
  2191. // https://webidl.spec.whatwg.org/#es-operations
  2192. for (auto const& overload_set : interface.overload_sets) {
  2193. auto function_generator = generator.fork();
  2194. function_generator.set("function.name", overload_set.key);
  2195. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(overload_set.key.to_snakecase()));
  2196. function_generator.set("function.length", DeprecatedString::number(get_shortest_function_length(overload_set.value)));
  2197. // FIXME: What if only some of the overloads are Unscopable?
  2198. if (any_of(overload_set.value, [](auto const& function) { return function.extended_attributes.contains("Unscopable"); })) {
  2199. function_generator.append(R"~~~(
  2200. MUST(unscopable_object->create_data_property("@function.name@", JS::Value(true)));
  2201. )~~~");
  2202. }
  2203. function_generator.append(R"~~~(
  2204. define_native_function(realm, "@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  2205. )~~~");
  2206. }
  2207. if (interface.has_stringifier) {
  2208. // FIXME: Do stringifiers need to be added to the unscopable list?
  2209. auto stringifier_generator = generator.fork();
  2210. stringifier_generator.append(R"~~~(
  2211. define_native_function(realm, "toString", to_string, 0, default_attributes);
  2212. )~~~");
  2213. }
  2214. // https://webidl.spec.whatwg.org/#define-the-iteration-methods
  2215. // This applies to this if block and the following if block.
  2216. if (interface.indexed_property_getter.has_value()) {
  2217. auto iterator_generator = generator.fork();
  2218. iterator_generator.append(R"~~~(
  2219. define_direct_property(*vm.well_known_symbol_iterator(), realm.intrinsics().array_prototype()->get_without_side_effects(vm.names.values), JS::Attribute::Configurable | JS::Attribute::Writable);
  2220. )~~~");
  2221. if (interface.value_iterator_type.has_value()) {
  2222. iterator_generator.append(R"~~~(
  2223. define_direct_property(vm.names.entries, realm.intrinsics().array_prototype()->get_without_side_effects(vm.names.entries), default_attributes);
  2224. define_direct_property(vm.names.keys, realm.intrinsics().array_prototype()->get_without_side_effects(vm.names.keys), default_attributes);
  2225. define_direct_property(vm.names.values, realm.intrinsics().array_prototype()->get_without_side_effects(vm.names.values), default_attributes);
  2226. define_direct_property(vm.names.forEach, realm.intrinsics().array_prototype()->get_without_side_effects(vm.names.forEach), default_attributes);
  2227. )~~~");
  2228. }
  2229. }
  2230. if (interface.pair_iterator_types.has_value()) {
  2231. // FIXME: Do pair iterators need to be added to the unscopable list?
  2232. auto iterator_generator = generator.fork();
  2233. iterator_generator.append(R"~~~(
  2234. define_native_function(realm, vm.names.entries, entries, 0, default_attributes);
  2235. define_native_function(realm, vm.names.forEach, for_each, 1, default_attributes);
  2236. define_native_function(realm, vm.names.keys, keys, 0, default_attributes);
  2237. define_native_function(realm, vm.names.values, values, 0, default_attributes);
  2238. define_direct_property(*vm.well_known_symbol_iterator(), get_without_side_effects(vm.names.entries), JS::Attribute::Configurable | JS::Attribute::Writable);
  2239. )~~~");
  2240. }
  2241. if (interface.has_unscopable_member) {
  2242. generator.append(R"~~~(
  2243. define_direct_property(*vm.well_known_symbol_unscopables(), unscopable_object, JS::Attribute::Configurable);
  2244. )~~~");
  2245. }
  2246. generator.append(R"~~~(
  2247. define_direct_property(*vm.well_known_symbol_to_string_tag(), MUST_OR_THROW_OOM(JS::PrimitiveString::create(vm, "@namespaced_name@"sv)), JS::Attribute::Configurable);
  2248. )~~~");
  2249. if (!is_global_interface) {
  2250. generator.append(R"~~~(
  2251. MUST_OR_THROW_OOM(Base::initialize(realm));
  2252. )~~~");
  2253. }
  2254. generator.append(R"~~~(
  2255. return {};
  2256. }
  2257. )~~~");
  2258. if (!interface.attributes.is_empty() || !interface.functions.is_empty() || interface.has_stringifier) {
  2259. generator.append(R"~~~(
  2260. static JS::ThrowCompletionOr<@fully_qualified_name@*> impl_from(JS::VM& vm)
  2261. {
  2262. auto this_value = vm.this_value();
  2263. JS::Object* this_object = nullptr;
  2264. if (this_value.is_nullish())
  2265. this_object = &vm.current_realm()->global_object();
  2266. else
  2267. this_object = TRY(this_value.to_object(vm));
  2268. )~~~");
  2269. if (interface.name.is_one_of("EventTarget", "Window")) {
  2270. generator.append(R"~~~(
  2271. if (is<HTML::Window>(this_object)) {
  2272. return static_cast<HTML::Window*>(this_object);
  2273. }
  2274. if (is<HTML::WindowProxy>(this_object)) {
  2275. return static_cast<HTML::WindowProxy*>(this_object)->window().ptr();
  2276. }
  2277. )~~~");
  2278. }
  2279. generator.append(R"~~~(
  2280. if (!is<@fully_qualified_name@>(this_object))
  2281. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@namespaced_name@");
  2282. return static_cast<@fully_qualified_name@*>(this_object);
  2283. }
  2284. )~~~");
  2285. }
  2286. for (auto& attribute : interface.attributes) {
  2287. auto attribute_generator = generator.fork();
  2288. attribute_generator.set("attribute.name", attribute.name);
  2289. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  2290. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  2291. if (attribute.extended_attributes.contains("ImplementedAs")) {
  2292. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  2293. attribute_generator.set("attribute.cpp_name", implemented_as);
  2294. } else {
  2295. attribute_generator.set("attribute.cpp_name", attribute.name.to_snakecase());
  2296. }
  2297. if (attribute.extended_attributes.contains("Reflect")) {
  2298. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  2299. if (attribute_name.is_null())
  2300. attribute_name = attribute.name;
  2301. attribute_name = make_input_acceptable_cpp(attribute_name);
  2302. attribute_generator.set("attribute.reflect_name", attribute_name);
  2303. } else {
  2304. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  2305. }
  2306. attribute_generator.append(R"~~~(
  2307. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@attribute.getter_callback@)
  2308. {
  2309. [[maybe_unused]] auto& realm = *vm.current_realm();
  2310. auto* impl = TRY(impl_from(vm));
  2311. )~~~");
  2312. if (attribute.extended_attributes.contains("Reflect")) {
  2313. if (attribute.type->name() != "boolean") {
  2314. attribute_generator.append(R"~~~(
  2315. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  2316. )~~~");
  2317. } else {
  2318. attribute_generator.append(R"~~~(
  2319. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  2320. )~~~");
  2321. }
  2322. } else {
  2323. attribute_generator.append(R"~~~(
  2324. auto retval = TRY(throw_dom_exception_if_needed(vm, [&] { return impl->@attribute.cpp_name@(); }));
  2325. )~~~");
  2326. }
  2327. generate_return_statement(generator, *attribute.type, interface);
  2328. attribute_generator.append(R"~~~(
  2329. }
  2330. )~~~");
  2331. if (!attribute.readonly) {
  2332. attribute_generator.append(R"~~~(
  2333. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@attribute.setter_callback@)
  2334. {
  2335. [[maybe_unused]] auto& realm = *vm.current_realm();
  2336. auto* impl = TRY(impl_from(vm));
  2337. auto value = vm.argument(0);
  2338. )~~~");
  2339. generate_to_cpp(generator, attribute, "value", "", "cpp_value", interface, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  2340. if (attribute.extended_attributes.contains("Reflect")) {
  2341. if (attribute.type->name() != "boolean") {
  2342. attribute_generator.append(R"~~~(
  2343. MUST(impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value));
  2344. )~~~");
  2345. } else {
  2346. attribute_generator.append(R"~~~(
  2347. if (!cpp_value)
  2348. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  2349. else
  2350. MUST(impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, DeprecatedString::empty()));
  2351. )~~~");
  2352. }
  2353. } else {
  2354. attribute_generator.append(R"~~~(
  2355. TRY(throw_dom_exception_if_needed(vm, [&] { return impl->set_@attribute.cpp_name@(cpp_value); }));
  2356. )~~~");
  2357. }
  2358. attribute_generator.append(R"~~~(
  2359. return JS::js_undefined();
  2360. }
  2361. )~~~");
  2362. } else if (attribute.extended_attributes.contains("Replaceable"sv)) {
  2363. attribute_generator.append(R"~~~(
  2364. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@attribute.setter_callback@)
  2365. {
  2366. auto this_value = vm.this_value();
  2367. if (!this_value.is_object() || !is<@fully_qualified_name@>(this_value.as_object()))
  2368. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@namespaced_name@");
  2369. TRY(this_value.as_object().internal_define_own_property("@attribute.name@", JS::PropertyDescriptor { .value = vm.argument(0), .writable = true }));
  2370. return JS::js_undefined();
  2371. }
  2372. )~~~");
  2373. } else if (auto put_forwards_identifier = attribute.extended_attributes.get("PutForwards"sv); put_forwards_identifier.has_value()) {
  2374. attribute_generator.set("put_forwards_identifier"sv, *put_forwards_identifier);
  2375. attribute_generator.append(R"~~~(
  2376. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@attribute.setter_callback@)
  2377. {
  2378. auto* impl = TRY(impl_from(vm));
  2379. auto value = vm.argument(0);
  2380. auto receiver = TRY(throw_dom_exception_if_needed(vm, [&]() { return impl->@attribute.cpp_name@(); }));
  2381. TRY(receiver->set(JS::PropertyKey { "@put_forwards_identifier@" }, value, JS::Object::ShouldThrowExceptions::Yes));
  2382. return JS::js_undefined();
  2383. }
  2384. )~~~");
  2385. }
  2386. }
  2387. // Implementation: Functions
  2388. for (auto& function : interface.functions) {
  2389. if (function.extended_attributes.contains("Default")) {
  2390. if (function.name == "toJSON"sv && function.return_type->name() == "object"sv) {
  2391. generate_default_to_json_function(generator, class_name, interface);
  2392. continue;
  2393. }
  2394. dbgln("Unknown default operation: {} {}()", function.return_type->name(), function.name);
  2395. VERIFY_NOT_REACHED();
  2396. }
  2397. generate_function(generator, function, StaticFunction::No, class_name, interface.fully_qualified_name, interface);
  2398. }
  2399. for (auto const& overload_set : interface.overload_sets) {
  2400. if (overload_set.value.size() == 1)
  2401. continue;
  2402. generate_overload_arbiter(generator, overload_set, class_name);
  2403. }
  2404. if (interface.has_stringifier) {
  2405. auto stringifier_generator = generator.fork();
  2406. stringifier_generator.set("class_name", class_name);
  2407. if (interface.stringifier_attribute.has_value())
  2408. stringifier_generator.set("attribute.cpp_getter_name", interface.stringifier_attribute->to_snakecase());
  2409. stringifier_generator.append(R"~~~(
  2410. JS_DEFINE_NATIVE_FUNCTION(@class_name@::to_string)
  2411. {
  2412. [[maybe_unused]] auto& realm = *vm.current_realm();
  2413. auto* impl = TRY(impl_from(vm));
  2414. )~~~");
  2415. if (interface.stringifier_attribute.has_value()) {
  2416. stringifier_generator.append(R"~~~(
  2417. auto retval = TRY(throw_dom_exception_if_needed(vm, [&] { return impl->@attribute.cpp_getter_name@(); }));
  2418. )~~~");
  2419. } else {
  2420. if (!interface.extended_attributes.contains("UseNewAKString")) {
  2421. stringifier_generator.append(R"~~~(
  2422. auto retval = TRY(throw_dom_exception_if_needed(vm, [&] { return impl->to_deprecated_string(); }));
  2423. )~~~");
  2424. } else {
  2425. stringifier_generator.append(R"~~~(
  2426. auto retval = TRY(throw_dom_exception_if_needed(vm, [&] { return impl->to_string(); }));
  2427. )~~~");
  2428. }
  2429. }
  2430. stringifier_generator.append(R"~~~(
  2431. return JS::PrimitiveString::create(vm, move(retval));
  2432. }
  2433. )~~~");
  2434. }
  2435. if (interface.pair_iterator_types.has_value()) {
  2436. auto iterator_generator = generator.fork();
  2437. iterator_generator.append(R"~~~(
  2438. JS_DEFINE_NATIVE_FUNCTION(@class_name@::entries)
  2439. {
  2440. auto* impl = TRY(impl_from(vm));
  2441. return TRY(throw_dom_exception_if_needed(vm, [&] { return @iterator_name@::create(*impl, Object::PropertyKind::KeyAndValue); }));
  2442. }
  2443. JS_DEFINE_NATIVE_FUNCTION(@class_name@::for_each)
  2444. {
  2445. [[maybe_unused]] auto& realm = *vm.current_realm();
  2446. auto* impl = TRY(impl_from(vm));
  2447. auto callback = vm.argument(0);
  2448. if (!callback.is_function())
  2449. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, TRY_OR_THROW_OOM(vm, callback.to_string_without_side_effects()));
  2450. auto this_value = vm.this_value();
  2451. TRY(impl->for_each([&](auto key, auto value) -> JS::ThrowCompletionOr<void> {
  2452. )~~~");
  2453. generate_variable_statement(iterator_generator, "wrapped_key", interface.pair_iterator_types->get<0>(), "key", interface);
  2454. generate_variable_statement(iterator_generator, "wrapped_value", interface.pair_iterator_types->get<1>(), "value", interface);
  2455. iterator_generator.append(R"~~~(
  2456. TRY(call(vm, callback.as_function(), vm.argument(1), wrapped_value, wrapped_key, this_value));
  2457. return {};
  2458. }));
  2459. return JS::js_undefined();
  2460. }
  2461. JS_DEFINE_NATIVE_FUNCTION(@class_name@::keys)
  2462. {
  2463. auto* impl = TRY(impl_from(vm));
  2464. return TRY(throw_dom_exception_if_needed(vm, [&] { return @iterator_name@::create(*impl, Object::PropertyKind::Key); }));
  2465. }
  2466. JS_DEFINE_NATIVE_FUNCTION(@class_name@::values)
  2467. {
  2468. auto* impl = TRY(impl_from(vm));
  2469. return TRY(throw_dom_exception_if_needed(vm, [&] { return @iterator_name@::create(*impl, Object::PropertyKind::Value); }));
  2470. }
  2471. )~~~");
  2472. }
  2473. }
  2474. void generate_namespace_header(IDL::Interface const& interface, StringBuilder& builder)
  2475. {
  2476. SourceGenerator generator { builder };
  2477. generator.set("namespace_class", interface.namespace_class);
  2478. generator.append(R"~~~(
  2479. #pragma once
  2480. #include <LibJS/Runtime/Object.h>
  2481. namespace Web::Bindings {
  2482. class @namespace_class@ final : public JS::Object {
  2483. JS_OBJECT(@namespace_class@, JS::Object);
  2484. public:
  2485. explicit @namespace_class@(JS::Realm&);
  2486. virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override;
  2487. virtual ~@namespace_class@() override;
  2488. private:
  2489. )~~~");
  2490. if (interface.extended_attributes.contains("WithGCVistor"sv)) {
  2491. generator.append(R"~~~(
  2492. virtual void visit_edges(JS::Cell::Visitor&) override;
  2493. )~~~");
  2494. }
  2495. for (auto const& overload_set : interface.overload_sets) {
  2496. auto function_generator = generator.fork();
  2497. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(overload_set.key.to_snakecase()));
  2498. function_generator.append(R"~~~(
  2499. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  2500. )~~~");
  2501. if (overload_set.value.size() > 1) {
  2502. for (auto i = 0u; i < overload_set.value.size(); ++i) {
  2503. function_generator.set("overload_suffix", DeprecatedString::number(i));
  2504. function_generator.append(R"~~~(
  2505. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@@overload_suffix@);
  2506. )~~~");
  2507. }
  2508. }
  2509. }
  2510. generator.append(R"~~~(
  2511. };
  2512. } // namespace Web::Bindings
  2513. )~~~");
  2514. }
  2515. void generate_namespace_implementation(IDL::Interface const& interface, StringBuilder& builder)
  2516. {
  2517. SourceGenerator generator { builder };
  2518. generator.set("name", interface.name);
  2519. generator.set("namespace_class", interface.namespace_class);
  2520. generator.append(R"~~~(
  2521. #include <AK/Function.h>
  2522. #include <LibIDL/Types.h>
  2523. #include <LibJS/Runtime/ArrayBuffer.h>
  2524. #include <LibJS/Runtime/DataView.h>
  2525. #include <LibJS/Runtime/Error.h>
  2526. #include <LibJS/Runtime/PrimitiveString.h>
  2527. #include <LibJS/Runtime/TypedArray.h>
  2528. #include <LibJS/Runtime/Value.h>
  2529. #include <LibWeb/Bindings/@namespace_class@.h>
  2530. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  2531. #include <LibWeb/Bindings/Intrinsics.h>
  2532. #include <LibWeb/HTML/Window.h>
  2533. #include <LibWeb/HTML/WindowProxy.h>
  2534. #include <LibWeb/WebIDL/OverloadResolution.h>
  2535. )~~~");
  2536. for (auto& path : interface.required_imported_paths)
  2537. generate_include_for(generator, path);
  2538. emit_includes_for_all_imports(interface, generator, interface.pair_iterator_types.has_value());
  2539. generator.append(R"~~~(
  2540. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  2541. using namespace Web::CSS;
  2542. using namespace Web::DOM;
  2543. using namespace Web::DOMParsing;
  2544. using namespace Web::Fetch;
  2545. using namespace Web::FileAPI;
  2546. using namespace Web::Geometry;
  2547. using namespace Web::HighResolutionTime;
  2548. using namespace Web::HTML;
  2549. using namespace Web::IntersectionObserver;
  2550. using namespace Web::RequestIdleCallback;
  2551. using namespace Web::ResizeObserver;
  2552. using namespace Web::Selection;
  2553. using namespace Web::Streams;
  2554. using namespace Web::UIEvents;
  2555. using namespace Web::URL;
  2556. using namespace Web::XHR;
  2557. using namespace Web::WebAssembly;
  2558. using namespace Web::WebGL;
  2559. using namespace Web::WebIDL;
  2560. namespace Web::Bindings {
  2561. @namespace_class@::@namespace_class@(JS::Realm& realm)
  2562. : Object(ConstructWithoutPrototypeTag::Tag, realm)
  2563. {
  2564. }
  2565. @namespace_class@::~@namespace_class@()
  2566. {
  2567. }
  2568. JS::ThrowCompletionOr<void> @namespace_class@::initialize(JS::Realm& realm)
  2569. {
  2570. [[maybe_unused]] auto& vm = this->vm();
  2571. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  2572. MUST_OR_THROW_OOM(Base::initialize(realm));
  2573. )~~~");
  2574. // https://webidl.spec.whatwg.org/#es-operations
  2575. for (auto const& overload_set : interface.overload_sets) {
  2576. auto function_generator = generator.fork();
  2577. function_generator.set("function.name", overload_set.key);
  2578. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(overload_set.key.to_snakecase()));
  2579. function_generator.set("function.length", DeprecatedString::number(get_shortest_function_length(overload_set.value)));
  2580. function_generator.append(R"~~~(
  2581. define_native_function(realm, "@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  2582. )~~~");
  2583. }
  2584. generator.append(R"~~~(
  2585. return {};
  2586. }
  2587. )~~~");
  2588. if (interface.extended_attributes.contains("WithGCVistor"sv)) {
  2589. generator.append(R"~~~(
  2590. void @namespace_class@::visit_edges(JS::Cell::Visitor& visitor)
  2591. {
  2592. Base::visit_edges(visitor);
  2593. @name@::visit_edges(visitor);
  2594. }
  2595. )~~~");
  2596. }
  2597. for (auto const& function : interface.functions)
  2598. generate_function(generator, function, StaticFunction::Yes, interface.namespace_class, interface.name, interface);
  2599. for (auto const& overload_set : interface.overload_sets) {
  2600. if (overload_set.value.size() == 1)
  2601. continue;
  2602. generate_overload_arbiter(generator, overload_set, interface.namespace_class);
  2603. }
  2604. generator.append(R"~~~(
  2605. } // namespace Web::Bindings
  2606. )~~~");
  2607. }
  2608. void generate_constructor_header(IDL::Interface const& interface, StringBuilder& builder)
  2609. {
  2610. SourceGenerator generator { builder };
  2611. generator.set("constructor_class", interface.constructor_class);
  2612. generator.append(R"~~~(
  2613. #pragma once
  2614. #include <LibJS/Runtime/NativeFunction.h>
  2615. namespace Web::Bindings {
  2616. class @constructor_class@ : public JS::NativeFunction {
  2617. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  2618. public:
  2619. explicit @constructor_class@(JS::Realm&);
  2620. virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override;
  2621. virtual ~@constructor_class@() override;
  2622. virtual JS::ThrowCompletionOr<JS::Value> call() override;
  2623. virtual JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> construct(JS::FunctionObject& new_target) override;
  2624. private:
  2625. virtual bool has_constructor() const override { return true; }
  2626. )~~~");
  2627. for (auto const& overload_set : interface.static_overload_sets) {
  2628. auto function_generator = generator.fork();
  2629. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(overload_set.key.to_snakecase()));
  2630. function_generator.append(R"~~~(
  2631. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  2632. )~~~");
  2633. if (overload_set.value.size() > 1) {
  2634. for (auto i = 0u; i < overload_set.value.size(); ++i) {
  2635. function_generator.set("overload_suffix", DeprecatedString::number(i));
  2636. function_generator.append(R"~~~(
  2637. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@@overload_suffix@);
  2638. )~~~");
  2639. }
  2640. }
  2641. }
  2642. generator.append(R"~~~(
  2643. };
  2644. } // namespace Web::Bindings
  2645. )~~~");
  2646. }
  2647. void generate_constructor_implementation(IDL::Interface const& interface, StringBuilder& builder)
  2648. {
  2649. SourceGenerator generator { builder };
  2650. generator.set("name", interface.name);
  2651. generator.set("namespaced_name", interface.namespaced_name);
  2652. generator.set("prototype_class", interface.prototype_class);
  2653. generator.set("constructor_class", interface.constructor_class);
  2654. generator.set("fully_qualified_name", interface.fully_qualified_name);
  2655. generator.append(R"~~~(
  2656. #include <LibJS/Heap/Heap.h>
  2657. #include <LibJS/Runtime/ArrayBuffer.h>
  2658. #include <LibJS/Runtime/DataView.h>
  2659. #include <LibJS/Runtime/GlobalObject.h>
  2660. #include <LibJS/Runtime/IteratorOperations.h>
  2661. #include <LibJS/Runtime/TypedArray.h>
  2662. #include <LibWeb/Bindings/@constructor_class@.h>
  2663. #include <LibWeb/Bindings/@prototype_class@.h>
  2664. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  2665. #include <LibWeb/Bindings/Intrinsics.h>
  2666. #if __has_include(<LibWeb/Crypto/@name@.h>)
  2667. # include <LibWeb/Crypto/@name@.h>
  2668. #elif __has_include(<LibWeb/CSS/@name@.h>)
  2669. # include <LibWeb/CSS/@name@.h>
  2670. #elif __has_include(<LibWeb/DOM/@name@.h>)
  2671. # include <LibWeb/DOM/@name@.h>
  2672. #elif __has_include(<LibWeb/Encoding/@name@.h>)
  2673. # include <LibWeb/Encoding/@name@.h>
  2674. #elif __has_include(<LibWeb/Fetch/@name@.h>)
  2675. # include <LibWeb/Fetch/@name@.h>
  2676. #elif __has_include(<LibWeb/FileAPI/@name@.h>)
  2677. # include <LibWeb/FileAPI/@name@.h>
  2678. #elif __has_include(<LibWeb/Geometry/@name@.h>)
  2679. # include <LibWeb/Geometry/@name@.h>
  2680. #elif __has_include(<LibWeb/HTML/@name@.h>)
  2681. # include <LibWeb/HTML/@name@.h>
  2682. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  2683. # include <LibWeb/UIEvents/@name@.h>
  2684. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  2685. # include <LibWeb/HighResolutionTime/@name@.h>
  2686. #elif __has_include(<LibWeb/IntersectionObserver/@name@.h>)
  2687. # include <LibWeb/IntersectionObserver/@name@.h>
  2688. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  2689. # include <LibWeb/NavigationTiming/@name@.h>
  2690. #elif __has_include(<LibWeb/RequestIdleCallback/@name@.h>)
  2691. # include <LibWeb/RequestIdleCallback/@name@.h>
  2692. #elif __has_include(<LibWeb/ResizeObserver/@name@.h>)
  2693. # include <LibWeb/ResizeObserver/@name@.h>
  2694. #elif __has_include(<LibWeb/SVG/@name@.h>)
  2695. # include <LibWeb/SVG/@name@.h>
  2696. #elif __has_include(<LibWeb/Selection/@name@.h>)
  2697. # include <LibWeb/Selection/@name@.h>
  2698. #elif __has_include(<LibWeb/WebSockets/@name@.h>)
  2699. # include <LibWeb/WebSockets/@name@.h>
  2700. #elif __has_include(<LibWeb/XHR/@name@.h>)
  2701. # include <LibWeb/XHR/@name@.h>
  2702. #elif __has_include(<LibWeb/URL/@name@.h>)
  2703. # include <LibWeb/URL/@name@.h>
  2704. #endif
  2705. )~~~");
  2706. for (auto& path : interface.required_imported_paths)
  2707. generate_include_for(generator, path);
  2708. emit_includes_for_all_imports(interface, generator, interface.pair_iterator_types.has_value());
  2709. generator.append(R"~~~(
  2710. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  2711. using namespace Web::CSS;
  2712. using namespace Web::DOM;
  2713. using namespace Web::DOMParsing;
  2714. using namespace Web::Fetch;
  2715. using namespace Web::FileAPI;
  2716. using namespace Web::Geometry;
  2717. using namespace Web::HighResolutionTime;
  2718. using namespace Web::HTML;
  2719. using namespace Web::IntersectionObserver;
  2720. using namespace Web::PerformanceTimeline;
  2721. using namespace Web::RequestIdleCallback;
  2722. using namespace Web::ResizeObserver;
  2723. using namespace Web::Selection;
  2724. using namespace Web::Streams;
  2725. using namespace Web::UIEvents;
  2726. using namespace Web::UserTiming;
  2727. using namespace Web::URL;
  2728. using namespace Web::XHR;
  2729. using namespace Web::WebAssembly;
  2730. using namespace Web::WebGL;
  2731. using namespace Web::WebIDL;
  2732. namespace Web::Bindings {
  2733. @constructor_class@::@constructor_class@(JS::Realm& realm)
  2734. : NativeFunction("@name@"sv, *realm.intrinsics().function_prototype())
  2735. {
  2736. }
  2737. @constructor_class@::~@constructor_class@()
  2738. {
  2739. }
  2740. JS::ThrowCompletionOr<JS::Value> @constructor_class@::call()
  2741. {
  2742. return vm().throw_completion<JS::TypeError>(JS::ErrorType::ConstructorWithoutNew, "@namespaced_name@");
  2743. }
  2744. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> @constructor_class@::construct(FunctionObject&)
  2745. {
  2746. )~~~");
  2747. if (interface.constructors.is_empty()) {
  2748. // No constructor
  2749. generator.set("constructor.length", "0");
  2750. generator.append(R"~~~(
  2751. return vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "@namespaced_name@");
  2752. )~~~");
  2753. } else if (interface.constructors.find_if([](auto const& x) { return x.extended_attributes.contains("HTMLConstructor"); }) != interface.constructors.end()) {
  2754. // https://html.spec.whatwg.org/multipage/dom.html#htmlconstructor
  2755. VERIFY(interface.constructors.size() == 1);
  2756. // FIXME: Properly implement HTMLConstructor extended attribute once custom elements are implemented
  2757. generator.set("constructor.length", "0");
  2758. generator.append(R"~~~(
  2759. return vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "@namespaced_name@");
  2760. )~~~");
  2761. } else if (interface.constructors.size() == 1) {
  2762. // Single constructor
  2763. auto& constructor = interface.constructors[0];
  2764. generator.set("constructor.length", DeprecatedString::number(constructor.shortest_length()));
  2765. generator.append(R"~~~(
  2766. auto& vm = this->vm();
  2767. auto& realm = *vm.current_realm();
  2768. )~~~");
  2769. if (!constructor.parameters.is_empty()) {
  2770. generate_argument_count_check(generator, constructor.name, constructor.shortest_length());
  2771. StringBuilder arguments_builder;
  2772. generate_arguments(generator, constructor.parameters, arguments_builder, interface);
  2773. generator.set(".constructor_arguments", arguments_builder.string_view());
  2774. generator.append(R"~~~(
  2775. auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return @fully_qualified_name@::construct_impl(realm, @.constructor_arguments@); }));
  2776. )~~~");
  2777. } else {
  2778. generator.append(R"~~~(
  2779. auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return @fully_qualified_name@::construct_impl(realm); }));
  2780. )~~~");
  2781. }
  2782. generator.append(R"~~~(
  2783. return *impl;
  2784. )~~~");
  2785. } else {
  2786. // Multiple constructor overloads - can't do that yet.
  2787. TODO();
  2788. }
  2789. generator.append(R"~~~(
  2790. }
  2791. JS::ThrowCompletionOr<void> @constructor_class@::initialize(JS::Realm& realm)
  2792. {
  2793. auto& vm = this->vm();
  2794. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  2795. MUST_OR_THROW_OOM(Base::initialize(realm));
  2796. define_direct_property(vm.names.prototype, &ensure_web_prototype<@prototype_class@>(realm, "@namespaced_name@"), 0);
  2797. define_direct_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  2798. )~~~");
  2799. for (auto& constant : interface.constants) {
  2800. auto constant_generator = generator.fork();
  2801. constant_generator.set("constant.name", constant.name);
  2802. generate_wrap_statement(constant_generator, constant.value, constant.type, interface, DeprecatedString::formatted("auto constant_{}_value =", constant.name));
  2803. constant_generator.append(R"~~~(
  2804. define_direct_property("@constant.name@", constant_@constant.name@_value, JS::Attribute::Enumerable);
  2805. )~~~");
  2806. }
  2807. // https://webidl.spec.whatwg.org/#es-operations
  2808. for (auto const& overload_set : interface.static_overload_sets) {
  2809. auto function_generator = generator.fork();
  2810. function_generator.set("function.name", overload_set.key);
  2811. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(overload_set.key.to_snakecase()));
  2812. function_generator.set("function.length", DeprecatedString::number(get_shortest_function_length(overload_set.value)));
  2813. function_generator.append(R"~~~(
  2814. define_native_function(realm, "@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  2815. )~~~");
  2816. }
  2817. generator.append(R"~~~(
  2818. return {};
  2819. }
  2820. )~~~");
  2821. // Implementation: Static Functions
  2822. for (auto& function : interface.static_functions)
  2823. generate_function(generator, function, StaticFunction::Yes, interface.constructor_class, interface.fully_qualified_name, interface);
  2824. for (auto const& overload_set : interface.static_overload_sets) {
  2825. if (overload_set.value.size() == 1)
  2826. continue;
  2827. generate_overload_arbiter(generator, overload_set, interface.constructor_class);
  2828. }
  2829. generator.append(R"~~~(
  2830. } // namespace Web::Bindings
  2831. )~~~");
  2832. }
  2833. void generate_prototype_header(IDL::Interface const& interface, StringBuilder& builder)
  2834. {
  2835. SourceGenerator generator { builder };
  2836. generator.set("prototype_class", interface.prototype_class);
  2837. generator.append(R"~~~(
  2838. #pragma once
  2839. #include <LibJS/Runtime/Object.h>
  2840. namespace Web::Bindings {
  2841. class @prototype_class@ : public JS::Object {
  2842. JS_OBJECT(@prototype_class@, JS::Object);
  2843. public:
  2844. explicit @prototype_class@(JS::Realm&);
  2845. virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override;
  2846. virtual ~@prototype_class@() override;
  2847. private:
  2848. )~~~");
  2849. // Generate an empty prototype object for global interfaces.
  2850. auto is_global_interface = interface.extended_attributes.contains("Global");
  2851. if (is_global_interface) {
  2852. generator.append(R"~~~(
  2853. };
  2854. )~~~");
  2855. } else {
  2856. generate_prototype_or_global_mixin_declarations(interface, builder);
  2857. }
  2858. generator.append(R"~~~(
  2859. } // namespace Web::Bindings
  2860. )~~~");
  2861. }
  2862. void generate_prototype_implementation(IDL::Interface const& interface, StringBuilder& builder)
  2863. {
  2864. SourceGenerator generator { builder };
  2865. generator.set("parent_name", interface.parent_name);
  2866. generator.set("prototype_class", interface.prototype_class);
  2867. generator.set("prototype_base_class", interface.prototype_base_class);
  2868. generator.append(R"~~~(
  2869. #include <AK/Function.h>
  2870. #include <LibIDL/Types.h>
  2871. #include <LibJS/Runtime/Array.h>
  2872. #include <LibJS/Runtime/ArrayBuffer.h>
  2873. #include <LibJS/Runtime/DataView.h>
  2874. #include <LibJS/Runtime/Error.h>
  2875. #include <LibJS/Runtime/FunctionObject.h>
  2876. #include <LibJS/Runtime/GlobalObject.h>
  2877. #include <LibJS/Runtime/IteratorOperations.h>
  2878. #include <LibJS/Runtime/TypedArray.h>
  2879. #include <LibJS/Runtime/Value.h>
  2880. #include <LibWeb/Bindings/@prototype_class@.h>
  2881. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  2882. #include <LibWeb/Bindings/Intrinsics.h>
  2883. #include <LibWeb/DOM/Element.h>
  2884. #include <LibWeb/DOM/Event.h>
  2885. #include <LibWeb/DOM/IDLEventListener.h>
  2886. #include <LibWeb/DOM/NodeFilter.h>
  2887. #include <LibWeb/DOM/Range.h>
  2888. #include <LibWeb/HTML/Origin.h>
  2889. #include <LibWeb/HTML/Scripting/Environments.h>
  2890. #include <LibWeb/HTML/Window.h>
  2891. #include <LibWeb/HTML/WindowProxy.h>
  2892. #include <LibWeb/WebIDL/OverloadResolution.h>
  2893. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  2894. # include <LibWeb/Bindings/@prototype_base_class@.h>
  2895. #endif
  2896. )~~~");
  2897. for (auto& path : interface.required_imported_paths)
  2898. generate_include_for(generator, path);
  2899. emit_includes_for_all_imports(interface, generator, interface.pair_iterator_types.has_value());
  2900. generator.append(R"~~~(
  2901. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  2902. using namespace Web::Crypto;
  2903. using namespace Web::CSS;
  2904. using namespace Web::DOM;
  2905. using namespace Web::DOMParsing;
  2906. using namespace Web::Fetch;
  2907. using namespace Web::FileAPI;
  2908. using namespace Web::Geometry;
  2909. using namespace Web::HighResolutionTime;
  2910. using namespace Web::HTML;
  2911. using namespace Web::IntersectionObserver;
  2912. using namespace Web::NavigationTiming;
  2913. using namespace Web::PerformanceTimeline;
  2914. using namespace Web::RequestIdleCallback;
  2915. using namespace Web::ResizeObserver;
  2916. using namespace Web::Selection;
  2917. using namespace Web::Streams;
  2918. using namespace Web::SVG;
  2919. using namespace Web::UIEvents;
  2920. using namespace Web::URL;
  2921. using namespace Web::UserTiming;
  2922. using namespace Web::WebSockets;
  2923. using namespace Web::XHR;
  2924. using namespace Web::WebAssembly;
  2925. using namespace Web::WebGL;
  2926. using namespace Web::WebIDL;
  2927. namespace Web::Bindings {
  2928. @prototype_class@::@prototype_class@([[maybe_unused]] JS::Realm& realm))~~~");
  2929. if (interface.name == "DOMException") {
  2930. // https://webidl.spec.whatwg.org/#es-DOMException-specialness
  2931. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  2932. generator.append(R"~~~(
  2933. : Object(ConstructWithPrototypeTag::Tag, *realm.intrinsics().error_prototype())
  2934. )~~~");
  2935. } else if (!interface.parent_name.is_empty()) {
  2936. generator.append(R"~~~(
  2937. : Object(ConstructWithPrototypeTag::Tag, ensure_web_prototype<@prototype_base_class@>(realm, "@parent_name@"))
  2938. )~~~");
  2939. } else {
  2940. generator.append(R"~~~(
  2941. : Object(ConstructWithPrototypeTag::Tag, *realm.intrinsics().object_prototype())
  2942. )~~~");
  2943. }
  2944. generator.append(R"~~~(
  2945. {
  2946. }
  2947. @prototype_class@::~@prototype_class@()
  2948. {
  2949. }
  2950. )~~~");
  2951. // Generate an empty prototype object for global interfaces.
  2952. auto is_global_interface = interface.extended_attributes.contains("Global");
  2953. if (is_global_interface) {
  2954. generator.append(R"~~~(
  2955. JS::ThrowCompletionOr<void> @prototype_class@::initialize(JS::Realm& realm)
  2956. {
  2957. MUST_OR_THROW_OOM(Base::initialize(realm));
  2958. return {};
  2959. }
  2960. )~~~");
  2961. } else {
  2962. generate_prototype_or_global_mixin_definitions(interface, builder);
  2963. }
  2964. generator.append(R"~~~(
  2965. } // namespace Web::Bindings
  2966. )~~~");
  2967. }
  2968. void generate_iterator_prototype_header(IDL::Interface const& interface, StringBuilder& builder)
  2969. {
  2970. VERIFY(interface.pair_iterator_types.has_value());
  2971. SourceGenerator generator { builder };
  2972. generator.set("prototype_class", DeprecatedString::formatted("{}IteratorPrototype", interface.name));
  2973. generator.append(R"~~~(
  2974. #pragma once
  2975. #include <LibJS/Runtime/Object.h>
  2976. namespace Web::Bindings {
  2977. class @prototype_class@ : public JS::Object {
  2978. JS_OBJECT(@prototype_class@, JS::Object);
  2979. public:
  2980. explicit @prototype_class@(JS::Realm&);
  2981. virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override;
  2982. virtual ~@prototype_class@() override;
  2983. private:
  2984. JS_DECLARE_NATIVE_FUNCTION(next);
  2985. };
  2986. } // namespace Web::Bindings
  2987. )~~~");
  2988. }
  2989. void generate_iterator_prototype_implementation(IDL::Interface const& interface, StringBuilder& builder)
  2990. {
  2991. VERIFY(interface.pair_iterator_types.has_value());
  2992. SourceGenerator generator { builder };
  2993. generator.set("name", DeprecatedString::formatted("{}Iterator", interface.name));
  2994. generator.set("prototype_class", DeprecatedString::formatted("{}IteratorPrototype", interface.name));
  2995. generator.set("fully_qualified_name", DeprecatedString::formatted("{}Iterator", interface.fully_qualified_name));
  2996. generator.set("possible_include_path", DeprecatedString::formatted("{}Iterator", interface.name.replace("::"sv, "/"sv, ReplaceMode::All)));
  2997. generator.append(R"~~~(
  2998. #include <AK/Function.h>
  2999. #include <AK/TypeCasts.h>
  3000. #include <LibJS/Runtime/Array.h>
  3001. #include <LibJS/Runtime/Error.h>
  3002. #include <LibJS/Runtime/FunctionObject.h>
  3003. #include <LibJS/Runtime/GlobalObject.h>
  3004. #include <LibJS/Runtime/TypedArray.h>
  3005. #include <LibWeb/Bindings/@prototype_class@.h>
  3006. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  3007. #if __has_include(<LibWeb/@possible_include_path@.h>)
  3008. # include <LibWeb/@possible_include_path@.h>
  3009. #endif
  3010. )~~~");
  3011. emit_includes_for_all_imports(interface, generator, true);
  3012. generator.append(R"~~~(
  3013. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  3014. using namespace Web::CSS;
  3015. using namespace Web::DOM;
  3016. using namespace Web::DOMParsing;
  3017. using namespace Web::Fetch;
  3018. using namespace Web::FileAPI;
  3019. using namespace Web::Geometry;
  3020. using namespace Web::HighResolutionTime;
  3021. using namespace Web::HTML;
  3022. using namespace Web::IntersectionObserver;
  3023. using namespace Web::NavigationTiming;
  3024. using namespace Web::PerformanceTimeline;
  3025. using namespace Web::RequestIdleCallback;
  3026. using namespace Web::ResizeObserver;
  3027. using namespace Web::Selection;
  3028. using namespace Web::XHR;
  3029. using namespace Web::UIEvents;
  3030. using namespace Web::URL;
  3031. using namespace Web::UserTiming;
  3032. using namespace Web::WebGL;
  3033. using namespace Web::WebIDL;
  3034. namespace Web::Bindings {
  3035. @prototype_class@::@prototype_class@(JS::Realm& realm)
  3036. : Object(ConstructWithPrototypeTag::Tag, *realm.intrinsics().iterator_prototype())
  3037. {
  3038. }
  3039. @prototype_class@::~@prototype_class@()
  3040. {
  3041. }
  3042. JS::ThrowCompletionOr<void> @prototype_class@::initialize(JS::Realm& realm)
  3043. {
  3044. auto& vm = this->vm();
  3045. MUST_OR_THROW_OOM(Base::initialize(realm));
  3046. define_native_function(realm, vm.names.next, next, 0, JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable);
  3047. define_direct_property(*vm.well_known_symbol_to_string_tag(), MUST_OR_THROW_OOM(JS::PrimitiveString::create(vm, "Iterator"sv)), JS::Attribute::Configurable);
  3048. return {};
  3049. }
  3050. static JS::ThrowCompletionOr<@fully_qualified_name@*> impl_from(JS::VM& vm)
  3051. {
  3052. auto* this_object = TRY(vm.this_value().to_object(vm));
  3053. if (!is<@fully_qualified_name@>(this_object))
  3054. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "@name@");
  3055. return static_cast<@fully_qualified_name@*>(this_object);
  3056. }
  3057. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::next)
  3058. {
  3059. auto* impl = TRY(impl_from(vm));
  3060. return TRY(throw_dom_exception_if_needed(vm, [&] { return impl->next(); }));
  3061. }
  3062. } // namespace Web::Bindings
  3063. )~~~");
  3064. }
  3065. void generate_global_mixin_header(IDL::Interface const& interface, StringBuilder& builder)
  3066. {
  3067. SourceGenerator generator { builder };
  3068. generator.set("class_name", interface.global_mixin_class);
  3069. generator.append(R"~~~(
  3070. #pragma once
  3071. #include <LibJS/Runtime/Object.h>
  3072. namespace Web::Bindings {
  3073. class @class_name@ {
  3074. public:
  3075. JS::ThrowCompletionOr<void> initialize(JS::Realm&, JS::Object&);
  3076. @class_name@();
  3077. virtual ~@class_name@();
  3078. private:
  3079. )~~~");
  3080. generate_prototype_or_global_mixin_declarations(interface, builder);
  3081. generator.append(R"~~~(
  3082. } // namespace Web::Bindings
  3083. )~~~");
  3084. }
  3085. void generate_global_mixin_implementation(IDL::Interface const& interface, StringBuilder& builder)
  3086. {
  3087. SourceGenerator generator { builder };
  3088. generator.set("class_name", interface.global_mixin_class);
  3089. generator.append(R"~~~(
  3090. #include <AK/Function.h>
  3091. #include <LibIDL/Types.h>
  3092. #include <LibJS/Runtime/Array.h>
  3093. #include <LibJS/Runtime/DataView.h>
  3094. #include <LibJS/Runtime/Error.h>
  3095. #include <LibJS/Runtime/FunctionObject.h>
  3096. #include <LibJS/Runtime/GlobalObject.h>
  3097. #include <LibJS/Runtime/IteratorOperations.h>
  3098. #include <LibJS/Runtime/TypedArray.h>
  3099. #include <LibJS/Runtime/Value.h>
  3100. #include <LibWeb/Bindings/@class_name@.h>
  3101. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  3102. #include <LibWeb/Bindings/Intrinsics.h>
  3103. #include <LibWeb/DOM/Element.h>
  3104. #include <LibWeb/DOM/Event.h>
  3105. #include <LibWeb/DOM/IDLEventListener.h>
  3106. #include <LibWeb/DOM/NodeFilter.h>
  3107. #include <LibWeb/DOM/Range.h>
  3108. #include <LibWeb/HTML/Origin.h>
  3109. #include <LibWeb/HTML/Scripting/Environments.h>
  3110. #include <LibWeb/HTML/Window.h>
  3111. #include <LibWeb/HTML/WindowProxy.h>
  3112. #include <LibWeb/WebIDL/OverloadResolution.h>
  3113. )~~~");
  3114. for (auto& path : interface.required_imported_paths)
  3115. generate_include_for(generator, path);
  3116. emit_includes_for_all_imports(interface, generator, interface.pair_iterator_types.has_value());
  3117. generator.append(R"~~~(
  3118. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  3119. using namespace Web::Crypto;
  3120. using namespace Web::CSS;
  3121. using namespace Web::DOM;
  3122. using namespace Web::DOMParsing;
  3123. using namespace Web::Fetch;
  3124. using namespace Web::FileAPI;
  3125. using namespace Web::Geometry;
  3126. using namespace Web::HighResolutionTime;
  3127. using namespace Web::HTML;
  3128. using namespace Web::IntersectionObserver;
  3129. using namespace Web::NavigationTiming;
  3130. using namespace Web::PerformanceTimeline;
  3131. using namespace Web::RequestIdleCallback;
  3132. using namespace Web::ResizeObserver;
  3133. using namespace Web::Selection;
  3134. using namespace Web::Streams;
  3135. using namespace Web::SVG;
  3136. using namespace Web::UIEvents;
  3137. using namespace Web::URL;
  3138. using namespace Web::UserTiming;
  3139. using namespace Web::WebSockets;
  3140. using namespace Web::XHR;
  3141. using namespace Web::WebGL;
  3142. using namespace Web::WebIDL;
  3143. namespace Web::Bindings {
  3144. @class_name@::@class_name@() = default;
  3145. @class_name@::~@class_name@() = default;
  3146. )~~~");
  3147. generate_prototype_or_global_mixin_definitions(interface, builder);
  3148. generator.append(R"~~~(
  3149. } // namespace Web::Bindings
  3150. )~~~");
  3151. }
  3152. }