IDLGenerators.cpp 139 KB

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