IDLGenerators.cpp 112 KB

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