WrapperGenerator.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  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", "XHR")) {
  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. #elif __has_include(<LibWeb/XHR/@name@.h>)
  447. # include <LibWeb/XHR/@name@.h>
  448. #endif
  449. )~~~");
  450. if (interface.wrapper_base_class != "Wrapper") {
  451. generator.append(R"~~~(
  452. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  453. )~~~");
  454. }
  455. generator.append(R"~~~(
  456. namespace Web::Bindings {
  457. class @wrapper_class@ : public @wrapper_base_class@ {
  458. JS_OBJECT(@wrapper_class@, @wrapper_base_class@);
  459. public:
  460. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  461. virtual void initialize(JS::GlobalObject&) override;
  462. virtual ~@wrapper_class@() override;
  463. )~~~");
  464. if (interface.wrapper_base_class == "Wrapper") {
  465. generator.append(R"~~~(
  466. @fully_qualified_name@& impl() { return *m_impl; }
  467. const @fully_qualified_name@& impl() const { return *m_impl; }
  468. )~~~");
  469. } else {
  470. generator.append(R"~~~(
  471. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  472. const @fully_qualified_name@& impl() const { return static_cast<const @fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  473. )~~~");
  474. }
  475. generator.append(R"~~~(
  476. private:
  477. )~~~");
  478. if (interface.wrapper_base_class == "Wrapper") {
  479. generator.append(R"~~~(
  480. NonnullRefPtr<@fully_qualified_name@> m_impl;
  481. )~~~");
  482. }
  483. generator.append(R"~~~(
  484. };
  485. )~~~");
  486. if (should_emit_wrapper_factory(interface)) {
  487. generator.append(R"~~~(
  488. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  489. )~~~");
  490. }
  491. generator.append(R"~~~(
  492. } // namespace Web::Bindings
  493. )~~~");
  494. outln("{}", generator.as_string_view());
  495. }
  496. void generate_implementation(const IDL::Interface& interface)
  497. {
  498. StringBuilder builder;
  499. SourceGenerator generator { builder };
  500. generator.set("name", interface.name);
  501. generator.set("wrapper_class", interface.wrapper_class);
  502. generator.set("wrapper_base_class", interface.wrapper_base_class);
  503. generator.set("prototype_class", interface.prototype_class);
  504. generator.set("fully_qualified_name", interface.fully_qualified_name);
  505. generator.append(R"~~~(
  506. #include <AK/FlyString.h>
  507. #include <LibJS/Runtime/Array.h>
  508. #include <LibJS/Runtime/Error.h>
  509. #include <LibJS/Runtime/Function.h>
  510. #include <LibJS/Runtime/GlobalObject.h>
  511. #include <LibJS/Runtime/Uint8ClampedArray.h>
  512. #include <LibJS/Runtime/Value.h>
  513. #include <LibWeb/Bindings/@prototype_class@.h>
  514. #include <LibWeb/Bindings/@wrapper_class@.h>
  515. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  516. #include <LibWeb/Bindings/CommentWrapper.h>
  517. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  518. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  519. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  520. #include <LibWeb/Bindings/DocumentWrapper.h>
  521. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  522. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  523. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  524. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  525. #include <LibWeb/Bindings/ImageDataWrapper.h>
  526. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  527. #include <LibWeb/Bindings/TextWrapper.h>
  528. #include <LibWeb/Bindings/WindowObject.h>
  529. #include <LibWeb/DOM/Element.h>
  530. #include <LibWeb/DOM/EventListener.h>
  531. #include <LibWeb/HTML/HTMLElement.h>
  532. #include <LibWeb/Origin.h>
  533. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  534. using namespace Web::DOM;
  535. using namespace Web::HTML;
  536. namespace Web::Bindings {
  537. )~~~");
  538. if (interface.wrapper_base_class == "Wrapper") {
  539. generator.append(R"~~~(
  540. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  541. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  542. , m_impl(impl)
  543. {
  544. }
  545. )~~~");
  546. } else {
  547. generator.append(R"~~~(
  548. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  549. : @wrapper_base_class@(global_object, impl)
  550. {
  551. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  552. }
  553. )~~~");
  554. }
  555. generator.append(R"~~~(
  556. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  557. {
  558. @wrapper_base_class@::initialize(global_object);
  559. }
  560. @wrapper_class@::~@wrapper_class@()
  561. {
  562. }
  563. )~~~");
  564. if (should_emit_wrapper_factory(interface)) {
  565. generator.append(R"~~~(
  566. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  567. {
  568. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  569. }
  570. )~~~");
  571. }
  572. generator.append(R"~~~(
  573. } // namespace Web::Bindings
  574. )~~~");
  575. outln("{}", generator.as_string_view());
  576. }
  577. static void generate_constructor_header(const IDL::Interface& interface)
  578. {
  579. StringBuilder builder;
  580. SourceGenerator generator { builder };
  581. generator.set("name", interface.name);
  582. generator.set("fully_qualified_name", interface.fully_qualified_name);
  583. generator.set("constructor_class", interface.constructor_class);
  584. generator.set("constructor_class:snakecase", snake_name(interface.constructor_class));
  585. generator.append(R"~~~(
  586. #pragma once
  587. #include <LibJS/Runtime/NativeFunction.h>
  588. namespace Web::Bindings {
  589. class @constructor_class@ : public JS::NativeFunction {
  590. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  591. public:
  592. explicit @constructor_class@(JS::GlobalObject&);
  593. virtual void initialize(JS::GlobalObject&) override;
  594. virtual ~@constructor_class@() override;
  595. virtual JS::Value call() override;
  596. virtual JS::Value construct(JS::Function& new_target) override;
  597. private:
  598. virtual bool has_constructor() const override { return true; }
  599. };
  600. } // namespace Web::Bindings
  601. )~~~");
  602. outln("{}", generator.as_string_view());
  603. }
  604. void generate_constructor_implementation(const IDL::Interface& interface)
  605. {
  606. StringBuilder builder;
  607. SourceGenerator generator { builder };
  608. generator.set("name", interface.name);
  609. generator.set("prototype_class", interface.prototype_class);
  610. generator.set("wrapper_class", interface.wrapper_class);
  611. generator.set("constructor_class", interface.constructor_class);
  612. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  613. generator.set("fully_qualified_name", interface.fully_qualified_name);
  614. generator.append(R"~~~(
  615. #include <LibJS/Heap/Heap.h>
  616. #include <LibJS/Runtime/GlobalObject.h>
  617. #include <LibWeb/Bindings/@constructor_class@.h>
  618. #include <LibWeb/Bindings/@prototype_class@.h>
  619. #include <LibWeb/Bindings/@wrapper_class@.h>
  620. #include <LibWeb/Bindings/WindowObject.h>
  621. #if __has_include(<LibWeb/DOM/@name@.h>)
  622. # include <LibWeb/DOM/@name@.h>
  623. #elif __has_include(<LibWeb/HTML/@name@.h>)
  624. # include <LibWeb/HTML/@name@.h>
  625. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  626. # include <LibWeb/UIEvents/@name@.h>
  627. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  628. # include <LibWeb/HighResolutionTime/@name@.h>
  629. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  630. # include <LibWeb/NavigationTiming/@name@.h>
  631. #elif __has_include(<LibWeb/SVG/@name@.h>)
  632. # include <LibWeb/SVG/@name@.h>
  633. #elif __has_include(<LibWeb/XHR/@name@.h>)
  634. # include <LibWeb/XHR/@name@.h>
  635. #endif
  636. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  637. using namespace Web::DOM;
  638. using namespace Web::HTML;
  639. namespace Web::Bindings {
  640. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  641. : NativeFunction(*global_object.function_prototype())
  642. {
  643. }
  644. @constructor_class@::~@constructor_class@()
  645. {
  646. }
  647. JS::Value @constructor_class@::call()
  648. {
  649. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  650. return {};
  651. }
  652. JS::Value @constructor_class@::construct(Function&)
  653. {
  654. return {};
  655. #if 0
  656. // FIXME: It would be cool to construct stuff!
  657. auto& window = static_cast<WindowObject&>(global_object());
  658. return heap().allocate<@wrapper_class@>(window, window, @fully_qualified_name@::create(window.impl()));
  659. #endif
  660. }
  661. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  662. {
  663. auto& vm = this->vm();
  664. auto& window = static_cast<WindowObject&>(global_object);
  665. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  666. NativeFunction::initialize(global_object);
  667. define_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  668. define_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
  669. )~~~");
  670. for (auto& constant : interface.constants) {
  671. auto constant_generator = generator.fork();
  672. constant_generator.set("constant.name", constant.name);
  673. constant_generator.set("constant.value", constant.value);
  674. constant_generator.append(R"~~~(
  675. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  676. )~~~");
  677. }
  678. generator.append(R"~~~(
  679. }
  680. } // namespace Web::Bindings
  681. )~~~");
  682. outln("{}", generator.as_string_view());
  683. }
  684. static void generate_prototype_header(const IDL::Interface& interface)
  685. {
  686. StringBuilder builder;
  687. SourceGenerator generator { builder };
  688. generator.set("name", interface.name);
  689. generator.set("fully_qualified_name", interface.fully_qualified_name);
  690. generator.set("prototype_class", interface.prototype_class);
  691. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  692. generator.append(R"~~~(
  693. #pragma once
  694. #include <LibJS/Runtime/Object.h>
  695. namespace Web::Bindings {
  696. class @prototype_class@ : public JS::Object {
  697. JS_OBJECT(@prototype_class@, JS::Object);
  698. public:
  699. explicit @prototype_class@(JS::GlobalObject&);
  700. virtual void initialize(JS::GlobalObject&) override;
  701. virtual ~@prototype_class@() override;
  702. private:
  703. )~~~");
  704. for (auto& function : interface.functions) {
  705. auto function_generator = generator.fork();
  706. function_generator.set("function.name:snakecase", snake_name(function.name));
  707. function_generator.append(R"~~~(
  708. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  709. )~~~");
  710. }
  711. for (auto& attribute : interface.attributes) {
  712. auto attribute_generator = generator.fork();
  713. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  714. attribute_generator.append(R"~~~(
  715. JS_DECLARE_NATIVE_GETTER(@attribute.name:snakecase@_getter);
  716. )~~~");
  717. if (!attribute.readonly) {
  718. attribute_generator.append(R"~~~(
  719. JS_DECLARE_NATIVE_SETTER(@attribute.name:snakecase@_setter);
  720. )~~~");
  721. }
  722. }
  723. generator.append(R"~~~(
  724. };
  725. } // namespace Web::Bindings
  726. )~~~");
  727. outln("{}", generator.as_string_view());
  728. }
  729. void generate_prototype_implementation(const IDL::Interface& interface)
  730. {
  731. StringBuilder builder;
  732. SourceGenerator generator { builder };
  733. generator.set("name", interface.name);
  734. generator.set("parent_name", interface.parent_name);
  735. generator.set("prototype_class", interface.prototype_class);
  736. generator.set("prototype_base_class", interface.prototype_base_class);
  737. generator.set("wrapper_class", interface.wrapper_class);
  738. generator.set("constructor_class", interface.constructor_class);
  739. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  740. generator.set("fully_qualified_name", interface.fully_qualified_name);
  741. generator.append(R"~~~(
  742. #include <AK/Function.h>
  743. #include <LibJS/Runtime/Array.h>
  744. #include <LibJS/Runtime/Error.h>
  745. #include <LibJS/Runtime/Function.h>
  746. #include <LibJS/Runtime/GlobalObject.h>
  747. #include <LibJS/Runtime/Uint8ClampedArray.h>
  748. #include <LibWeb/Bindings/@prototype_class@.h>
  749. #include <LibWeb/Bindings/@wrapper_class@.h>
  750. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  751. #include <LibWeb/Bindings/CommentWrapper.h>
  752. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  753. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  754. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  755. #include <LibWeb/Bindings/DocumentWrapper.h>
  756. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  757. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  758. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  759. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  760. #include <LibWeb/Bindings/ImageDataWrapper.h>
  761. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  762. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  763. #include <LibWeb/Bindings/TextWrapper.h>
  764. #include <LibWeb/Bindings/WindowObject.h>
  765. #include <LibWeb/DOM/Element.h>
  766. #include <LibWeb/DOM/EventListener.h>
  767. #include <LibWeb/DOM/Window.h>
  768. #include <LibWeb/HTML/HTMLElement.h>
  769. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  770. #include <LibWeb/Origin.h>
  771. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  772. # include <LibWeb/Bindings/@prototype_base_class@.h>
  773. #endif
  774. #if __has_include(<LibWeb/DOM/@name@.h>)
  775. # include <LibWeb/DOM/@name@.h>
  776. #elif __has_include(<LibWeb/HTML/@name@.h>)
  777. # include <LibWeb/HTML/@name@.h>
  778. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  779. # include <LibWeb/UIEvents/@name@.h>
  780. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  781. # include <LibWeb/HighResolutionTime/@name@.h>
  782. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  783. # include <LibWeb/NavigationTiming/@name@.h>
  784. #elif __has_include(<LibWeb/SVG/@name@.h>)
  785. # include <LibWeb/SVG/@name@.h>
  786. #elif __has_include(<LibWeb/XHR/@name@.h>)
  787. # include <LibWeb/XHR/@name@.h>
  788. #endif
  789. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  790. using namespace Web::DOM;
  791. using namespace Web::HTML;
  792. using namespace Web::NavigationTiming;
  793. using namespace Web::XHR;
  794. namespace Web::Bindings {
  795. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  796. : Object(*global_object.object_prototype())
  797. {
  798. )~~~");
  799. if (!interface.parent_name.is_empty()) {
  800. generator.append(R"~~~(
  801. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  802. )~~~");
  803. }
  804. generator.append(R"~~~(
  805. }
  806. @prototype_class@::~@prototype_class@()
  807. {
  808. }
  809. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  810. {
  811. [[maybe_unused]] auto& vm = this->vm();
  812. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;
  813. )~~~");
  814. for (auto& attribute : interface.attributes) {
  815. auto attribute_generator = generator.fork();
  816. attribute_generator.set("attribute.name", attribute.name);
  817. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  818. if (attribute.readonly)
  819. attribute_generator.set("attribute.setter_callback", "nullptr");
  820. else
  821. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  822. attribute_generator.append(R"~~~(
  823. define_native_property("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  824. )~~~");
  825. }
  826. for (auto& constant : interface.constants) {
  827. auto constant_generator = generator.fork();
  828. constant_generator.set("constant.name", constant.name);
  829. constant_generator.set("constant.value", constant.value);
  830. constant_generator.append(R"~~~(
  831. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  832. )~~~");
  833. }
  834. for (auto& function : interface.functions) {
  835. auto function_generator = generator.fork();
  836. function_generator.set("function.name", function.name);
  837. function_generator.set("function.name:snakecase", snake_name(function.name));
  838. function_generator.set("function.name:length", String::number(function.name.length()));
  839. function_generator.append(R"~~~(
  840. define_native_function("@function.name@", @function.name:snakecase@, @function.name:length@, default_attributes);
  841. )~~~");
  842. }
  843. generator.append(R"~~~(
  844. Object::initialize(global_object);
  845. }
  846. )~~~");
  847. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  848. generator.append(R"~~~(
  849. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  850. {
  851. auto* this_object = vm.this_value(global_object).to_object(global_object);
  852. if (!this_object)
  853. return {};
  854. )~~~");
  855. if (interface.name == "EventTarget") {
  856. generator.append(R"~~~(
  857. if (is<WindowObject>(this_object)) {
  858. return &static_cast<WindowObject*>(this_object)->impl();
  859. }
  860. )~~~");
  861. }
  862. generator.append(R"~~~(
  863. if (!is<@wrapper_class@>(this_object)) {
  864. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  865. return nullptr;
  866. }
  867. return &static_cast<@wrapper_class@*>(this_object)->impl();
  868. }
  869. )~~~");
  870. }
  871. 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) {
  872. auto scoped_generator = generator.fork();
  873. scoped_generator.set("cpp_name", cpp_name);
  874. scoped_generator.set("js_name", js_name);
  875. scoped_generator.set("js_suffix", js_suffix);
  876. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  877. scoped_generator.set("parameter.type.name", parameter.type.name);
  878. if (return_void)
  879. scoped_generator.set("return_statement", "return;");
  880. else
  881. scoped_generator.set("return_statement", "return {};");
  882. // FIXME: Add support for optional to all types
  883. if (parameter.type.name == "DOMString") {
  884. if (!optional) {
  885. scoped_generator.append(R"~~~(
  886. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  887. if (vm.exception())
  888. @return_statement@
  889. )~~~");
  890. } else {
  891. scoped_generator.append(R"~~~(
  892. String @cpp_name@;
  893. if (!@js_name@@js_suffix@.is_undefined()) {
  894. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  895. if (vm.exception())
  896. @return_statement@
  897. }
  898. )~~~");
  899. }
  900. } else if (parameter.type.name == "EventListener") {
  901. scoped_generator.append(R"~~~(
  902. if (!@js_name@@js_suffix@.is_function()) {
  903. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "Function");
  904. @return_statement@
  905. }
  906. auto @cpp_name@ = adopt(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  907. )~~~");
  908. } else if (is_wrappable_type(parameter.type)) {
  909. scoped_generator.append(R"~~~(
  910. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  911. if (vm.exception())
  912. @return_statement@
  913. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  914. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  915. @return_statement@
  916. }
  917. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  918. )~~~");
  919. } else if (parameter.type.name == "double") {
  920. scoped_generator.append(R"~~~(
  921. auto @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  922. if (vm.exception())
  923. @return_statement@
  924. )~~~");
  925. } else if (parameter.type.name == "boolean") {
  926. scoped_generator.append(R"~~~(
  927. auto @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  928. )~~~");
  929. } else {
  930. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  931. ASSERT_NOT_REACHED();
  932. }
  933. };
  934. auto generate_arguments = [&](auto& parameters, auto& arguments_builder, bool return_void = false) {
  935. auto arguments_generator = generator.fork();
  936. Vector<String> parameter_names;
  937. size_t argument_index = 0;
  938. for (auto& parameter : parameters) {
  939. parameter_names.append(snake_name(parameter.name));
  940. arguments_generator.set("argument.index", String::number(argument_index));
  941. arguments_generator.append(R"~~~(
  942. auto arg@argument.index@ = vm.argument(@argument.index@);
  943. )~~~");
  944. // FIXME: Parameters can have [LegacyNullToEmptyString] attached.
  945. generate_to_cpp(parameter, "arg", String::number(argument_index), snake_name(parameter.name), return_void, false, parameter.optional);
  946. ++argument_index;
  947. }
  948. arguments_builder.join(", ", parameter_names);
  949. };
  950. auto generate_return_statement = [&](auto& return_type) {
  951. auto scoped_generator = generator.fork();
  952. scoped_generator.set("return_type", return_type.name);
  953. if (return_type.name == "undefined") {
  954. scoped_generator.append(R"~~~(
  955. return JS::js_undefined();
  956. )~~~");
  957. return;
  958. }
  959. if (return_type.nullable) {
  960. if (return_type.name == "DOMString") {
  961. scoped_generator.append(R"~~~(
  962. if (retval.is_null())
  963. return JS::js_null();
  964. )~~~");
  965. } else {
  966. scoped_generator.append(R"~~~(
  967. if (!retval)
  968. return JS::js_null();
  969. )~~~");
  970. }
  971. }
  972. if (return_type.name == "DOMString") {
  973. scoped_generator.append(R"~~~(
  974. return JS::js_string(vm, retval);
  975. )~~~");
  976. } else if (return_type.name == "ArrayFromVector") {
  977. // FIXME: Remove this fake type hack once it's no longer needed.
  978. // Basically once we have NodeList we can throw this out.
  979. scoped_generator.append(R"~~~(
  980. auto* new_array = JS::Array::create(global_object);
  981. for (auto& element : retval)
  982. new_array->indexed_properties().append(wrap(global_object, element));
  983. return new_array;
  984. )~~~");
  985. } else if (return_type.name == "boolean" || return_type.name == "double" || return_type.name == "long") {
  986. scoped_generator.append(R"~~~(
  987. return JS::Value(retval);
  988. )~~~");
  989. } else if (return_type.name == "short") {
  990. scoped_generator.append(R"~~~(
  991. return JS::Value((i32)retval);
  992. )~~~");
  993. } else if (return_type.name == "Uint8ClampedArray") {
  994. scoped_generator.append(R"~~~(
  995. return retval;
  996. )~~~");
  997. } else {
  998. scoped_generator.append(R"~~~(
  999. return wrap(global_object, const_cast<@return_type@&>(*retval));
  1000. )~~~");
  1001. }
  1002. };
  1003. for (auto& attribute : interface.attributes) {
  1004. auto attribute_generator = generator.fork();
  1005. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1006. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1007. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  1008. if (attribute.extended_attributes.contains("Reflect")) {
  1009. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1010. if (attribute_name.is_null())
  1011. attribute_name = attribute.name;
  1012. attribute_name = make_input_acceptable_cpp(attribute_name);
  1013. attribute_generator.set("attribute.reflect_name", attribute_name);
  1014. } else {
  1015. attribute_generator.set("attribute.reflect_name", snake_name(attribute.name));
  1016. }
  1017. attribute_generator.append(R"~~~(
  1018. JS_DEFINE_NATIVE_GETTER(@prototype_class@::@attribute.getter_callback@)
  1019. {
  1020. auto* impl = impl_from(vm, global_object);
  1021. if (!impl)
  1022. return {};
  1023. )~~~");
  1024. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1025. attribute_generator.append(R"~~~(
  1026. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1027. return JS::js_null();
  1028. )~~~");
  1029. }
  1030. if (attribute.extended_attributes.contains("Reflect")) {
  1031. if (attribute.type.name != "boolean") {
  1032. attribute_generator.append(R"~~~(
  1033. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1034. )~~~");
  1035. } else {
  1036. attribute_generator.append(R"~~~(
  1037. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1038. )~~~");
  1039. }
  1040. } else {
  1041. attribute_generator.append(R"~~~(
  1042. auto retval = impl->@attribute.name:snakecase@();
  1043. )~~~");
  1044. }
  1045. generate_return_statement(attribute.type);
  1046. attribute_generator.append(R"~~~(
  1047. }
  1048. )~~~");
  1049. if (!attribute.readonly) {
  1050. attribute_generator.append(R"~~~(
  1051. JS_DEFINE_NATIVE_SETTER(@prototype_class@::@attribute.setter_callback@)
  1052. {
  1053. auto* impl = impl_from(vm, global_object);
  1054. if (!impl)
  1055. return;
  1056. )~~~");
  1057. generate_to_cpp(attribute, "value", "", "cpp_value", true, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1058. if (attribute.extended_attributes.contains("Reflect")) {
  1059. if (attribute.type.name != "boolean") {
  1060. attribute_generator.append(R"~~~(
  1061. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1062. )~~~");
  1063. } else {
  1064. attribute_generator.append(R"~~~(
  1065. if (!cpp_value)
  1066. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1067. else
  1068. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1069. )~~~");
  1070. }
  1071. } else {
  1072. attribute_generator.append(R"~~~(
  1073. impl->set_@attribute.name:snakecase@(cpp_value);
  1074. )~~~");
  1075. }
  1076. attribute_generator.append(R"~~~(
  1077. }
  1078. )~~~");
  1079. }
  1080. }
  1081. // Implementation: Functions
  1082. for (auto& function : interface.functions) {
  1083. auto function_generator = generator.fork();
  1084. function_generator.set("function.name", function.name);
  1085. function_generator.set("function.name:snakecase", snake_name(function.name));
  1086. function_generator.set("function.nargs", String::number(function.length()));
  1087. function_generator.append(R"~~~(
  1088. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@function.name:snakecase@)
  1089. {
  1090. auto* impl = impl_from(vm, global_object);
  1091. if (!impl)
  1092. return {};
  1093. )~~~");
  1094. if (function.length() > 0) {
  1095. if (function.length() == 1) {
  1096. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  1097. function_generator.set(".arg_count_suffix", "");
  1098. } else {
  1099. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  1100. function_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  1101. }
  1102. function_generator.append(R"~~~(
  1103. if (vm.argument_count() < @function.nargs@) {
  1104. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  1105. return {};
  1106. }
  1107. )~~~");
  1108. }
  1109. StringBuilder arguments_builder;
  1110. generate_arguments(function.parameters, arguments_builder);
  1111. function_generator.set(".arguments", arguments_builder.string_view());
  1112. if (function.return_type.name != "undefined") {
  1113. function_generator.append(R"~~~(
  1114. auto retval = impl->@function.name:snakecase@(@.arguments@);
  1115. )~~~");
  1116. } else {
  1117. function_generator.append(R"~~~(
  1118. impl->@function.name:snakecase@(@.arguments@);
  1119. )~~~");
  1120. }
  1121. generate_return_statement(function.return_type);
  1122. function_generator.append(R"~~~(
  1123. }
  1124. )~~~");
  1125. }
  1126. generator.append(R"~~~(
  1127. } // namespace Web::Bindings
  1128. )~~~");
  1129. outln("{}", generator.as_string_view());
  1130. }