IDLGenerators.cpp 148 KB

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