IDLGenerators.cpp 118 KB

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