IDLGenerators.cpp 117 KB

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