IDLGenerators.cpp 117 KB

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