WrapperGenerator.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/Debug.h>
  29. #include <AK/GenericLexer.h>
  30. #include <AK/HashMap.h>
  31. #include <AK/LexicalPath.h>
  32. #include <AK/SourceGenerator.h>
  33. #include <AK/StringBuilder.h>
  34. #include <LibCore/ArgsParser.h>
  35. #include <LibCore/File.h>
  36. #include <ctype.h>
  37. static String snake_name(const StringView& title_name)
  38. {
  39. StringBuilder builder;
  40. bool first = true;
  41. bool last_was_uppercase = false;
  42. for (auto ch : title_name) {
  43. if (isupper(ch)) {
  44. if (!first && !last_was_uppercase)
  45. builder.append('_');
  46. builder.append(tolower(ch));
  47. } else {
  48. builder.append(ch);
  49. }
  50. first = false;
  51. last_was_uppercase = isupper(ch);
  52. }
  53. return builder.to_string();
  54. }
  55. static String make_input_acceptable_cpp(const String& input)
  56. {
  57. if (input.is_one_of("class", "template", "for", "default", "char", "namespace")) {
  58. StringBuilder builder;
  59. builder.append(input);
  60. builder.append('_');
  61. return builder.to_string();
  62. }
  63. String input_without_dashes = input;
  64. input_without_dashes.replace("-", "_");
  65. return input_without_dashes;
  66. }
  67. static void report_parsing_error(StringView message, StringView filename, StringView input, size_t offset)
  68. {
  69. // FIXME: Spaghetti code ahead.
  70. size_t lineno = 1;
  71. size_t colno = 1;
  72. size_t start_line = 0;
  73. size_t line_length = 0;
  74. for (size_t index = 0; index < input.length(); ++index) {
  75. if (offset == index)
  76. colno = index - start_line + 1;
  77. if (input[index] == '\n') {
  78. if (index >= offset)
  79. break;
  80. start_line = index + 1;
  81. line_length = 0;
  82. ++lineno;
  83. } else {
  84. ++line_length;
  85. }
  86. }
  87. StringBuilder error_message;
  88. error_message.appendff("{}\n", input.substring_view(start_line, line_length));
  89. for (size_t i = 0; i < colno - 1; ++i)
  90. error_message.append(' ');
  91. error_message.append("\033[1;31m^\n");
  92. error_message.appendff("{}:{}: error: {}\033[0m\n", filename, lineno, message);
  93. warnln("{}", error_message.string_view());
  94. exit(EXIT_FAILURE);
  95. }
  96. namespace IDL {
  97. template<typename FunctionType>
  98. static size_t get_function_length(FunctionType& function)
  99. {
  100. size_t length = 0;
  101. for (auto& parameter : function.parameters) {
  102. if (!parameter.optional)
  103. length++;
  104. }
  105. return length;
  106. }
  107. struct Type {
  108. String name;
  109. bool nullable { false };
  110. };
  111. struct Parameter {
  112. Type type;
  113. String name;
  114. bool optional { false };
  115. };
  116. struct Function {
  117. Type return_type;
  118. String name;
  119. Vector<Parameter> parameters;
  120. HashMap<String, String> extended_attributes;
  121. size_t length() const { return get_function_length(*this); }
  122. };
  123. struct Constructor {
  124. String name;
  125. Vector<Parameter> parameters;
  126. size_t length() const { return get_function_length(*this); }
  127. };
  128. struct Constant {
  129. Type type;
  130. String name;
  131. String value;
  132. };
  133. struct Attribute {
  134. bool readonly { false };
  135. Type type;
  136. String name;
  137. HashMap<String, String> extended_attributes;
  138. // Added for convenience after parsing
  139. String getter_callback_name;
  140. String setter_callback_name;
  141. };
  142. struct Interface {
  143. String name;
  144. String parent_name;
  145. Vector<Attribute> attributes;
  146. Vector<Constant> constants;
  147. Vector<Constructor> constructors;
  148. Vector<Function> functions;
  149. // Added for convenience after parsing
  150. String wrapper_class;
  151. String wrapper_base_class;
  152. String fully_qualified_name;
  153. String constructor_class;
  154. String prototype_class;
  155. String prototype_base_class;
  156. };
  157. static OwnPtr<Interface> parse_interface(StringView filename, const StringView& input)
  158. {
  159. auto interface = make<Interface>();
  160. GenericLexer lexer(input);
  161. auto assert_specific = [&](char ch) {
  162. if (!lexer.consume_specific(ch))
  163. report_parsing_error(String::formatted("expected '{}'", ch), filename, input, lexer.tell());
  164. };
  165. auto consume_whitespace = [&] {
  166. bool consumed = true;
  167. while (consumed) {
  168. consumed = lexer.consume_while([](char ch) { return isspace(ch); }).length() > 0;
  169. if (lexer.consume_specific("//")) {
  170. lexer.consume_until('\n');
  171. consumed = true;
  172. }
  173. }
  174. };
  175. auto assert_string = [&](const StringView& expected) {
  176. if (!lexer.consume_specific(expected))
  177. report_parsing_error(String::formatted("expected '{}'", expected), filename, input, lexer.tell());
  178. };
  179. assert_string("interface");
  180. consume_whitespace();
  181. interface->name = lexer.consume_until([](auto ch) { return isspace(ch); });
  182. consume_whitespace();
  183. if (lexer.consume_specific(':')) {
  184. consume_whitespace();
  185. interface->parent_name = lexer.consume_until([](auto ch) { return isspace(ch); });
  186. consume_whitespace();
  187. }
  188. assert_specific('{');
  189. auto parse_type = [&] {
  190. bool unsigned_ = lexer.consume_specific("unsigned");
  191. if (unsigned_)
  192. consume_whitespace();
  193. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '?'; });
  194. auto nullable = lexer.consume_specific('?');
  195. StringBuilder builder;
  196. if (unsigned_)
  197. builder.append("unsigned ");
  198. builder.append(name);
  199. return Type { builder.to_string(), nullable };
  200. };
  201. auto parse_attribute = [&](HashMap<String, String>& extended_attributes) {
  202. bool readonly = lexer.consume_specific("readonly");
  203. if (readonly)
  204. consume_whitespace();
  205. if (lexer.consume_specific("attribute"))
  206. consume_whitespace();
  207. auto type = parse_type();
  208. consume_whitespace();
  209. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ';'; });
  210. consume_whitespace();
  211. assert_specific(';');
  212. Attribute attribute;
  213. attribute.readonly = readonly;
  214. attribute.type = type;
  215. attribute.name = name;
  216. attribute.getter_callback_name = String::formatted("{}_getter", snake_name(attribute.name));
  217. attribute.setter_callback_name = String::formatted("{}_setter", snake_name(attribute.name));
  218. attribute.extended_attributes = move(extended_attributes);
  219. interface->attributes.append(move(attribute));
  220. };
  221. auto parse_constant = [&] {
  222. lexer.consume_specific("const");
  223. consume_whitespace();
  224. Constant constant;
  225. constant.type = parse_type();
  226. consume_whitespace();
  227. constant.name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '='; });
  228. consume_whitespace();
  229. lexer.consume_specific('=');
  230. consume_whitespace();
  231. constant.value = lexer.consume_while([](auto ch) { return !isspace(ch) && ch != ';'; });
  232. consume_whitespace();
  233. assert_specific(';');
  234. interface->constants.append(move(constant));
  235. };
  236. auto parse_parameters = [&] {
  237. consume_whitespace();
  238. Vector<Parameter> parameters;
  239. for (;;) {
  240. if (lexer.next_is(')'))
  241. break;
  242. bool optional = lexer.consume_specific("optional");
  243. if (optional)
  244. consume_whitespace();
  245. auto type = parse_type();
  246. consume_whitespace();
  247. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ',' || ch == ')'; });
  248. parameters.append({ move(type), move(name), optional });
  249. if (lexer.next_is(')'))
  250. break;
  251. assert_specific(',');
  252. consume_whitespace();
  253. }
  254. return parameters;
  255. };
  256. auto parse_function = [&](HashMap<String, String>& extended_attributes) {
  257. auto return_type = parse_type();
  258. consume_whitespace();
  259. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '('; });
  260. consume_whitespace();
  261. assert_specific('(');
  262. auto parameters = parse_parameters();
  263. assert_specific(')');
  264. consume_whitespace();
  265. assert_specific(';');
  266. interface->functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  267. };
  268. auto parse_constructor = [&] {
  269. assert_string("constructor");
  270. consume_whitespace();
  271. assert_specific('(');
  272. auto parameters = parse_parameters();
  273. assert_specific(')');
  274. consume_whitespace();
  275. assert_specific(';');
  276. interface->constructors.append(Constructor { interface->name, move(parameters) });
  277. };
  278. auto parse_extended_attributes = [&] {
  279. HashMap<String, String> extended_attributes;
  280. for (;;) {
  281. consume_whitespace();
  282. if (lexer.consume_specific(']'))
  283. break;
  284. auto name = lexer.consume_until([](auto ch) { return ch == ']' || ch == '=' || ch == ','; });
  285. if (lexer.consume_specific('=')) {
  286. auto value = lexer.consume_until([](auto ch) { return ch == ']' || ch == ','; });
  287. extended_attributes.set(name, value);
  288. } else {
  289. extended_attributes.set(name, {});
  290. }
  291. lexer.consume_specific(',');
  292. }
  293. consume_whitespace();
  294. return extended_attributes;
  295. };
  296. for (;;) {
  297. HashMap<String, String> extended_attributes;
  298. consume_whitespace();
  299. if (lexer.consume_specific('}')) {
  300. consume_whitespace();
  301. assert_specific(';');
  302. break;
  303. }
  304. if (lexer.consume_specific('[')) {
  305. extended_attributes = parse_extended_attributes();
  306. }
  307. if (lexer.next_is("constructor")) {
  308. parse_constructor();
  309. continue;
  310. }
  311. if (lexer.next_is("const")) {
  312. parse_constant();
  313. continue;
  314. }
  315. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  316. parse_attribute(extended_attributes);
  317. continue;
  318. }
  319. parse_function(extended_attributes);
  320. }
  321. interface->wrapper_class = String::formatted("{}Wrapper", interface->name);
  322. interface->wrapper_base_class = String::formatted("{}Wrapper", interface->parent_name.is_empty() ? String::empty() : interface->parent_name);
  323. interface->constructor_class = String::formatted("{}Constructor", interface->name);
  324. interface->prototype_class = String::formatted("{}Prototype", interface->name);
  325. interface->prototype_base_class = String::formatted("{}Prototype", interface->parent_name.is_empty() ? "Object" : interface->parent_name);
  326. return interface;
  327. }
  328. }
  329. static void generate_constructor_header(const IDL::Interface&);
  330. static void generate_constructor_implementation(const IDL::Interface&);
  331. static void generate_prototype_header(const IDL::Interface&);
  332. static void generate_prototype_implementation(const IDL::Interface&);
  333. static void generate_header(const IDL::Interface&);
  334. static void generate_implementation(const IDL::Interface&);
  335. int main(int argc, char** argv)
  336. {
  337. Core::ArgsParser args_parser;
  338. const char* path = nullptr;
  339. bool header_mode = false;
  340. bool implementation_mode = false;
  341. bool constructor_header_mode = false;
  342. bool constructor_implementation_mode = false;
  343. bool prototype_header_mode = false;
  344. bool prototype_implementation_mode = false;
  345. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  346. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  347. args_parser.add_option(constructor_header_mode, "Generate the constructor .h file", "constructor-header", 'C');
  348. args_parser.add_option(constructor_implementation_mode, "Generate the constructor .cpp file", "constructor-implementation", 'O');
  349. args_parser.add_option(prototype_header_mode, "Generate the prototype .h file", "prototype-header", 'P');
  350. args_parser.add_option(prototype_implementation_mode, "Generate the prototype .cpp file", "prototype-implementation", 'R');
  351. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  352. args_parser.parse(argc, argv);
  353. auto file_or_error = Core::File::open(path, Core::IODevice::ReadOnly);
  354. if (file_or_error.is_error()) {
  355. fprintf(stderr, "Cannot open %s\n", path);
  356. return 1;
  357. }
  358. LexicalPath lexical_path(path);
  359. auto namespace_ = lexical_path.parts().at(lexical_path.parts().size() - 2);
  360. auto data = file_or_error.value()->read_all();
  361. auto interface = IDL::parse_interface(path, data);
  362. if (!interface) {
  363. warnln("Cannot parse {}", path);
  364. return 1;
  365. }
  366. if (namespace_.is_one_of("DOM", "HTML", "UIEvents", "HighResolutionTime", "NavigationTiming", "SVG", "XHR")) {
  367. StringBuilder builder;
  368. builder.append(namespace_);
  369. builder.append("::");
  370. builder.append(interface->name);
  371. interface->fully_qualified_name = builder.to_string();
  372. } else {
  373. interface->fully_qualified_name = interface->name;
  374. }
  375. if constexpr (WRAPPER_GENERATOR_DEBUG) {
  376. dbgln("Attributes:");
  377. for (auto& attribute : interface->attributes) {
  378. dbgln(" {}{}{} {}",
  379. attribute.readonly ? "readonly " : "",
  380. attribute.type.name,
  381. attribute.type.nullable ? "?" : "",
  382. attribute.name);
  383. }
  384. dbgln("Functions:");
  385. for (auto& function : interface->functions) {
  386. dbgln(" {}{} {}",
  387. function.return_type.name,
  388. function.return_type.nullable ? "?" : "",
  389. function.name);
  390. for (auto& parameter : function.parameters) {
  391. dbgln(" {}{} {}",
  392. parameter.type.name,
  393. parameter.type.nullable ? "?" : "",
  394. parameter.name);
  395. }
  396. }
  397. }
  398. if (header_mode)
  399. generate_header(*interface);
  400. if (implementation_mode)
  401. generate_implementation(*interface);
  402. if (constructor_header_mode)
  403. generate_constructor_header(*interface);
  404. if (constructor_implementation_mode)
  405. generate_constructor_implementation(*interface);
  406. if (prototype_header_mode)
  407. generate_prototype_header(*interface);
  408. if (prototype_implementation_mode)
  409. generate_prototype_implementation(*interface);
  410. return 0;
  411. }
  412. static bool should_emit_wrapper_factory(const IDL::Interface& interface)
  413. {
  414. // FIXME: This is very hackish.
  415. if (interface.name == "Event")
  416. return false;
  417. if (interface.name == "EventTarget")
  418. return false;
  419. if (interface.name == "Node")
  420. return false;
  421. if (interface.name == "Text")
  422. return false;
  423. if (interface.name == "Document")
  424. return false;
  425. if (interface.name == "DocumentType")
  426. return false;
  427. if (interface.name.ends_with("Element"))
  428. return false;
  429. return true;
  430. }
  431. static bool is_wrappable_type(const IDL::Type& type)
  432. {
  433. if (type.name == "Node")
  434. return true;
  435. if (type.name == "Document")
  436. return true;
  437. if (type.name == "Text")
  438. return true;
  439. if (type.name == "DocumentType")
  440. return true;
  441. if (type.name.ends_with("Element"))
  442. return true;
  443. if (type.name == "ImageData")
  444. return true;
  445. return false;
  446. }
  447. static void generate_header(const IDL::Interface& interface)
  448. {
  449. StringBuilder builder;
  450. SourceGenerator generator { builder };
  451. generator.set("name", interface.name);
  452. generator.set("fully_qualified_name", interface.fully_qualified_name);
  453. generator.set("wrapper_base_class", interface.wrapper_base_class);
  454. generator.set("wrapper_class", interface.wrapper_class);
  455. generator.set("wrapper_class:snakecase", snake_name(interface.wrapper_class));
  456. generator.append(R"~~~(
  457. #pragma once
  458. #include <LibWeb/Bindings/Wrapper.h>
  459. // FIXME: This is very strange.
  460. #if __has_include(<LibWeb/DOM/@name@.h>)
  461. # include <LibWeb/DOM/@name@.h>
  462. #elif __has_include(<LibWeb/HTML/@name@.h>)
  463. # include <LibWeb/HTML/@name@.h>
  464. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  465. # include <LibWeb/UIEvents/@name@.h>
  466. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  467. # include <LibWeb/HighResolutionTime/@name@.h>
  468. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  469. # include <LibWeb/NavigationTiming/@name@.h>
  470. #elif __has_include(<LibWeb/SVG/@name@.h>)
  471. # include <LibWeb/SVG/@name@.h>
  472. #elif __has_include(<LibWeb/XHR/@name@.h>)
  473. # include <LibWeb/XHR/@name@.h>
  474. #endif
  475. )~~~");
  476. if (interface.wrapper_base_class != "Wrapper") {
  477. generator.append(R"~~~(
  478. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  479. )~~~");
  480. }
  481. generator.append(R"~~~(
  482. namespace Web::Bindings {
  483. class @wrapper_class@ : public @wrapper_base_class@ {
  484. JS_OBJECT(@wrapper_class@, @wrapper_base_class@);
  485. public:
  486. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  487. virtual void initialize(JS::GlobalObject&) override;
  488. virtual ~@wrapper_class@() override;
  489. )~~~");
  490. if (interface.wrapper_base_class == "Wrapper") {
  491. generator.append(R"~~~(
  492. @fully_qualified_name@& impl() { return *m_impl; }
  493. const @fully_qualified_name@& impl() const { return *m_impl; }
  494. )~~~");
  495. } else {
  496. generator.append(R"~~~(
  497. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  498. const @fully_qualified_name@& impl() const { return static_cast<const @fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  499. )~~~");
  500. }
  501. generator.append(R"~~~(
  502. private:
  503. )~~~");
  504. if (interface.wrapper_base_class == "Wrapper") {
  505. generator.append(R"~~~(
  506. NonnullRefPtr<@fully_qualified_name@> m_impl;
  507. )~~~");
  508. }
  509. generator.append(R"~~~(
  510. };
  511. )~~~");
  512. if (should_emit_wrapper_factory(interface)) {
  513. generator.append(R"~~~(
  514. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  515. )~~~");
  516. }
  517. generator.append(R"~~~(
  518. } // namespace Web::Bindings
  519. )~~~");
  520. outln("{}", generator.as_string_view());
  521. }
  522. void generate_implementation(const IDL::Interface& interface)
  523. {
  524. StringBuilder builder;
  525. SourceGenerator generator { builder };
  526. generator.set("name", interface.name);
  527. generator.set("wrapper_class", interface.wrapper_class);
  528. generator.set("wrapper_base_class", interface.wrapper_base_class);
  529. generator.set("prototype_class", interface.prototype_class);
  530. generator.set("fully_qualified_name", interface.fully_qualified_name);
  531. generator.append(R"~~~(
  532. #include <AK/FlyString.h>
  533. #include <LibJS/Runtime/Array.h>
  534. #include <LibJS/Runtime/Error.h>
  535. #include <LibJS/Runtime/Function.h>
  536. #include <LibJS/Runtime/GlobalObject.h>
  537. #include <LibJS/Runtime/Uint8ClampedArray.h>
  538. #include <LibJS/Runtime/Value.h>
  539. #include <LibWeb/Bindings/@prototype_class@.h>
  540. #include <LibWeb/Bindings/@wrapper_class@.h>
  541. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  542. #include <LibWeb/Bindings/CommentWrapper.h>
  543. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  544. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  545. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  546. #include <LibWeb/Bindings/DocumentWrapper.h>
  547. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  548. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  549. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  550. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  551. #include <LibWeb/Bindings/ImageDataWrapper.h>
  552. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  553. #include <LibWeb/Bindings/TextWrapper.h>
  554. #include <LibWeb/Bindings/WindowObject.h>
  555. #include <LibWeb/DOM/Element.h>
  556. #include <LibWeb/DOM/EventListener.h>
  557. #include <LibWeb/HTML/HTMLElement.h>
  558. #include <LibWeb/Origin.h>
  559. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  560. using namespace Web::DOM;
  561. using namespace Web::HTML;
  562. namespace Web::Bindings {
  563. )~~~");
  564. if (interface.wrapper_base_class == "Wrapper") {
  565. generator.append(R"~~~(
  566. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  567. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  568. , m_impl(impl)
  569. {
  570. }
  571. )~~~");
  572. } else {
  573. generator.append(R"~~~(
  574. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  575. : @wrapper_base_class@(global_object, impl)
  576. {
  577. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  578. }
  579. )~~~");
  580. }
  581. generator.append(R"~~~(
  582. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  583. {
  584. @wrapper_base_class@::initialize(global_object);
  585. }
  586. @wrapper_class@::~@wrapper_class@()
  587. {
  588. }
  589. )~~~");
  590. if (should_emit_wrapper_factory(interface)) {
  591. generator.append(R"~~~(
  592. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  593. {
  594. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  595. }
  596. )~~~");
  597. }
  598. generator.append(R"~~~(
  599. } // namespace Web::Bindings
  600. )~~~");
  601. outln("{}", generator.as_string_view());
  602. }
  603. static void generate_constructor_header(const IDL::Interface& interface)
  604. {
  605. StringBuilder builder;
  606. SourceGenerator generator { builder };
  607. generator.set("name", interface.name);
  608. generator.set("fully_qualified_name", interface.fully_qualified_name);
  609. generator.set("constructor_class", interface.constructor_class);
  610. generator.set("constructor_class:snakecase", snake_name(interface.constructor_class));
  611. generator.append(R"~~~(
  612. #pragma once
  613. #include <LibJS/Runtime/NativeFunction.h>
  614. namespace Web::Bindings {
  615. class @constructor_class@ : public JS::NativeFunction {
  616. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  617. public:
  618. explicit @constructor_class@(JS::GlobalObject&);
  619. virtual void initialize(JS::GlobalObject&) override;
  620. virtual ~@constructor_class@() override;
  621. virtual JS::Value call() override;
  622. virtual JS::Value construct(JS::Function& new_target) override;
  623. private:
  624. virtual bool has_constructor() const override { return true; }
  625. };
  626. } // namespace Web::Bindings
  627. )~~~");
  628. outln("{}", generator.as_string_view());
  629. }
  630. void generate_constructor_implementation(const IDL::Interface& interface)
  631. {
  632. StringBuilder builder;
  633. SourceGenerator generator { builder };
  634. generator.set("name", interface.name);
  635. generator.set("prototype_class", interface.prototype_class);
  636. generator.set("wrapper_class", interface.wrapper_class);
  637. generator.set("constructor_class", interface.constructor_class);
  638. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  639. generator.set("fully_qualified_name", interface.fully_qualified_name);
  640. generator.append(R"~~~(
  641. #include <LibJS/Heap/Heap.h>
  642. #include <LibJS/Runtime/GlobalObject.h>
  643. #include <LibWeb/Bindings/@constructor_class@.h>
  644. #include <LibWeb/Bindings/@prototype_class@.h>
  645. #include <LibWeb/Bindings/@wrapper_class@.h>
  646. #include <LibWeb/Bindings/WindowObject.h>
  647. #if __has_include(<LibWeb/DOM/@name@.h>)
  648. # include <LibWeb/DOM/@name@.h>
  649. #elif __has_include(<LibWeb/HTML/@name@.h>)
  650. # include <LibWeb/HTML/@name@.h>
  651. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  652. # include <LibWeb/UIEvents/@name@.h>
  653. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  654. # include <LibWeb/HighResolutionTime/@name@.h>
  655. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  656. # include <LibWeb/NavigationTiming/@name@.h>
  657. #elif __has_include(<LibWeb/SVG/@name@.h>)
  658. # include <LibWeb/SVG/@name@.h>
  659. #elif __has_include(<LibWeb/XHR/@name@.h>)
  660. # include <LibWeb/XHR/@name@.h>
  661. #endif
  662. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  663. using namespace Web::DOM;
  664. using namespace Web::HTML;
  665. namespace Web::Bindings {
  666. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  667. : NativeFunction(*global_object.function_prototype())
  668. {
  669. }
  670. @constructor_class@::~@constructor_class@()
  671. {
  672. }
  673. JS::Value @constructor_class@::call()
  674. {
  675. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  676. return {};
  677. }
  678. JS::Value @constructor_class@::construct(Function&)
  679. {
  680. return {};
  681. #if 0
  682. // FIXME: It would be cool to construct stuff!
  683. auto& window = static_cast<WindowObject&>(global_object());
  684. return heap().allocate<@wrapper_class@>(window, window, @fully_qualified_name@::create(window.impl()));
  685. #endif
  686. }
  687. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  688. {
  689. auto& vm = this->vm();
  690. auto& window = static_cast<WindowObject&>(global_object);
  691. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  692. NativeFunction::initialize(global_object);
  693. define_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  694. define_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
  695. )~~~");
  696. for (auto& constant : interface.constants) {
  697. auto constant_generator = generator.fork();
  698. constant_generator.set("constant.name", constant.name);
  699. constant_generator.set("constant.value", constant.value);
  700. constant_generator.append(R"~~~(
  701. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  702. )~~~");
  703. }
  704. generator.append(R"~~~(
  705. }
  706. } // namespace Web::Bindings
  707. )~~~");
  708. outln("{}", generator.as_string_view());
  709. }
  710. static void generate_prototype_header(const IDL::Interface& interface)
  711. {
  712. StringBuilder builder;
  713. SourceGenerator generator { builder };
  714. generator.set("name", interface.name);
  715. generator.set("fully_qualified_name", interface.fully_qualified_name);
  716. generator.set("prototype_class", interface.prototype_class);
  717. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  718. generator.append(R"~~~(
  719. #pragma once
  720. #include <LibJS/Runtime/Object.h>
  721. namespace Web::Bindings {
  722. class @prototype_class@ : public JS::Object {
  723. JS_OBJECT(@prototype_class@, JS::Object);
  724. public:
  725. explicit @prototype_class@(JS::GlobalObject&);
  726. virtual void initialize(JS::GlobalObject&) override;
  727. virtual ~@prototype_class@() override;
  728. private:
  729. )~~~");
  730. for (auto& function : interface.functions) {
  731. auto function_generator = generator.fork();
  732. function_generator.set("function.name:snakecase", snake_name(function.name));
  733. function_generator.append(R"~~~(
  734. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  735. )~~~");
  736. }
  737. for (auto& attribute : interface.attributes) {
  738. auto attribute_generator = generator.fork();
  739. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  740. attribute_generator.append(R"~~~(
  741. JS_DECLARE_NATIVE_GETTER(@attribute.name:snakecase@_getter);
  742. )~~~");
  743. if (!attribute.readonly) {
  744. attribute_generator.append(R"~~~(
  745. JS_DECLARE_NATIVE_SETTER(@attribute.name:snakecase@_setter);
  746. )~~~");
  747. }
  748. }
  749. generator.append(R"~~~(
  750. };
  751. } // namespace Web::Bindings
  752. )~~~");
  753. outln("{}", generator.as_string_view());
  754. }
  755. void generate_prototype_implementation(const IDL::Interface& interface)
  756. {
  757. StringBuilder builder;
  758. SourceGenerator generator { builder };
  759. generator.set("name", interface.name);
  760. generator.set("parent_name", interface.parent_name);
  761. generator.set("prototype_class", interface.prototype_class);
  762. generator.set("prototype_base_class", interface.prototype_base_class);
  763. generator.set("wrapper_class", interface.wrapper_class);
  764. generator.set("constructor_class", interface.constructor_class);
  765. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  766. generator.set("fully_qualified_name", interface.fully_qualified_name);
  767. generator.append(R"~~~(
  768. #include <AK/Function.h>
  769. #include <LibJS/Runtime/Array.h>
  770. #include <LibJS/Runtime/Error.h>
  771. #include <LibJS/Runtime/Function.h>
  772. #include <LibJS/Runtime/GlobalObject.h>
  773. #include <LibJS/Runtime/Uint8ClampedArray.h>
  774. #include <LibWeb/Bindings/@prototype_class@.h>
  775. #include <LibWeb/Bindings/@wrapper_class@.h>
  776. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  777. #include <LibWeb/Bindings/CommentWrapper.h>
  778. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  779. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  780. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  781. #include <LibWeb/Bindings/DocumentWrapper.h>
  782. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  783. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  784. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  785. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  786. #include <LibWeb/Bindings/ImageDataWrapper.h>
  787. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  788. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  789. #include <LibWeb/Bindings/TextWrapper.h>
  790. #include <LibWeb/Bindings/WindowObject.h>
  791. #include <LibWeb/DOM/Element.h>
  792. #include <LibWeb/DOM/EventListener.h>
  793. #include <LibWeb/DOM/Window.h>
  794. #include <LibWeb/HTML/EventHandler.h>
  795. #include <LibWeb/HTML/HTMLElement.h>
  796. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  797. #include <LibWeb/Origin.h>
  798. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  799. # include <LibWeb/Bindings/@prototype_base_class@.h>
  800. #endif
  801. #if __has_include(<LibWeb/DOM/@name@.h>)
  802. # include <LibWeb/DOM/@name@.h>
  803. #elif __has_include(<LibWeb/HTML/@name@.h>)
  804. # include <LibWeb/HTML/@name@.h>
  805. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  806. # include <LibWeb/UIEvents/@name@.h>
  807. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  808. # include <LibWeb/HighResolutionTime/@name@.h>
  809. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  810. # include <LibWeb/NavigationTiming/@name@.h>
  811. #elif __has_include(<LibWeb/SVG/@name@.h>)
  812. # include <LibWeb/SVG/@name@.h>
  813. #elif __has_include(<LibWeb/XHR/@name@.h>)
  814. # include <LibWeb/XHR/@name@.h>
  815. #endif
  816. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  817. using namespace Web::DOM;
  818. using namespace Web::HTML;
  819. using namespace Web::NavigationTiming;
  820. using namespace Web::XHR;
  821. namespace Web::Bindings {
  822. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  823. : Object(*global_object.object_prototype())
  824. {
  825. )~~~");
  826. if (!interface.parent_name.is_empty()) {
  827. generator.append(R"~~~(
  828. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  829. )~~~");
  830. }
  831. generator.append(R"~~~(
  832. }
  833. @prototype_class@::~@prototype_class@()
  834. {
  835. }
  836. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  837. {
  838. [[maybe_unused]] auto& vm = this->vm();
  839. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;
  840. )~~~");
  841. for (auto& attribute : interface.attributes) {
  842. auto attribute_generator = generator.fork();
  843. attribute_generator.set("attribute.name", attribute.name);
  844. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  845. if (attribute.readonly)
  846. attribute_generator.set("attribute.setter_callback", "nullptr");
  847. else
  848. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  849. attribute_generator.append(R"~~~(
  850. define_native_property("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  851. )~~~");
  852. }
  853. for (auto& constant : interface.constants) {
  854. auto constant_generator = generator.fork();
  855. constant_generator.set("constant.name", constant.name);
  856. constant_generator.set("constant.value", constant.value);
  857. constant_generator.append(R"~~~(
  858. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  859. )~~~");
  860. }
  861. for (auto& function : interface.functions) {
  862. auto function_generator = generator.fork();
  863. function_generator.set("function.name", function.name);
  864. function_generator.set("function.name:snakecase", snake_name(function.name));
  865. function_generator.set("function.length", String::number(function.length()));
  866. function_generator.append(R"~~~(
  867. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  868. )~~~");
  869. }
  870. generator.append(R"~~~(
  871. Object::initialize(global_object);
  872. }
  873. )~~~");
  874. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  875. generator.append(R"~~~(
  876. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  877. {
  878. auto* this_object = vm.this_value(global_object).to_object(global_object);
  879. if (!this_object)
  880. return {};
  881. )~~~");
  882. if (interface.name == "EventTarget") {
  883. generator.append(R"~~~(
  884. if (is<WindowObject>(this_object)) {
  885. return &static_cast<WindowObject*>(this_object)->impl();
  886. }
  887. )~~~");
  888. }
  889. generator.append(R"~~~(
  890. if (!is<@wrapper_class@>(this_object)) {
  891. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  892. return nullptr;
  893. }
  894. return &static_cast<@wrapper_class@*>(this_object)->impl();
  895. }
  896. )~~~");
  897. }
  898. auto generate_to_cpp = [&](auto& parameter, auto& js_name, const auto& js_suffix, auto cpp_name, bool return_void = false, bool legacy_null_to_empty_string = false, bool optional = false) {
  899. auto scoped_generator = generator.fork();
  900. scoped_generator.set("cpp_name", make_input_acceptable_cpp(cpp_name));
  901. scoped_generator.set("js_name", js_name);
  902. scoped_generator.set("js_suffix", js_suffix);
  903. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  904. scoped_generator.set("parameter.type.name", parameter.type.name);
  905. if (return_void)
  906. scoped_generator.set("return_statement", "return;");
  907. else
  908. scoped_generator.set("return_statement", "return {};");
  909. // FIXME: Add support for optional to all types
  910. if (parameter.type.name == "DOMString") {
  911. if (!optional) {
  912. scoped_generator.append(R"~~~(
  913. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  914. if (vm.exception())
  915. @return_statement@
  916. )~~~");
  917. } else {
  918. scoped_generator.append(R"~~~(
  919. String @cpp_name@;
  920. if (!@js_name@@js_suffix@.is_undefined()) {
  921. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  922. if (vm.exception())
  923. @return_statement@
  924. }
  925. )~~~");
  926. }
  927. } else if (parameter.type.name == "EventListener") {
  928. scoped_generator.append(R"~~~(
  929. if (!@js_name@@js_suffix@.is_function()) {
  930. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "Function");
  931. @return_statement@
  932. }
  933. auto @cpp_name@ = adopt(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  934. )~~~");
  935. } else if (is_wrappable_type(parameter.type)) {
  936. scoped_generator.append(R"~~~(
  937. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  938. if (vm.exception())
  939. @return_statement@
  940. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  941. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  942. @return_statement@
  943. }
  944. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  945. )~~~");
  946. } else if (parameter.type.name == "double") {
  947. scoped_generator.append(R"~~~(
  948. auto @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  949. if (vm.exception())
  950. @return_statement@
  951. )~~~");
  952. } else if (parameter.type.name == "boolean") {
  953. scoped_generator.append(R"~~~(
  954. auto @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  955. )~~~");
  956. } else if (parameter.type.name == "unsigned long") {
  957. scoped_generator.append(R"~~~(
  958. auto @cpp_name@ = @js_name@@js_suffix@.to_u32(global_object);
  959. if (vm.exception())
  960. @return_statement@
  961. )~~~");
  962. } else if (parameter.type.name == "EventHandler") {
  963. // x.onfoo = function() { ... }
  964. scoped_generator.append(R"~~~(
  965. HTML::EventHandler @cpp_name@;
  966. if (@js_name@@js_suffix@.is_function()) {
  967. @cpp_name@.callback = JS::make_handle(&@js_name@@js_suffix@.as_function());
  968. } else if (@js_name@@js_suffix@.is_string()) {
  969. @cpp_name@.string = @js_name@@js_suffix@.as_string().string();
  970. } else {
  971. @return_statement@
  972. }
  973. )~~~");
  974. } else {
  975. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  976. ASSERT_NOT_REACHED();
  977. }
  978. };
  979. auto generate_arguments = [&](auto& parameters, auto& arguments_builder, bool return_void = false) {
  980. auto arguments_generator = generator.fork();
  981. Vector<String> parameter_names;
  982. size_t argument_index = 0;
  983. for (auto& parameter : parameters) {
  984. parameter_names.append(make_input_acceptable_cpp(snake_name(parameter.name)));
  985. arguments_generator.set("argument.index", String::number(argument_index));
  986. arguments_generator.append(R"~~~(
  987. auto arg@argument.index@ = vm.argument(@argument.index@);
  988. )~~~");
  989. // FIXME: Parameters can have [LegacyNullToEmptyString] attached.
  990. generate_to_cpp(parameter, "arg", String::number(argument_index), snake_name(parameter.name), return_void, false, parameter.optional);
  991. ++argument_index;
  992. }
  993. arguments_builder.join(", ", parameter_names);
  994. };
  995. auto generate_return_statement = [&](auto& return_type) {
  996. auto scoped_generator = generator.fork();
  997. scoped_generator.set("return_type", return_type.name);
  998. if (return_type.name == "undefined") {
  999. scoped_generator.append(R"~~~(
  1000. return JS::js_undefined();
  1001. )~~~");
  1002. return;
  1003. }
  1004. if (return_type.nullable) {
  1005. if (return_type.name == "DOMString") {
  1006. scoped_generator.append(R"~~~(
  1007. if (retval.is_null())
  1008. return JS::js_null();
  1009. )~~~");
  1010. } else {
  1011. scoped_generator.append(R"~~~(
  1012. if (!retval)
  1013. return JS::js_null();
  1014. )~~~");
  1015. }
  1016. }
  1017. if (return_type.name == "DOMString") {
  1018. scoped_generator.append(R"~~~(
  1019. return JS::js_string(vm, retval);
  1020. )~~~");
  1021. } else if (return_type.name == "ArrayFromVector") {
  1022. // FIXME: Remove this fake type hack once it's no longer needed.
  1023. // Basically once we have NodeList we can throw this out.
  1024. scoped_generator.append(R"~~~(
  1025. auto* new_array = JS::Array::create(global_object);
  1026. for (auto& element : retval)
  1027. new_array->indexed_properties().append(wrap(global_object, element));
  1028. return new_array;
  1029. )~~~");
  1030. } else if (return_type.name == "boolean" || return_type.name == "double" || return_type.name == "long" || return_type.name == "unsigned long") {
  1031. scoped_generator.append(R"~~~(
  1032. return JS::Value(retval);
  1033. )~~~");
  1034. } else if (return_type.name == "short" || return_type.name == "unsigned short") {
  1035. scoped_generator.append(R"~~~(
  1036. return JS::Value((i32)retval);
  1037. )~~~");
  1038. } else if (return_type.name == "Uint8ClampedArray") {
  1039. scoped_generator.append(R"~~~(
  1040. return retval;
  1041. )~~~");
  1042. } else if (return_type.name == "EventHandler") {
  1043. scoped_generator.append(R"~~~(
  1044. return retval.callback.cell();
  1045. )~~~");
  1046. } else {
  1047. scoped_generator.append(R"~~~(
  1048. return wrap(global_object, const_cast<@return_type@&>(*retval));
  1049. )~~~");
  1050. }
  1051. };
  1052. for (auto& attribute : interface.attributes) {
  1053. auto attribute_generator = generator.fork();
  1054. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1055. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1056. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  1057. if (attribute.extended_attributes.contains("Reflect")) {
  1058. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1059. if (attribute_name.is_null())
  1060. attribute_name = attribute.name;
  1061. attribute_name = make_input_acceptable_cpp(attribute_name);
  1062. attribute_generator.set("attribute.reflect_name", attribute_name);
  1063. } else {
  1064. attribute_generator.set("attribute.reflect_name", snake_name(attribute.name));
  1065. }
  1066. attribute_generator.append(R"~~~(
  1067. JS_DEFINE_NATIVE_GETTER(@prototype_class@::@attribute.getter_callback@)
  1068. {
  1069. auto* impl = impl_from(vm, global_object);
  1070. if (!impl)
  1071. return {};
  1072. )~~~");
  1073. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1074. attribute_generator.append(R"~~~(
  1075. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1076. return JS::js_null();
  1077. )~~~");
  1078. }
  1079. if (attribute.extended_attributes.contains("Reflect")) {
  1080. if (attribute.type.name != "boolean") {
  1081. attribute_generator.append(R"~~~(
  1082. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1083. )~~~");
  1084. } else {
  1085. attribute_generator.append(R"~~~(
  1086. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1087. )~~~");
  1088. }
  1089. } else {
  1090. attribute_generator.append(R"~~~(
  1091. auto retval = impl->@attribute.name:snakecase@();
  1092. )~~~");
  1093. }
  1094. generate_return_statement(attribute.type);
  1095. attribute_generator.append(R"~~~(
  1096. }
  1097. )~~~");
  1098. if (!attribute.readonly) {
  1099. attribute_generator.append(R"~~~(
  1100. JS_DEFINE_NATIVE_SETTER(@prototype_class@::@attribute.setter_callback@)
  1101. {
  1102. auto* impl = impl_from(vm, global_object);
  1103. if (!impl)
  1104. return;
  1105. )~~~");
  1106. generate_to_cpp(attribute, "value", "", "cpp_value", true, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1107. if (attribute.extended_attributes.contains("Reflect")) {
  1108. if (attribute.type.name != "boolean") {
  1109. attribute_generator.append(R"~~~(
  1110. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1111. )~~~");
  1112. } else {
  1113. attribute_generator.append(R"~~~(
  1114. if (!cpp_value)
  1115. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1116. else
  1117. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1118. )~~~");
  1119. }
  1120. } else {
  1121. attribute_generator.append(R"~~~(
  1122. impl->set_@attribute.name:snakecase@(cpp_value);
  1123. )~~~");
  1124. }
  1125. attribute_generator.append(R"~~~(
  1126. }
  1127. )~~~");
  1128. }
  1129. }
  1130. // Implementation: Functions
  1131. for (auto& function : interface.functions) {
  1132. auto function_generator = generator.fork();
  1133. function_generator.set("function.name", function.name);
  1134. function_generator.set("function.name:snakecase", snake_name(function.name));
  1135. function_generator.set("function.nargs", String::number(function.length()));
  1136. function_generator.append(R"~~~(
  1137. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@function.name:snakecase@)
  1138. {
  1139. auto* impl = impl_from(vm, global_object);
  1140. if (!impl)
  1141. return {};
  1142. )~~~");
  1143. if (function.length() > 0) {
  1144. if (function.length() == 1) {
  1145. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  1146. function_generator.set(".arg_count_suffix", "");
  1147. } else {
  1148. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  1149. function_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  1150. }
  1151. function_generator.append(R"~~~(
  1152. if (vm.argument_count() < @function.nargs@) {
  1153. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  1154. return {};
  1155. }
  1156. )~~~");
  1157. }
  1158. StringBuilder arguments_builder;
  1159. generate_arguments(function.parameters, arguments_builder);
  1160. function_generator.set(".arguments", arguments_builder.string_view());
  1161. if (function.return_type.name != "undefined") {
  1162. function_generator.append(R"~~~(
  1163. auto retval = impl->@function.name:snakecase@(@.arguments@);
  1164. )~~~");
  1165. } else {
  1166. function_generator.append(R"~~~(
  1167. impl->@function.name:snakecase@(@.arguments@);
  1168. )~~~");
  1169. }
  1170. generate_return_statement(function.return_type);
  1171. function_generator.append(R"~~~(
  1172. }
  1173. )~~~");
  1174. }
  1175. generator.append(R"~~~(
  1176. } // namespace Web::Bindings
  1177. )~~~");
  1178. outln("{}", generator.as_string_view());
  1179. }