IDLGenerators.cpp 138 KB

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