IDLGenerators.cpp 122 KB

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