IDLGenerators.cpp 117 KB

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