WrapperGenerator.cpp 44 KB

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