WrapperGenerator.cpp 44 KB

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