IDLGenerators.cpp 138 KB

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