IDLGenerators.cpp 147 KB

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