IDLGenerators.cpp 137 KB

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