IDLGenerators.cpp 125 KB

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