IDLGenerators.cpp 116 KB

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