IDLGenerators.cpp 129 KB

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