IDLGenerators.cpp 148 KB

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