IDLGenerators.cpp 138 KB

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