IDLGenerators.cpp 138 KB

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