IDLGenerators.cpp 138 KB

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