IDLGenerators.cpp 117 KB

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