WrapperGenerator.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Debug.h>
  10. #include <AK/GenericLexer.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/LexicalPath.h>
  13. #include <AK/OwnPtr.h>
  14. #include <AK/SourceGenerator.h>
  15. #include <AK/StringBuilder.h>
  16. #include <LibCore/ArgsParser.h>
  17. #include <LibCore/File.h>
  18. #include <ctype.h>
  19. static String make_input_acceptable_cpp(String const& input)
  20. {
  21. if (input.is_one_of("class", "template", "for", "default", "char", "namespace", "delete")) {
  22. StringBuilder builder;
  23. builder.append(input);
  24. builder.append('_');
  25. return builder.to_string();
  26. }
  27. return input.replace("-", "_");
  28. }
  29. static void report_parsing_error(StringView message, StringView filename, StringView input, size_t offset)
  30. {
  31. // FIXME: Spaghetti code ahead.
  32. size_t lineno = 1;
  33. size_t colno = 1;
  34. size_t start_line = 0;
  35. size_t line_length = 0;
  36. for (size_t index = 0; index < input.length(); ++index) {
  37. if (offset == index)
  38. colno = index - start_line + 1;
  39. if (input[index] == '\n') {
  40. if (index >= offset)
  41. break;
  42. start_line = index + 1;
  43. line_length = 0;
  44. ++lineno;
  45. } else {
  46. ++line_length;
  47. }
  48. }
  49. StringBuilder error_message;
  50. error_message.appendff("{}\n", input.substring_view(start_line, line_length));
  51. for (size_t i = 0; i < colno - 1; ++i)
  52. error_message.append(' ');
  53. error_message.append("\033[1;31m^\n");
  54. error_message.appendff("{}:{}: error: {}\033[0m\n", filename, lineno, message);
  55. warnln("{}", error_message.string_view());
  56. exit(EXIT_FAILURE);
  57. }
  58. namespace IDL {
  59. template<typename FunctionType>
  60. static size_t get_function_length(FunctionType& function)
  61. {
  62. size_t length = 0;
  63. for (auto& parameter : function.parameters) {
  64. if (!parameter.optional)
  65. length++;
  66. }
  67. return length;
  68. }
  69. struct Type {
  70. String name;
  71. bool nullable { false };
  72. bool is_string() const { return name.is_one_of("ByteString", "CSSOMString", "DOMString", "USVString"); }
  73. };
  74. struct Parameter {
  75. Type type;
  76. String name;
  77. bool optional { false };
  78. Optional<String> optional_default_value;
  79. HashMap<String, String> extended_attributes;
  80. };
  81. struct Function {
  82. Type return_type;
  83. String name;
  84. Vector<Parameter> parameters;
  85. HashMap<String, String> extended_attributes;
  86. size_t length() const { return get_function_length(*this); }
  87. };
  88. struct Constructor {
  89. String name;
  90. Vector<Parameter> parameters;
  91. size_t length() const { return get_function_length(*this); }
  92. };
  93. struct Constant {
  94. Type type;
  95. String name;
  96. String value;
  97. };
  98. struct Attribute {
  99. bool readonly { false };
  100. Type type;
  101. String name;
  102. HashMap<String, String> extended_attributes;
  103. // Added for convenience after parsing
  104. String getter_callback_name;
  105. String setter_callback_name;
  106. };
  107. struct Interface {
  108. String name;
  109. String parent_name;
  110. HashMap<String, String> extended_attributes;
  111. Vector<Attribute> attributes;
  112. Vector<Constant> constants;
  113. Vector<Constructor> constructors;
  114. Vector<Function> functions;
  115. Vector<Function> static_functions;
  116. bool has_stringifier { false };
  117. Optional<String> stringifier_attribute;
  118. // Added for convenience after parsing
  119. String wrapper_class;
  120. String wrapper_base_class;
  121. String fully_qualified_name;
  122. String constructor_class;
  123. String prototype_class;
  124. String prototype_base_class;
  125. };
  126. static OwnPtr<Interface> parse_interface(StringView filename, StringView const& input)
  127. {
  128. auto interface = make<Interface>();
  129. GenericLexer lexer(input);
  130. auto assert_specific = [&](char ch) {
  131. if (!lexer.consume_specific(ch))
  132. report_parsing_error(String::formatted("expected '{}'", ch), filename, input, lexer.tell());
  133. };
  134. auto consume_whitespace = [&] {
  135. bool consumed = true;
  136. while (consumed) {
  137. consumed = lexer.consume_while([](char ch) { return isspace(ch); }).length() > 0;
  138. if (lexer.consume_specific("//")) {
  139. lexer.consume_until('\n');
  140. consumed = true;
  141. }
  142. }
  143. };
  144. auto assert_string = [&](StringView const& expected) {
  145. if (!lexer.consume_specific(expected))
  146. report_parsing_error(String::formatted("expected '{}'", expected), filename, input, lexer.tell());
  147. };
  148. auto parse_extended_attributes = [&] {
  149. HashMap<String, String> extended_attributes;
  150. for (;;) {
  151. consume_whitespace();
  152. if (lexer.consume_specific(']'))
  153. break;
  154. auto name = lexer.consume_until([](auto ch) { return ch == ']' || ch == '=' || ch == ','; });
  155. if (lexer.consume_specific('=')) {
  156. auto value = lexer.consume_until([](auto ch) { return ch == ']' || ch == ','; });
  157. extended_attributes.set(name, value);
  158. } else {
  159. extended_attributes.set(name, {});
  160. }
  161. lexer.consume_specific(',');
  162. }
  163. consume_whitespace();
  164. return extended_attributes;
  165. };
  166. if (lexer.consume_specific('['))
  167. interface->extended_attributes = parse_extended_attributes();
  168. assert_string("interface");
  169. consume_whitespace();
  170. interface->name = lexer.consume_until([](auto ch) { return isspace(ch); });
  171. consume_whitespace();
  172. if (lexer.consume_specific(':')) {
  173. consume_whitespace();
  174. interface->parent_name = lexer.consume_until([](auto ch) { return isspace(ch); });
  175. consume_whitespace();
  176. }
  177. assert_specific('{');
  178. auto parse_type = [&] {
  179. bool unsigned_ = lexer.consume_specific("unsigned");
  180. if (unsigned_)
  181. consume_whitespace();
  182. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '?'; });
  183. auto nullable = lexer.consume_specific('?');
  184. StringBuilder builder;
  185. if (unsigned_)
  186. builder.append("unsigned ");
  187. builder.append(name);
  188. return Type { builder.to_string(), nullable };
  189. };
  190. auto parse_attribute = [&](HashMap<String, String>& extended_attributes) {
  191. bool readonly = lexer.consume_specific("readonly");
  192. if (readonly)
  193. consume_whitespace();
  194. if (lexer.consume_specific("attribute"))
  195. consume_whitespace();
  196. auto type = parse_type();
  197. consume_whitespace();
  198. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ';'; });
  199. consume_whitespace();
  200. assert_specific(';');
  201. Attribute attribute;
  202. attribute.readonly = readonly;
  203. attribute.type = type;
  204. attribute.name = name;
  205. attribute.getter_callback_name = String::formatted("{}_getter", attribute.name.to_snakecase());
  206. attribute.setter_callback_name = String::formatted("{}_setter", attribute.name.to_snakecase());
  207. attribute.extended_attributes = move(extended_attributes);
  208. interface->attributes.append(move(attribute));
  209. };
  210. auto parse_constant = [&] {
  211. lexer.consume_specific("const");
  212. consume_whitespace();
  213. Constant constant;
  214. constant.type = parse_type();
  215. consume_whitespace();
  216. constant.name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '='; });
  217. consume_whitespace();
  218. lexer.consume_specific('=');
  219. consume_whitespace();
  220. constant.value = lexer.consume_while([](auto ch) { return !isspace(ch) && ch != ';'; });
  221. consume_whitespace();
  222. assert_specific(';');
  223. interface->constants.append(move(constant));
  224. };
  225. auto parse_parameters = [&] {
  226. consume_whitespace();
  227. Vector<Parameter> parameters;
  228. for (;;) {
  229. if (lexer.next_is(')'))
  230. break;
  231. HashMap<String, String> extended_attributes;
  232. if (lexer.consume_specific('['))
  233. extended_attributes = parse_extended_attributes();
  234. bool optional = lexer.consume_specific("optional");
  235. if (optional)
  236. consume_whitespace();
  237. auto type = parse_type();
  238. consume_whitespace();
  239. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ',' || ch == ')' || ch == '='; });
  240. Parameter parameter = { move(type), move(name), optional, {}, extended_attributes };
  241. consume_whitespace();
  242. if (lexer.next_is(')')) {
  243. parameters.append(parameter);
  244. break;
  245. }
  246. if (lexer.next_is('=') && optional) {
  247. assert_specific('=');
  248. consume_whitespace();
  249. auto default_value = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ',' || ch == ')'; });
  250. parameter.optional_default_value = default_value;
  251. }
  252. parameters.append(parameter);
  253. if (lexer.next_is(')'))
  254. break;
  255. assert_specific(',');
  256. consume_whitespace();
  257. }
  258. return parameters;
  259. };
  260. auto parse_function = [&](HashMap<String, String>& extended_attributes) {
  261. bool static_ = false;
  262. if (lexer.consume_specific("static")) {
  263. static_ = true;
  264. consume_whitespace();
  265. }
  266. auto return_type = parse_type();
  267. consume_whitespace();
  268. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '('; });
  269. consume_whitespace();
  270. assert_specific('(');
  271. auto parameters = parse_parameters();
  272. assert_specific(')');
  273. consume_whitespace();
  274. assert_specific(';');
  275. if (!static_)
  276. interface->functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  277. else
  278. interface->static_functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  279. };
  280. auto parse_constructor = [&] {
  281. assert_string("constructor");
  282. consume_whitespace();
  283. assert_specific('(');
  284. auto parameters = parse_parameters();
  285. assert_specific(')');
  286. consume_whitespace();
  287. assert_specific(';');
  288. interface->constructors.append(Constructor { interface->name, move(parameters) });
  289. };
  290. auto parse_stringifier = [&](HashMap<String, String>& extended_attributes) {
  291. assert_string("stringifier");
  292. interface->has_stringifier = true;
  293. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  294. parse_attribute(extended_attributes);
  295. interface->stringifier_attribute = interface->attributes.last().name;
  296. }
  297. assert_specific(';');
  298. };
  299. for (;;) {
  300. HashMap<String, String> extended_attributes;
  301. consume_whitespace();
  302. if (lexer.consume_specific('}')) {
  303. consume_whitespace();
  304. assert_specific(';');
  305. break;
  306. }
  307. if (lexer.consume_specific('[')) {
  308. extended_attributes = parse_extended_attributes();
  309. }
  310. if (lexer.next_is("constructor")) {
  311. parse_constructor();
  312. continue;
  313. }
  314. if (lexer.next_is("const")) {
  315. parse_constant();
  316. continue;
  317. }
  318. if (lexer.next_is("stringifier")) {
  319. parse_stringifier(extended_attributes);
  320. continue;
  321. }
  322. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  323. parse_attribute(extended_attributes);
  324. continue;
  325. }
  326. parse_function(extended_attributes);
  327. }
  328. interface->wrapper_class = String::formatted("{}Wrapper", interface->name);
  329. interface->wrapper_base_class = String::formatted("{}Wrapper", interface->parent_name.is_empty() ? String::empty() : interface->parent_name);
  330. interface->constructor_class = String::formatted("{}Constructor", interface->name);
  331. interface->prototype_class = String::formatted("{}Prototype", interface->name);
  332. interface->prototype_base_class = String::formatted("{}Prototype", interface->parent_name.is_empty() ? "Object" : interface->parent_name);
  333. return interface;
  334. }
  335. }
  336. static void generate_constructor_header(IDL::Interface const&);
  337. static void generate_constructor_implementation(IDL::Interface const&);
  338. static void generate_prototype_header(IDL::Interface const&);
  339. static void generate_prototype_implementation(IDL::Interface const&);
  340. static void generate_header(IDL::Interface const&);
  341. static void generate_implementation(IDL::Interface const&);
  342. int main(int argc, char** argv)
  343. {
  344. Core::ArgsParser args_parser;
  345. char const* path = nullptr;
  346. bool header_mode = false;
  347. bool implementation_mode = false;
  348. bool constructor_header_mode = false;
  349. bool constructor_implementation_mode = false;
  350. bool prototype_header_mode = false;
  351. bool prototype_implementation_mode = false;
  352. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  353. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  354. args_parser.add_option(constructor_header_mode, "Generate the constructor .h file", "constructor-header", 'C');
  355. args_parser.add_option(constructor_implementation_mode, "Generate the constructor .cpp file", "constructor-implementation", 'O');
  356. args_parser.add_option(prototype_header_mode, "Generate the prototype .h file", "prototype-header", 'P');
  357. args_parser.add_option(prototype_implementation_mode, "Generate the prototype .cpp file", "prototype-implementation", 'R');
  358. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  359. args_parser.parse(argc, argv);
  360. auto file_or_error = Core::File::open(path, Core::OpenMode::ReadOnly);
  361. if (file_or_error.is_error()) {
  362. warnln("Failed to open {}: {}", path, file_or_error.error());
  363. return 1;
  364. }
  365. LexicalPath lexical_path(path);
  366. auto& namespace_ = lexical_path.parts_view().at(lexical_path.parts_view().size() - 2);
  367. auto data = file_or_error.value()->read_all();
  368. auto interface = IDL::parse_interface(path, data);
  369. if (!interface) {
  370. warnln("Cannot parse {}", path);
  371. return 1;
  372. }
  373. if (namespace_.is_one_of("CSS", "DOM", "HTML", "UIEvents", "HighResolutionTime", "NavigationTiming", "SVG", "XHR")) {
  374. StringBuilder builder;
  375. builder.append(namespace_);
  376. builder.append("::");
  377. builder.append(interface->name);
  378. interface->fully_qualified_name = builder.to_string();
  379. } else {
  380. interface->fully_qualified_name = interface->name;
  381. }
  382. if constexpr (WRAPPER_GENERATOR_DEBUG) {
  383. dbgln("Attributes:");
  384. for (auto& attribute : interface->attributes) {
  385. dbgln(" {}{}{} {}",
  386. attribute.readonly ? "readonly " : "",
  387. attribute.type.name,
  388. attribute.type.nullable ? "?" : "",
  389. attribute.name);
  390. }
  391. dbgln("Functions:");
  392. for (auto& function : interface->functions) {
  393. dbgln(" {}{} {}",
  394. function.return_type.name,
  395. function.return_type.nullable ? "?" : "",
  396. function.name);
  397. for (auto& parameter : function.parameters) {
  398. dbgln(" {}{} {}",
  399. parameter.type.name,
  400. parameter.type.nullable ? "?" : "",
  401. parameter.name);
  402. }
  403. }
  404. dbgln("Static Functions:");
  405. for (auto& function : interface->static_functions) {
  406. dbgln(" static {}{} {}",
  407. function.return_type.name,
  408. function.return_type.nullable ? "?" : "",
  409. function.name);
  410. for (auto& parameter : function.parameters) {
  411. dbgln(" {}{} {}",
  412. parameter.type.name,
  413. parameter.type.nullable ? "?" : "",
  414. parameter.name);
  415. }
  416. }
  417. }
  418. if (header_mode)
  419. generate_header(*interface);
  420. if (implementation_mode)
  421. generate_implementation(*interface);
  422. if (constructor_header_mode)
  423. generate_constructor_header(*interface);
  424. if (constructor_implementation_mode)
  425. generate_constructor_implementation(*interface);
  426. if (prototype_header_mode)
  427. generate_prototype_header(*interface);
  428. if (prototype_implementation_mode)
  429. generate_prototype_implementation(*interface);
  430. return 0;
  431. }
  432. static bool should_emit_wrapper_factory(IDL::Interface const& interface)
  433. {
  434. // FIXME: This is very hackish.
  435. if (interface.name == "Event")
  436. return false;
  437. if (interface.name == "EventTarget")
  438. return false;
  439. if (interface.name == "Node")
  440. return false;
  441. if (interface.name == "Text")
  442. return false;
  443. if (interface.name == "Document")
  444. return false;
  445. if (interface.name == "DocumentType")
  446. return false;
  447. if (interface.name.ends_with("Element"))
  448. return false;
  449. return true;
  450. }
  451. static bool is_wrappable_type(IDL::Type const& type)
  452. {
  453. if (type.name == "Node")
  454. return true;
  455. if (type.name == "Document")
  456. return true;
  457. if (type.name == "Text")
  458. return true;
  459. if (type.name == "DocumentType")
  460. return true;
  461. if (type.name.ends_with("Element"))
  462. return true;
  463. if (type.name.ends_with("Event"))
  464. return true;
  465. if (type.name == "ImageData")
  466. return true;
  467. return false;
  468. }
  469. template<typename ParameterType>
  470. static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter, String const& js_name, String const& js_suffix, String const& cpp_name, bool return_void = false, bool legacy_null_to_empty_string = false, bool optional = false, Optional<String> optional_default_value = {})
  471. {
  472. auto scoped_generator = generator.fork();
  473. scoped_generator.set("cpp_name", make_input_acceptable_cpp(cpp_name));
  474. scoped_generator.set("js_name", js_name);
  475. scoped_generator.set("js_suffix", js_suffix);
  476. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  477. scoped_generator.set("parameter.type.name", parameter.type.name);
  478. if (optional_default_value.has_value())
  479. scoped_generator.set("parameter.optional_default_value", *optional_default_value);
  480. if (return_void)
  481. scoped_generator.set("return_statement", "return;");
  482. else
  483. scoped_generator.set("return_statement", "return {};");
  484. // FIXME: Add support for optional, nullable and default values to all types
  485. if (parameter.type.is_string()) {
  486. if (!optional) {
  487. if (!parameter.type.nullable) {
  488. scoped_generator.append(R"~~~(
  489. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  490. if (vm.exception())
  491. @return_statement@
  492. )~~~");
  493. } else {
  494. scoped_generator.append(R"~~~(
  495. String @cpp_name@;
  496. if (!@js_name@@js_suffix@.is_nullish()) {
  497. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  498. if (vm.exception())
  499. @return_statement@
  500. }
  501. )~~~");
  502. }
  503. } else {
  504. scoped_generator.append(R"~~~(
  505. String @cpp_name@;
  506. if (!@js_name@@js_suffix@.is_undefined()) {
  507. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  508. if (vm.exception())
  509. @return_statement@
  510. })~~~");
  511. if (optional_default_value.has_value() && (!parameter.type.nullable || optional_default_value.value() != "null")) {
  512. scoped_generator.append(R"~~~( else {
  513. @cpp_name@ = @parameter.optional_default_value@;
  514. }
  515. )~~~");
  516. } else {
  517. scoped_generator.append(R"~~~(
  518. )~~~");
  519. }
  520. }
  521. } else if (parameter.type.name == "EventListener") {
  522. if (parameter.type.nullable) {
  523. scoped_generator.append(R"~~~(
  524. RefPtr<EventListener> @cpp_name@;
  525. if (!@js_name@@js_suffix@.is_nullish()) {
  526. if (!@js_name@@js_suffix@.is_function()) {
  527. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "Function");
  528. @return_statement@
  529. }
  530. @cpp_name@ = adopt_ref(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  531. }
  532. )~~~");
  533. } else {
  534. scoped_generator.append(R"~~~(
  535. if (!@js_name@@js_suffix@.is_function()) {
  536. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "Function");
  537. @return_statement@
  538. }
  539. auto @cpp_name@ = adopt_ref(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  540. )~~~");
  541. }
  542. } else if (is_wrappable_type(parameter.type)) {
  543. if (!parameter.type.nullable) {
  544. scoped_generator.append(R"~~~(
  545. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  546. if (vm.exception())
  547. @return_statement@
  548. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  549. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  550. @return_statement@
  551. }
  552. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  553. )~~~");
  554. } else {
  555. scoped_generator.append(R"~~~(
  556. @parameter.type.name@* @cpp_name@ = nullptr;
  557. if (!@js_name@@js_suffix@.is_nullish()) {
  558. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  559. if (vm.exception())
  560. @return_statement@
  561. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  562. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  563. @return_statement@
  564. }
  565. @cpp_name@ = &static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  566. }
  567. )~~~");
  568. }
  569. } else if (parameter.type.name == "double") {
  570. if (!optional) {
  571. scoped_generator.append(R"~~~(
  572. double @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  573. if (vm.exception())
  574. @return_statement@
  575. )~~~");
  576. } else {
  577. if (optional_default_value.has_value()) {
  578. scoped_generator.append(R"~~~(
  579. double @cpp_name@;
  580. )~~~");
  581. } else {
  582. scoped_generator.append(R"~~~(
  583. Optional<double> @cpp_name@;
  584. )~~~");
  585. }
  586. scoped_generator.append(R"~~~(
  587. if (!@js_name@@js_suffix@.is_undefined()) {
  588. @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  589. if (vm.exception())
  590. @return_statement@
  591. }
  592. )~~~");
  593. if (optional_default_value.has_value()) {
  594. scoped_generator.append(R"~~~(
  595. else
  596. @cpp_name@ = @parameter.optional_default_value@;
  597. )~~~");
  598. } else {
  599. scoped_generator.append(R"~~~(
  600. )~~~");
  601. }
  602. }
  603. } else if (parameter.type.name == "boolean") {
  604. if (!optional) {
  605. scoped_generator.append(R"~~~(
  606. bool @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  607. )~~~");
  608. } else {
  609. if (optional_default_value.has_value()) {
  610. scoped_generator.append(R"~~~(
  611. bool @cpp_name@;
  612. )~~~");
  613. } else {
  614. scoped_generator.append(R"~~~(
  615. Optional<bool> @cpp_name@;
  616. )~~~");
  617. }
  618. scoped_generator.append(R"~~~(
  619. if (!@js_name@@js_suffix@.is_undefined())
  620. @cpp_name@ = @js_name@@js_suffix@.to_boolean();)~~~");
  621. if (optional_default_value.has_value()) {
  622. scoped_generator.append(R"~~~(
  623. else
  624. @cpp_name@ = @parameter.optional_default_value@;
  625. )~~~");
  626. } else {
  627. scoped_generator.append(R"~~~(
  628. )~~~");
  629. }
  630. }
  631. } else if (parameter.type.name == "unsigned long") {
  632. scoped_generator.append(R"~~~(
  633. auto @cpp_name@ = @js_name@@js_suffix@.to_u32(global_object);
  634. if (vm.exception())
  635. @return_statement@
  636. )~~~");
  637. } else if (parameter.type.name == "unsigned short") {
  638. scoped_generator.append(R"~~~(
  639. auto @cpp_name@ = (u16)@js_name@@js_suffix@.to_u32(global_object);
  640. if (vm.exception())
  641. @return_statement@
  642. )~~~");
  643. } else if (parameter.type.name == "long") {
  644. scoped_generator.append(R"~~~(
  645. auto @cpp_name@ = @js_name@@js_suffix@.to_i32(global_object);
  646. if (vm.exception())
  647. @return_statement@
  648. )~~~");
  649. } else if (parameter.type.name == "EventHandler") {
  650. // x.onfoo = function() { ... }
  651. scoped_generator.append(R"~~~(
  652. HTML::EventHandler @cpp_name@;
  653. if (@js_name@@js_suffix@.is_function()) {
  654. @cpp_name@.callback = JS::make_handle(&@js_name@@js_suffix@.as_function());
  655. } else if (@js_name@@js_suffix@.is_string()) {
  656. @cpp_name@.string = @js_name@@js_suffix@.as_string().string();
  657. } else {
  658. @return_statement@
  659. }
  660. )~~~");
  661. } else if (parameter.type.name == "any") {
  662. scoped_generator.append(R"~~~(
  663. auto @cpp_name@ = @js_name@@js_suffix@;
  664. )~~~");
  665. } else {
  666. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  667. VERIFY_NOT_REACHED();
  668. }
  669. }
  670. template<typename FunctionType>
  671. static void generate_argument_count_check(SourceGenerator& generator, FunctionType& function)
  672. {
  673. auto argument_count_check_generator = generator.fork();
  674. argument_count_check_generator.set("function.name", function.name);
  675. argument_count_check_generator.set("function.nargs", String::number(function.length()));
  676. if (function.length() == 0)
  677. return;
  678. if (function.length() == 1) {
  679. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  680. argument_count_check_generator.set(".arg_count_suffix", "");
  681. } else {
  682. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  683. argument_count_check_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  684. }
  685. argument_count_check_generator.append(R"~~~(
  686. if (vm.argument_count() < @function.nargs@) {
  687. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  688. return {};
  689. }
  690. )~~~");
  691. }
  692. static void generate_arguments(SourceGenerator& generator, Vector<IDL::Parameter> const& parameters, StringBuilder& arguments_builder, bool return_void = false)
  693. {
  694. auto arguments_generator = generator.fork();
  695. Vector<String> parameter_names;
  696. size_t argument_index = 0;
  697. for (auto& parameter : parameters) {
  698. parameter_names.append(make_input_acceptable_cpp(parameter.name.to_snakecase()));
  699. arguments_generator.set("argument.index", String::number(argument_index));
  700. arguments_generator.append(R"~~~(
  701. auto arg@argument.index@ = vm.argument(@argument.index@);
  702. )~~~");
  703. bool legacy_null_to_empty_string = parameter.extended_attributes.contains("LegacyNullToEmptyString");
  704. generate_to_cpp(generator, parameter, "arg", String::number(argument_index), parameter.name.to_snakecase(), return_void, legacy_null_to_empty_string, parameter.optional, parameter.optional_default_value);
  705. ++argument_index;
  706. }
  707. arguments_builder.join(", ", parameter_names);
  708. }
  709. static void generate_return_statement(SourceGenerator& generator, IDL::Type const& return_type)
  710. {
  711. auto scoped_generator = generator.fork();
  712. scoped_generator.set("return_type", return_type.name);
  713. if (return_type.name == "undefined") {
  714. scoped_generator.append(R"~~~(
  715. return JS::js_undefined();
  716. )~~~");
  717. return;
  718. }
  719. if (return_type.nullable) {
  720. if (return_type.is_string()) {
  721. scoped_generator.append(R"~~~(
  722. if (retval.is_null())
  723. return JS::js_null();
  724. )~~~");
  725. } else {
  726. scoped_generator.append(R"~~~(
  727. if (!retval)
  728. return JS::js_null();
  729. )~~~");
  730. }
  731. }
  732. if (return_type.is_string()) {
  733. scoped_generator.append(R"~~~(
  734. return JS::js_string(vm, retval);
  735. )~~~");
  736. } else if (return_type.name == "ArrayFromVector") {
  737. // FIXME: Remove this fake type hack once it's no longer needed.
  738. // Basically once we have NodeList we can throw this out.
  739. scoped_generator.append(R"~~~(
  740. auto* new_array = JS::Array::create(global_object, 0);
  741. for (auto& element : retval)
  742. new_array->indexed_properties().append(wrap(global_object, element));
  743. return new_array;
  744. )~~~");
  745. } else if (return_type.name == "boolean" || return_type.name == "double") {
  746. scoped_generator.append(R"~~~(
  747. return JS::Value(retval);
  748. )~~~");
  749. } else if (return_type.name == "short" || return_type.name == "unsigned short" || return_type.name == "long" || return_type.name == "unsigned long") {
  750. scoped_generator.append(R"~~~(
  751. return JS::Value((i32)retval);
  752. )~~~");
  753. } else if (return_type.name == "Uint8ClampedArray") {
  754. scoped_generator.append(R"~~~(
  755. return retval;
  756. )~~~");
  757. } else if (return_type.name == "EventHandler") {
  758. scoped_generator.append(R"~~~(
  759. if (retval.callback.is_null())
  760. return JS::js_null();
  761. return retval.callback.cell();
  762. )~~~");
  763. } else if (return_type.name == "Location") {
  764. // Location is special cased as it is already a JS::Object.
  765. scoped_generator.append(R"~~~(
  766. return JS::Value(retval);
  767. )~~~");
  768. } else {
  769. scoped_generator.append(R"~~~(
  770. return wrap(global_object, const_cast<@return_type@&>(*retval));
  771. )~~~");
  772. }
  773. }
  774. enum class StaticFunction {
  775. No,
  776. Yes,
  777. };
  778. static void generate_function(SourceGenerator& generator, IDL::Function const& function, StaticFunction is_static_function, String const& class_name, String const& interface_fully_qualified_name)
  779. {
  780. auto function_generator = generator.fork();
  781. function_generator.set("class_name", class_name);
  782. function_generator.set("interface_fully_qualified_name", interface_fully_qualified_name);
  783. function_generator.set("function.name", function.name);
  784. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  785. if (function.extended_attributes.contains("ImplementedAs")) {
  786. auto implemented_as = function.extended_attributes.get("ImplementedAs").value();
  787. function_generator.set("function.cpp_name", implemented_as);
  788. } else {
  789. function_generator.set("function.cpp_name", make_input_acceptable_cpp(function.name.to_snakecase()));
  790. }
  791. function_generator.append(R"~~~(
  792. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@function.name:snakecase@)
  793. {
  794. )~~~");
  795. if (is_static_function == StaticFunction::No) {
  796. function_generator.append(R"~~~(
  797. auto* impl = impl_from(vm, global_object);
  798. if (!impl)
  799. return {};
  800. )~~~");
  801. }
  802. generate_argument_count_check(generator, function);
  803. StringBuilder arguments_builder;
  804. generate_arguments(generator, function.parameters, arguments_builder);
  805. function_generator.set(".arguments", arguments_builder.string_view());
  806. if (is_static_function == StaticFunction::No) {
  807. function_generator.append(R"~~~(
  808. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->@function.cpp_name@(@.arguments@); });
  809. )~~~");
  810. } else {
  811. function_generator.append(R"~~~(
  812. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return @interface_fully_qualified_name@::@function.cpp_name@(@.arguments@); });
  813. )~~~");
  814. }
  815. function_generator.append(R"~~~(
  816. if (should_return_empty(result))
  817. return JS::Value();
  818. [[maybe_unused]] auto retval = result.release_value();
  819. )~~~");
  820. generate_return_statement(generator, function.return_type);
  821. function_generator.append(R"~~~(
  822. }
  823. )~~~");
  824. }
  825. static void generate_header(IDL::Interface const& interface)
  826. {
  827. StringBuilder builder;
  828. SourceGenerator generator { builder };
  829. generator.set("name", interface.name);
  830. generator.set("fully_qualified_name", interface.fully_qualified_name);
  831. generator.set("wrapper_base_class", interface.wrapper_base_class);
  832. generator.set("wrapper_class", interface.wrapper_class);
  833. generator.set("wrapper_class:snakecase", interface.wrapper_class.to_snakecase());
  834. generator.append(R"~~~(
  835. #pragma once
  836. #include <LibWeb/Bindings/Wrapper.h>
  837. // FIXME: This is very strange.
  838. #if __has_include(<LibWeb/CSS/@name@.h>)
  839. # include <LibWeb/CSS/@name@.h>
  840. #elif __has_include(<LibWeb/DOM/@name@.h>)
  841. # include <LibWeb/DOM/@name@.h>
  842. #elif __has_include(<LibWeb/HTML/@name@.h>)
  843. # include <LibWeb/HTML/@name@.h>
  844. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  845. # include <LibWeb/UIEvents/@name@.h>
  846. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  847. # include <LibWeb/HighResolutionTime/@name@.h>
  848. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  849. # include <LibWeb/NavigationTiming/@name@.h>
  850. #elif __has_include(<LibWeb/SVG/@name@.h>)
  851. # include <LibWeb/SVG/@name@.h>
  852. #elif __has_include(<LibWeb/XHR/@name@.h>)
  853. # include <LibWeb/XHR/@name@.h>
  854. #endif
  855. )~~~");
  856. if (interface.wrapper_base_class != "Wrapper") {
  857. generator.append(R"~~~(
  858. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  859. )~~~");
  860. }
  861. generator.append(R"~~~(
  862. namespace Web::Bindings {
  863. class @wrapper_class@ : public @wrapper_base_class@ {
  864. JS_OBJECT(@name@, @wrapper_base_class@);
  865. public:
  866. static @wrapper_class@* create(JS::GlobalObject&, @fully_qualified_name@&);
  867. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  868. virtual void initialize(JS::GlobalObject&) override;
  869. virtual ~@wrapper_class@() override;
  870. )~~~");
  871. if (interface.extended_attributes.contains("CustomGet")) {
  872. generator.append(R"~~~(
  873. virtual JS::Value internal_get(JS::PropertyName const&, JS::Value receiver) const override;
  874. )~~~");
  875. }
  876. if (interface.extended_attributes.contains("CustomSet")) {
  877. generator.append(R"~~~(
  878. virtual bool internal_set(JS::PropertyName const&, JS::Value, JS::Value receiver) override;
  879. )~~~");
  880. }
  881. if (interface.extended_attributes.contains("CustomHasProperty")) {
  882. generator.append(R"~~~(
  883. virtual bool internal_has_property(JS::PropertyName const&) const override;
  884. )~~~");
  885. }
  886. if (interface.wrapper_base_class == "Wrapper") {
  887. generator.append(R"~~~(
  888. @fully_qualified_name@& impl() { return *m_impl; }
  889. @fully_qualified_name@ const& impl() const { return *m_impl; }
  890. )~~~");
  891. } else {
  892. generator.append(R"~~~(
  893. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  894. @fully_qualified_name@ const& impl() const { return static_cast<@fully_qualified_name@ const&>(@wrapper_base_class@::impl()); }
  895. )~~~");
  896. }
  897. generator.append(R"~~~(
  898. private:
  899. )~~~");
  900. if (interface.wrapper_base_class == "Wrapper") {
  901. generator.append(R"~~~(
  902. NonnullRefPtr<@fully_qualified_name@> m_impl;
  903. )~~~");
  904. }
  905. generator.append(R"~~~(
  906. };
  907. )~~~");
  908. if (should_emit_wrapper_factory(interface)) {
  909. generator.append(R"~~~(
  910. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  911. )~~~");
  912. }
  913. generator.append(R"~~~(
  914. } // namespace Web::Bindings
  915. )~~~");
  916. outln("{}", generator.as_string_view());
  917. }
  918. void generate_implementation(IDL::Interface const& interface)
  919. {
  920. StringBuilder builder;
  921. SourceGenerator generator { builder };
  922. generator.set("name", interface.name);
  923. generator.set("wrapper_class", interface.wrapper_class);
  924. generator.set("wrapper_base_class", interface.wrapper_base_class);
  925. generator.set("prototype_class", interface.prototype_class);
  926. generator.set("fully_qualified_name", interface.fully_qualified_name);
  927. generator.append(R"~~~(
  928. #include <AK/FlyString.h>
  929. #include <LibJS/Runtime/Array.h>
  930. #include <LibJS/Runtime/Error.h>
  931. #include <LibJS/Runtime/FunctionObject.h>
  932. #include <LibJS/Runtime/GlobalObject.h>
  933. #include <LibJS/Runtime/TypedArray.h>
  934. #include <LibJS/Runtime/Value.h>
  935. #include <LibWeb/Bindings/@prototype_class@.h>
  936. #include <LibWeb/Bindings/@wrapper_class@.h>
  937. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  938. #include <LibWeb/Bindings/CommentWrapper.h>
  939. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  940. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  941. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  942. #include <LibWeb/Bindings/DocumentWrapper.h>
  943. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  944. #include <LibWeb/Bindings/EventWrapperFactory.h>
  945. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  946. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  947. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  948. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  949. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  950. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  951. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  952. #include <LibWeb/Bindings/ImageDataWrapper.h>
  953. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  954. #include <LibWeb/Bindings/TextWrapper.h>
  955. #include <LibWeb/Bindings/WindowObject.h>
  956. #include <LibWeb/DOM/Element.h>
  957. #include <LibWeb/DOM/EventListener.h>
  958. #include <LibWeb/HTML/HTMLElement.h>
  959. #include <LibWeb/Origin.h>
  960. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  961. using namespace Web::CSS;
  962. using namespace Web::DOM;
  963. using namespace Web::HTML;
  964. namespace Web::Bindings {
  965. @wrapper_class@* @wrapper_class@::create(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  966. {
  967. return global_object.heap().allocate<@wrapper_class@>(global_object, global_object, impl);
  968. }
  969. )~~~");
  970. if (interface.wrapper_base_class == "Wrapper") {
  971. generator.append(R"~~~(
  972. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  973. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  974. , m_impl(impl)
  975. {
  976. }
  977. )~~~");
  978. } else {
  979. generator.append(R"~~~(
  980. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  981. : @wrapper_base_class@(global_object, impl)
  982. {
  983. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  984. VERIFY(success);
  985. }
  986. )~~~");
  987. }
  988. generator.append(R"~~~(
  989. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  990. {
  991. @wrapper_base_class@::initialize(global_object);
  992. }
  993. @wrapper_class@::~@wrapper_class@()
  994. {
  995. }
  996. )~~~");
  997. if (should_emit_wrapper_factory(interface)) {
  998. generator.append(R"~~~(
  999. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  1000. {
  1001. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  1002. }
  1003. )~~~");
  1004. }
  1005. generator.append(R"~~~(
  1006. } // namespace Web::Bindings
  1007. )~~~");
  1008. outln("{}", generator.as_string_view());
  1009. }
  1010. static void generate_constructor_header(IDL::Interface const& interface)
  1011. {
  1012. StringBuilder builder;
  1013. SourceGenerator generator { builder };
  1014. generator.set("name", interface.name);
  1015. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1016. generator.set("constructor_class", interface.constructor_class);
  1017. generator.set("constructor_class:snakecase", interface.constructor_class.to_snakecase());
  1018. generator.append(R"~~~(
  1019. #pragma once
  1020. #include <LibJS/Runtime/NativeFunction.h>
  1021. namespace Web::Bindings {
  1022. class @constructor_class@ : public JS::NativeFunction {
  1023. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  1024. public:
  1025. explicit @constructor_class@(JS::GlobalObject&);
  1026. virtual void initialize(JS::GlobalObject&) override;
  1027. virtual ~@constructor_class@() override;
  1028. virtual JS::Value call() override;
  1029. virtual JS::Value construct(JS::FunctionObject& new_target) override;
  1030. private:
  1031. virtual bool has_constructor() const override { return true; }
  1032. )~~~");
  1033. for (auto& function : interface.static_functions) {
  1034. auto function_generator = generator.fork();
  1035. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1036. function_generator.append(R"~~~(
  1037. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1038. )~~~");
  1039. }
  1040. generator.append(R"~~~(
  1041. };
  1042. } // namespace Web::Bindings
  1043. )~~~");
  1044. outln("{}", generator.as_string_view());
  1045. }
  1046. void generate_constructor_implementation(IDL::Interface const& interface)
  1047. {
  1048. StringBuilder builder;
  1049. SourceGenerator generator { builder };
  1050. generator.set("name", interface.name);
  1051. generator.set("prototype_class", interface.prototype_class);
  1052. generator.set("wrapper_class", interface.wrapper_class);
  1053. generator.set("constructor_class", interface.constructor_class);
  1054. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1055. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1056. generator.append(R"~~~(
  1057. #include <LibJS/Heap/Heap.h>
  1058. #include <LibJS/Runtime/GlobalObject.h>
  1059. #include <LibWeb/Bindings/@constructor_class@.h>
  1060. #include <LibWeb/Bindings/@prototype_class@.h>
  1061. #include <LibWeb/Bindings/@wrapper_class@.h>
  1062. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1063. #include <LibWeb/Bindings/WindowObject.h>
  1064. #if __has_include(<LibWeb/CSS/@name@.h>)
  1065. # include <LibWeb/CSS/@name@.h>
  1066. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1067. # include <LibWeb/DOM/@name@.h>
  1068. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1069. # include <LibWeb/HTML/@name@.h>
  1070. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1071. # include <LibWeb/UIEvents/@name@.h>
  1072. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1073. # include <LibWeb/HighResolutionTime/@name@.h>
  1074. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1075. # include <LibWeb/NavigationTiming/@name@.h>
  1076. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1077. # include <LibWeb/SVG/@name@.h>
  1078. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1079. # include <LibWeb/XHR/@name@.h>
  1080. #endif
  1081. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1082. using namespace Web::CSS;
  1083. using namespace Web::DOM;
  1084. using namespace Web::HTML;
  1085. namespace Web::Bindings {
  1086. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  1087. : NativeFunction(*global_object.function_prototype())
  1088. {
  1089. }
  1090. @constructor_class@::~@constructor_class@()
  1091. {
  1092. }
  1093. JS::Value @constructor_class@::call()
  1094. {
  1095. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  1096. return {};
  1097. }
  1098. JS::Value @constructor_class@::construct(FunctionObject&)
  1099. {
  1100. )~~~");
  1101. if (interface.constructors.is_empty()) {
  1102. // No constructor
  1103. generator.set("constructor.length", "0");
  1104. generator.append(R"~~~(
  1105. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::NotAConstructor, "@name@");
  1106. return {};
  1107. )~~~");
  1108. } else if (interface.constructors.size() == 1) {
  1109. // Single constructor
  1110. auto& constructor = interface.constructors[0];
  1111. generator.set("constructor.length", String::number(constructor.length()));
  1112. generator.append(R"~~~(
  1113. [[maybe_unused]] auto& vm = this->vm();
  1114. auto& global_object = this->global_object();
  1115. auto& window = static_cast<WindowObject&>(global_object);
  1116. )~~~");
  1117. if (!constructor.parameters.is_empty()) {
  1118. generate_argument_count_check(generator, constructor);
  1119. StringBuilder arguments_builder;
  1120. generate_arguments(generator, constructor.parameters, arguments_builder);
  1121. generator.set(".constructor_arguments", arguments_builder.string_view());
  1122. generator.append(R"~~~(
  1123. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window, @.constructor_arguments@); });
  1124. )~~~");
  1125. } else {
  1126. generator.append(R"~~~(
  1127. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window); });
  1128. )~~~");
  1129. }
  1130. generator.append(R"~~~(
  1131. if (should_return_empty(impl))
  1132. return JS::Value();
  1133. return @wrapper_class@::create(global_object, impl.release_value());
  1134. )~~~");
  1135. } else {
  1136. // Multiple constructor overloads - can't do that yet.
  1137. TODO();
  1138. }
  1139. generator.append(R"~~~(
  1140. }
  1141. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  1142. {
  1143. auto& vm = this->vm();
  1144. auto& window = static_cast<WindowObject&>(global_object);
  1145. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  1146. NativeFunction::initialize(global_object);
  1147. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  1148. define_direct_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  1149. )~~~");
  1150. for (auto& constant : interface.constants) {
  1151. auto constant_generator = generator.fork();
  1152. constant_generator.set("constant.name", constant.name);
  1153. constant_generator.set("constant.value", constant.value);
  1154. constant_generator.append(R"~~~(
  1155. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1156. )~~~");
  1157. }
  1158. // https://heycam.github.io/webidl/#es-operations
  1159. for (auto& function : interface.static_functions) {
  1160. auto function_generator = generator.fork();
  1161. function_generator.set("function.name", function.name);
  1162. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1163. function_generator.set("function.length", String::number(function.length()));
  1164. function_generator.append(R"~~~(
  1165. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1166. )~~~");
  1167. }
  1168. generator.append(R"~~~(
  1169. }
  1170. )~~~");
  1171. // Implementation: Static Functions
  1172. for (auto& function : interface.static_functions) {
  1173. generate_function(generator, function, StaticFunction::Yes, interface.constructor_class, interface.fully_qualified_name);
  1174. }
  1175. generator.append(R"~~~(
  1176. } // namespace Web::Bindings
  1177. )~~~");
  1178. outln("{}", generator.as_string_view());
  1179. }
  1180. static void generate_prototype_header(IDL::Interface const& interface)
  1181. {
  1182. StringBuilder builder;
  1183. SourceGenerator generator { builder };
  1184. generator.set("name", interface.name);
  1185. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1186. generator.set("prototype_class", interface.prototype_class);
  1187. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1188. generator.append(R"~~~(
  1189. #pragma once
  1190. #include <LibJS/Runtime/Object.h>
  1191. namespace Web::Bindings {
  1192. class @prototype_class@ : public JS::Object {
  1193. JS_OBJECT(@prototype_class@, JS::Object);
  1194. public:
  1195. explicit @prototype_class@(JS::GlobalObject&);
  1196. virtual void initialize(JS::GlobalObject&) override;
  1197. virtual ~@prototype_class@() override;
  1198. private:
  1199. )~~~");
  1200. for (auto& function : interface.functions) {
  1201. auto function_generator = generator.fork();
  1202. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1203. function_generator.append(R"~~~(
  1204. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1205. )~~~");
  1206. }
  1207. if (interface.has_stringifier) {
  1208. auto stringifier_generator = generator.fork();
  1209. stringifier_generator.append(R"~~~(
  1210. JS_DECLARE_NATIVE_FUNCTION(to_string);
  1211. )~~~");
  1212. }
  1213. for (auto& attribute : interface.attributes) {
  1214. auto attribute_generator = generator.fork();
  1215. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1216. attribute_generator.append(R"~~~(
  1217. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_getter);
  1218. )~~~");
  1219. if (!attribute.readonly) {
  1220. attribute_generator.append(R"~~~(
  1221. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_setter);
  1222. )~~~");
  1223. }
  1224. }
  1225. generator.append(R"~~~(
  1226. };
  1227. } // namespace Web::Bindings
  1228. )~~~");
  1229. outln("{}", generator.as_string_view());
  1230. }
  1231. void generate_prototype_implementation(IDL::Interface const& interface)
  1232. {
  1233. StringBuilder builder;
  1234. SourceGenerator generator { builder };
  1235. generator.set("name", interface.name);
  1236. generator.set("parent_name", interface.parent_name);
  1237. generator.set("prototype_class", interface.prototype_class);
  1238. generator.set("prototype_base_class", interface.prototype_base_class);
  1239. generator.set("wrapper_class", interface.wrapper_class);
  1240. generator.set("constructor_class", interface.constructor_class);
  1241. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1242. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1243. generator.append(R"~~~(
  1244. #include <AK/Function.h>
  1245. #include <LibJS/Runtime/Array.h>
  1246. #include <LibJS/Runtime/Error.h>
  1247. #include <LibJS/Runtime/FunctionObject.h>
  1248. #include <LibJS/Runtime/GlobalObject.h>
  1249. #include <LibJS/Runtime/TypedArray.h>
  1250. #include <LibWeb/Bindings/@prototype_class@.h>
  1251. #include <LibWeb/Bindings/@wrapper_class@.h>
  1252. #include <LibWeb/Bindings/AbortSignalWrapper.h>
  1253. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  1254. #include <LibWeb/Bindings/CSSStyleSheetWrapper.h>
  1255. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  1256. #include <LibWeb/Bindings/CommentWrapper.h>
  1257. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  1258. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  1259. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  1260. #include <LibWeb/Bindings/DocumentWrapper.h>
  1261. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  1262. #include <LibWeb/Bindings/EventWrapper.h>
  1263. #include <LibWeb/Bindings/EventWrapperFactory.h>
  1264. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1265. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  1266. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  1267. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  1268. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  1269. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  1270. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  1271. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  1272. #include <LibWeb/Bindings/ImageDataWrapper.h>
  1273. #include <LibWeb/Bindings/LocationObject.h>
  1274. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  1275. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  1276. #include <LibWeb/Bindings/RangeWrapper.h>
  1277. #include <LibWeb/Bindings/StyleSheetListWrapper.h>
  1278. #include <LibWeb/Bindings/TextWrapper.h>
  1279. #include <LibWeb/Bindings/WindowObject.h>
  1280. #include <LibWeb/DOM/Element.h>
  1281. #include <LibWeb/DOM/EventListener.h>
  1282. #include <LibWeb/DOM/Range.h>
  1283. #include <LibWeb/DOM/Window.h>
  1284. #include <LibWeb/HTML/EventHandler.h>
  1285. #include <LibWeb/HTML/HTMLElement.h>
  1286. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  1287. #include <LibWeb/Origin.h>
  1288. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  1289. # include <LibWeb/Bindings/@prototype_base_class@.h>
  1290. #endif
  1291. #if __has_include(<LibWeb/CSS/@name@.h>)
  1292. # include <LibWeb/CSS/@name@.h>
  1293. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1294. # include <LibWeb/DOM/@name@.h>
  1295. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1296. # include <LibWeb/HTML/@name@.h>
  1297. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1298. # include <LibWeb/UIEvents/@name@.h>
  1299. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1300. # include <LibWeb/HighResolutionTime/@name@.h>
  1301. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1302. # include <LibWeb/NavigationTiming/@name@.h>
  1303. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1304. # include <LibWeb/SVG/@name@.h>
  1305. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1306. # include <LibWeb/XHR/@name@.h>
  1307. #endif
  1308. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1309. using namespace Web::CSS;
  1310. using namespace Web::DOM;
  1311. using namespace Web::HTML;
  1312. using namespace Web::NavigationTiming;
  1313. using namespace Web::XHR;
  1314. namespace Web::Bindings {
  1315. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  1316. : Object(*global_object.object_prototype())
  1317. {
  1318. )~~~");
  1319. if (interface.name == "DOMException") {
  1320. // https://heycam.github.io/webidl/#es-DOMException-specialness
  1321. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  1322. generator.append(R"~~~(
  1323. auto success = internal_set_prototype_of(global_object.error_prototype());
  1324. VERIFY(success);
  1325. )~~~");
  1326. } else if (!interface.parent_name.is_empty()) {
  1327. generator.append(R"~~~(
  1328. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  1329. VERIFY(success);
  1330. )~~~");
  1331. }
  1332. // FIXME: Currently almost everything gets default_attributes but it should be configurable per attribute.
  1333. // See the spec links for details
  1334. generator.append(R"~~~(
  1335. }
  1336. @prototype_class@::~@prototype_class@()
  1337. {
  1338. }
  1339. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  1340. {
  1341. [[maybe_unused]] auto& vm = this->vm();
  1342. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;
  1343. )~~~");
  1344. // https://heycam.github.io/webidl/#es-attributes
  1345. for (auto& attribute : interface.attributes) {
  1346. auto attribute_generator = generator.fork();
  1347. attribute_generator.set("attribute.name", attribute.name);
  1348. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1349. if (attribute.readonly)
  1350. attribute_generator.set("attribute.setter_callback", "nullptr");
  1351. else
  1352. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1353. attribute_generator.append(R"~~~(
  1354. define_native_accessor("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  1355. )~~~");
  1356. }
  1357. // https://heycam.github.io/webidl/#es-constants
  1358. for (auto& constant : interface.constants) {
  1359. auto constant_generator = generator.fork();
  1360. constant_generator.set("constant.name", constant.name);
  1361. constant_generator.set("constant.value", constant.value);
  1362. constant_generator.append(R"~~~(
  1363. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1364. )~~~");
  1365. }
  1366. // https://heycam.github.io/webidl/#es-operations
  1367. for (auto& function : interface.functions) {
  1368. auto function_generator = generator.fork();
  1369. function_generator.set("function.name", function.name);
  1370. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1371. function_generator.set("function.length", String::number(function.length()));
  1372. function_generator.append(R"~~~(
  1373. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1374. )~~~");
  1375. }
  1376. if (interface.has_stringifier) {
  1377. auto stringifier_generator = generator.fork();
  1378. stringifier_generator.append(R"~~~(
  1379. define_native_function("toString", to_string, 0, default_attributes);
  1380. )~~~");
  1381. }
  1382. generator.append(R"~~~(
  1383. Object::initialize(global_object);
  1384. }
  1385. )~~~");
  1386. if (!interface.attributes.is_empty() || !interface.functions.is_empty() || interface.has_stringifier) {
  1387. generator.append(R"~~~(
  1388. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  1389. {
  1390. auto* this_object = vm.this_value(global_object).to_object(global_object);
  1391. if (!this_object)
  1392. return {};
  1393. )~~~");
  1394. if (interface.name == "EventTarget") {
  1395. generator.append(R"~~~(
  1396. if (is<WindowObject>(this_object)) {
  1397. return &static_cast<WindowObject*>(this_object)->impl();
  1398. }
  1399. )~~~");
  1400. }
  1401. generator.append(R"~~~(
  1402. if (!is<@wrapper_class@>(this_object)) {
  1403. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@fully_qualified_name@");
  1404. return nullptr;
  1405. }
  1406. return &static_cast<@wrapper_class@*>(this_object)->impl();
  1407. }
  1408. )~~~");
  1409. }
  1410. for (auto& attribute : interface.attributes) {
  1411. auto attribute_generator = generator.fork();
  1412. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1413. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1414. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1415. if (attribute.extended_attributes.contains("ImplementedAs")) {
  1416. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  1417. attribute_generator.set("attribute.cpp_getter_name", implemented_as);
  1418. } else {
  1419. attribute_generator.set("attribute.cpp_getter_name", attribute.name.to_snakecase());
  1420. }
  1421. if (attribute.extended_attributes.contains("Reflect")) {
  1422. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1423. if (attribute_name.is_null())
  1424. attribute_name = attribute.name;
  1425. attribute_name = make_input_acceptable_cpp(attribute_name);
  1426. attribute_generator.set("attribute.reflect_name", attribute_name);
  1427. } else {
  1428. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  1429. }
  1430. attribute_generator.append(R"~~~(
  1431. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.getter_callback@)
  1432. {
  1433. auto* impl = impl_from(vm, global_object);
  1434. if (!impl)
  1435. return {};
  1436. )~~~");
  1437. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1438. attribute_generator.append(R"~~~(
  1439. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1440. return JS::js_null();
  1441. )~~~");
  1442. }
  1443. if (attribute.extended_attributes.contains("Reflect")) {
  1444. if (attribute.type.name != "boolean") {
  1445. attribute_generator.append(R"~~~(
  1446. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1447. )~~~");
  1448. } else {
  1449. attribute_generator.append(R"~~~(
  1450. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1451. )~~~");
  1452. }
  1453. } else {
  1454. attribute_generator.append(R"~~~(
  1455. auto retval = impl->@attribute.cpp_getter_name@();
  1456. )~~~");
  1457. }
  1458. generate_return_statement(generator, attribute.type);
  1459. attribute_generator.append(R"~~~(
  1460. }
  1461. )~~~");
  1462. if (!attribute.readonly) {
  1463. attribute_generator.append(R"~~~(
  1464. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.setter_callback@)
  1465. {
  1466. auto* impl = impl_from(vm, global_object);
  1467. if (!impl)
  1468. return {};
  1469. auto value = vm.argument(0);
  1470. )~~~");
  1471. generate_to_cpp(generator, attribute, "value", "", "cpp_value", false, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1472. if (attribute.extended_attributes.contains("Reflect")) {
  1473. if (attribute.type.name != "boolean") {
  1474. attribute_generator.append(R"~~~(
  1475. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1476. )~~~");
  1477. } else {
  1478. attribute_generator.append(R"~~~(
  1479. if (!cpp_value)
  1480. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1481. else
  1482. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1483. )~~~");
  1484. }
  1485. } else {
  1486. attribute_generator.append(R"~~~(
  1487. impl->set_@attribute.name:snakecase@(cpp_value);
  1488. )~~~");
  1489. }
  1490. attribute_generator.append(R"~~~(
  1491. return {};
  1492. }
  1493. )~~~");
  1494. }
  1495. }
  1496. // Implementation: Functions
  1497. for (auto& function : interface.functions) {
  1498. generate_function(generator, function, StaticFunction::No, interface.prototype_class, interface.fully_qualified_name);
  1499. }
  1500. if (interface.has_stringifier) {
  1501. auto stringifier_generator = generator.fork();
  1502. stringifier_generator.set("class_name", interface.prototype_class);
  1503. if (interface.stringifier_attribute.has_value())
  1504. stringifier_generator.set("attribute.cpp_getter_name", interface.stringifier_attribute->to_snakecase());
  1505. stringifier_generator.append(R"~~~(
  1506. JS_DEFINE_NATIVE_FUNCTION(@class_name@::to_string)
  1507. {
  1508. auto* impl = impl_from(vm, global_object);
  1509. if (!impl)
  1510. return {};
  1511. )~~~");
  1512. if (interface.stringifier_attribute.has_value()) {
  1513. stringifier_generator.append(R"~~~(
  1514. auto retval = impl->@attribute.cpp_getter_name@();
  1515. )~~~");
  1516. } else {
  1517. stringifier_generator.append(R"~~~(
  1518. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->to_string(); });
  1519. if (should_return_empty(result))
  1520. return JS::Value();
  1521. auto retval = result.release_value();
  1522. )~~~");
  1523. }
  1524. stringifier_generator.append(R"~~~(
  1525. return JS::js_string(vm, move(retval));
  1526. }
  1527. )~~~");
  1528. }
  1529. generator.append(R"~~~(
  1530. } // namespace Web::Bindings
  1531. )~~~");
  1532. outln("{}", generator.as_string_view());
  1533. }