IDLGenerators.cpp 118 KB

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