WrapperGenerator.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. /*
  2. * Copyright (c) 2020, 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/GenericLexer.h>
  28. #include <AK/HashMap.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/SourceGenerator.h>
  31. #include <AK/StringBuilder.h>
  32. #include <LibCore/ArgsParser.h>
  33. #include <LibCore/File.h>
  34. #include <ctype.h>
  35. static String snake_name(const StringView& title_name)
  36. {
  37. StringBuilder builder;
  38. bool first = true;
  39. bool last_was_uppercase = false;
  40. for (auto ch : title_name) {
  41. if (isupper(ch)) {
  42. if (!first && !last_was_uppercase)
  43. builder.append('_');
  44. builder.append(tolower(ch));
  45. } else {
  46. builder.append(ch);
  47. }
  48. first = false;
  49. last_was_uppercase = isupper(ch);
  50. }
  51. return builder.to_string();
  52. }
  53. static String make_input_acceptable_cpp(const String& input)
  54. {
  55. if (input.is_one_of("class", "template", "for", "default", "char")) {
  56. StringBuilder builder;
  57. builder.append(input);
  58. builder.append('_');
  59. return builder.to_string();
  60. }
  61. String input_without_dashes = input;
  62. input_without_dashes.replace("-", "_");
  63. return input_without_dashes;
  64. }
  65. static void report_parsing_error(StringView message, StringView filename, StringView input, size_t offset)
  66. {
  67. // FIXME: Spaghetti code ahead.
  68. size_t lineno = 1;
  69. size_t colno = 1;
  70. size_t start_line = 0;
  71. size_t line_length = 0;
  72. for (size_t index = 0; index < input.length(); ++index) {
  73. if (offset == index)
  74. colno = index - start_line + 1;
  75. if (input[index] == '\n') {
  76. if (index >= offset)
  77. break;
  78. start_line = index + 1;
  79. line_length = 0;
  80. ++lineno;
  81. } else {
  82. ++line_length;
  83. }
  84. }
  85. StringBuilder error_message;
  86. error_message.appendff("{}\n", input.substring_view(start_line, line_length));
  87. for (size_t i = 0; i < colno - 1; ++i)
  88. error_message.append(' ');
  89. error_message.append("\033[1;31m^\n");
  90. error_message.appendff("{}:{}: error: {}\033[0m\n", filename, lineno, message);
  91. warnln("{}", error_message.string_view());
  92. exit(EXIT_FAILURE);
  93. }
  94. namespace IDL {
  95. struct Type {
  96. String name;
  97. bool nullable { false };
  98. };
  99. struct Parameter {
  100. Type type;
  101. String name;
  102. bool optional { false };
  103. };
  104. struct Function {
  105. Type return_type;
  106. String name;
  107. Vector<Parameter> parameters;
  108. HashMap<String, String> extended_attributes;
  109. size_t length() const
  110. {
  111. // FIXME: This seems to produce a length that is way over what it's supposed to be.
  112. // For example, getElementsByTagName has its length set to 20 when it should be 1.
  113. size_t length = 0;
  114. for (auto& parameter : parameters) {
  115. if (!parameter.optional)
  116. length++;
  117. }
  118. return length;
  119. }
  120. };
  121. struct Attribute {
  122. bool readonly { false };
  123. bool unsigned_ { false };
  124. Type type;
  125. String name;
  126. HashMap<String, String> extended_attributes;
  127. // Added for convenience after parsing
  128. String getter_callback_name;
  129. String setter_callback_name;
  130. };
  131. struct Interface {
  132. String name;
  133. String parent_name;
  134. Vector<Attribute> attributes;
  135. Vector<Function> functions;
  136. // Added for convenience after parsing
  137. String wrapper_class;
  138. String wrapper_base_class;
  139. String fully_qualified_name;
  140. };
  141. static OwnPtr<Interface> parse_interface(StringView filename, const StringView& input)
  142. {
  143. auto interface = make<Interface>();
  144. GenericLexer lexer(input);
  145. auto assert_specific = [&](char ch) {
  146. if (!lexer.consume_specific(ch))
  147. report_parsing_error(String::formatted("expected '{}'", ch), filename, input, lexer.tell());
  148. };
  149. auto consume_whitespace = [&] {
  150. bool consumed = true;
  151. while (consumed) {
  152. consumed = lexer.consume_while([](char ch) { return isspace(ch); }).length() > 0;
  153. if (lexer.consume_specific("//")) {
  154. lexer.consume_until('\n');
  155. consumed = true;
  156. }
  157. }
  158. };
  159. auto assert_string = [&](const StringView& expected) {
  160. if (!lexer.consume_specific(expected))
  161. report_parsing_error(String::formatted("expected '{}'", expected), filename, input, lexer.tell());
  162. };
  163. assert_string("interface");
  164. consume_whitespace();
  165. interface->name = lexer.consume_until([](auto ch) { return isspace(ch); });
  166. consume_whitespace();
  167. if (lexer.consume_specific(':')) {
  168. consume_whitespace();
  169. interface->parent_name = lexer.consume_until([](auto ch) { return isspace(ch); });
  170. consume_whitespace();
  171. }
  172. assert_specific('{');
  173. auto parse_type = [&] {
  174. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '?'; });
  175. auto nullable = lexer.consume_specific('?');
  176. return Type { name, nullable };
  177. };
  178. auto parse_attribute = [&](HashMap<String, String>& extended_attributes) {
  179. bool readonly = lexer.consume_specific("readonly");
  180. if (readonly)
  181. consume_whitespace();
  182. if (lexer.consume_specific("attribute"))
  183. consume_whitespace();
  184. bool unsigned_ = lexer.consume_specific("unsigned");
  185. if (unsigned_)
  186. consume_whitespace();
  187. auto type = parse_type();
  188. consume_whitespace();
  189. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ';'; });
  190. consume_whitespace();
  191. assert_specific(';');
  192. Attribute attribute;
  193. attribute.readonly = readonly;
  194. attribute.unsigned_ = unsigned_;
  195. attribute.type = type;
  196. attribute.name = name;
  197. attribute.getter_callback_name = String::format("%s_getter", snake_name(attribute.name).characters());
  198. attribute.setter_callback_name = String::format("%s_setter", snake_name(attribute.name).characters());
  199. attribute.extended_attributes = move(extended_attributes);
  200. interface->attributes.append(move(attribute));
  201. };
  202. auto parse_function = [&](HashMap<String, String>& extended_attributes) {
  203. auto return_type = parse_type();
  204. consume_whitespace();
  205. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '('; });
  206. consume_whitespace();
  207. assert_specific('(');
  208. Vector<Parameter> parameters;
  209. for (;;) {
  210. if (lexer.consume_specific(')'))
  211. break;
  212. bool optional = lexer.consume_specific("optional");
  213. if (optional)
  214. consume_whitespace();
  215. auto type = parse_type();
  216. consume_whitespace();
  217. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ',' || ch == ')'; });
  218. parameters.append({ move(type), move(name), optional });
  219. if (lexer.consume_specific(')'))
  220. break;
  221. assert_specific(',');
  222. consume_whitespace();
  223. }
  224. consume_whitespace();
  225. assert_specific(';');
  226. interface->functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  227. };
  228. auto parse_extended_attributes = [&] {
  229. HashMap<String, String> extended_attributes;
  230. for (;;) {
  231. consume_whitespace();
  232. if (lexer.consume_specific(']'))
  233. break;
  234. auto name = lexer.consume_until([](auto ch) { return ch == ']' || ch == '=' || ch == ','; });
  235. if (lexer.consume_specific('=')) {
  236. auto value = lexer.consume_until([](auto ch) { return ch == ']' || ch == ','; });
  237. extended_attributes.set(name, value);
  238. } else {
  239. extended_attributes.set(name, {});
  240. }
  241. lexer.consume_specific(',');
  242. }
  243. consume_whitespace();
  244. return extended_attributes;
  245. };
  246. for (;;) {
  247. HashMap<String, String> extended_attributes;
  248. consume_whitespace();
  249. if (lexer.consume_specific('}'))
  250. break;
  251. if (lexer.consume_specific('[')) {
  252. extended_attributes = parse_extended_attributes();
  253. }
  254. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  255. parse_attribute(extended_attributes);
  256. continue;
  257. }
  258. parse_function(extended_attributes);
  259. }
  260. interface->wrapper_class = String::format("%sWrapper", interface->name.characters());
  261. interface->wrapper_base_class = String::format("%sWrapper", interface->parent_name.is_empty() ? "" : interface->parent_name.characters());
  262. return interface;
  263. }
  264. }
  265. static void generate_header(const IDL::Interface&);
  266. static void generate_implementation(const IDL::Interface&);
  267. int main(int argc, char** argv)
  268. {
  269. Core::ArgsParser args_parser;
  270. const char* path = nullptr;
  271. bool header_mode = false;
  272. bool implementation_mode = false;
  273. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  274. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  275. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  276. args_parser.parse(argc, argv);
  277. auto file_or_error = Core::File::open(path, Core::IODevice::ReadOnly);
  278. if (file_or_error.is_error()) {
  279. fprintf(stderr, "Cannot open %s\n", path);
  280. return 1;
  281. }
  282. LexicalPath lexical_path(path);
  283. auto namespace_ = lexical_path.parts().at(lexical_path.parts().size() - 2);
  284. auto data = file_or_error.value()->read_all();
  285. auto interface = IDL::parse_interface(path, data);
  286. if (!interface) {
  287. warnln("Cannot parse {}", path);
  288. return 1;
  289. }
  290. if (namespace_.is_one_of("DOM", "HTML", "UIEvents", "HighResolutionTime", "SVG")) {
  291. StringBuilder builder;
  292. builder.append(namespace_);
  293. builder.append("::");
  294. builder.append(interface->name);
  295. interface->fully_qualified_name = builder.to_string();
  296. } else {
  297. interface->fully_qualified_name = interface->name;
  298. }
  299. #if 0
  300. dbg() << "Attributes:";
  301. for (auto& attribute : interface->attributes) {
  302. dbg() << " " << (attribute.readonly ? "Readonly " : "")
  303. << attribute.type.name << (attribute.type.nullable ? "?" : "")
  304. << " " << attribute.name;
  305. }
  306. dbg() << "Functions:";
  307. for (auto& function : interface->functions) {
  308. dbg() << " " << function.return_type.name << (function.return_type.nullable ? "?" : "")
  309. << " " << function.name;
  310. for (auto& parameter : function.parameters) {
  311. dbg() << " " << parameter.type.name << (parameter.type.nullable ? "?" : "") << " " << parameter.name;
  312. }
  313. }
  314. #endif
  315. if (header_mode)
  316. generate_header(*interface);
  317. if (implementation_mode)
  318. generate_implementation(*interface);
  319. return 0;
  320. }
  321. static bool should_emit_wrapper_factory(const IDL::Interface& interface)
  322. {
  323. // FIXME: This is very hackish.
  324. if (interface.name == "Event")
  325. return false;
  326. if (interface.name == "EventTarget")
  327. return false;
  328. if (interface.name == "Node")
  329. return false;
  330. if (interface.name == "Text")
  331. return false;
  332. if (interface.name == "Document")
  333. return false;
  334. if (interface.name == "DocumentType")
  335. return false;
  336. if (interface.name.ends_with("Element"))
  337. return false;
  338. return true;
  339. }
  340. static bool is_wrappable_type(const IDL::Type& type)
  341. {
  342. if (type.name == "Node")
  343. return true;
  344. if (type.name == "Document")
  345. return true;
  346. if (type.name == "Text")
  347. return true;
  348. if (type.name == "DocumentType")
  349. return true;
  350. if (type.name.ends_with("Element"))
  351. return true;
  352. if (type.name == "ImageData")
  353. return true;
  354. return false;
  355. }
  356. static void generate_header(const IDL::Interface& interface)
  357. {
  358. StringBuilder builder;
  359. SourceGenerator generator { builder };
  360. generator.set("name", interface.name);
  361. generator.set("fully_qualified_name", interface.fully_qualified_name);
  362. generator.set("wrapper_base_class", interface.wrapper_base_class);
  363. generator.set("wrapper_class", interface.wrapper_class);
  364. generator.set("wrapper_class:snakecase", snake_name(interface.wrapper_class));
  365. generator.append(R"~~~(
  366. #pragma once
  367. #include <LibWeb/Bindings/Wrapper.h>
  368. // FIXME: This is very strange.
  369. #if __has_include(<LibWeb/DOM/@name@.h>)
  370. # include <LibWeb/DOM/@name@.h>
  371. #elif __has_include(<LibWeb/HTML/@name@.h>)
  372. # include <LibWeb/HTML/@name@.h>
  373. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  374. # include <LibWeb/UIEvents/@name@.h>
  375. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  376. # include <LibWeb/HighResolutionTime/@name@.h>
  377. #elif __has_include(<LibWeb/SVG/@name@.h>)
  378. # include <LibWeb/SVG/@name@.h>
  379. #endif
  380. )~~~");
  381. if (interface.wrapper_base_class != "Wrapper") {
  382. generator.append(R"~~~(
  383. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  384. )~~~");
  385. }
  386. generator.append(R"~~~(
  387. namespace Web::Bindings {
  388. class @wrapper_class@ : public @wrapper_base_class@ {
  389. JS_OBJECT(@wrapper_class@, @wrapper_base_class@);
  390. public:
  391. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  392. virtual void initialize(JS::GlobalObject&) override;
  393. virtual ~@wrapper_class@() override;
  394. )~~~");
  395. if (interface.wrapper_base_class == "Wrapper") {
  396. generator.append(R"~~~(
  397. @fully_qualified_name@& impl() { return *m_impl; }
  398. const @fully_qualified_name@& impl() const { return *m_impl; }
  399. )~~~");
  400. } else {
  401. generator.append(R"~~~(
  402. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  403. const @fully_qualified_name@& impl() const { return static_cast<const @fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  404. )~~~");
  405. }
  406. generator.append(R"~~~(
  407. private:
  408. virtual bool is_@wrapper_class:snakecase@() const final { return true; }
  409. )~~~");
  410. for (auto& function : interface.functions) {
  411. auto function_generator = generator.fork();
  412. function_generator.set("function.name:snakecase", snake_name(function.name));
  413. function_generator.append(R"~~~(
  414. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  415. )~~~");
  416. }
  417. for (auto& attribute : interface.attributes) {
  418. auto attribute_generator = generator.fork();
  419. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  420. attribute_generator.append(R"~~~(
  421. JS_DECLARE_NATIVE_GETTER(@attribute.name:snakecase@_getter);
  422. )~~~");
  423. if (!attribute.readonly) {
  424. attribute_generator.append(R"~~~(
  425. JS_DECLARE_NATIVE_SETTER(@attribute.name:snakecase@_setter);
  426. )~~~");
  427. }
  428. }
  429. if (interface.wrapper_base_class == "Wrapper") {
  430. generator.append(R"~~~(
  431. NonnullRefPtr<@fully_qualified_name@> m_impl;
  432. )~~~");
  433. }
  434. generator.append(R"~~~(
  435. };
  436. )~~~");
  437. if (should_emit_wrapper_factory(interface)) {
  438. generator.append(R"~~~(
  439. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  440. )~~~");
  441. }
  442. generator.append(R"~~~(
  443. } // namespace Web::Bindings
  444. )~~~");
  445. outln("{}", generator.as_string_view());
  446. }
  447. void generate_implementation(const IDL::Interface& interface)
  448. {
  449. StringBuilder builder;
  450. SourceGenerator generator { builder };
  451. generator.set("wrapper_class", interface.wrapper_class);
  452. generator.set("wrapper_base_class", interface.wrapper_base_class);
  453. generator.set("fully_qualified_name", interface.fully_qualified_name);
  454. generator.append(R"~~~(
  455. #include <AK/FlyString.h>
  456. #include <LibJS/Runtime/Array.h>
  457. #include <LibJS/Runtime/Error.h>
  458. #include <LibJS/Runtime/Function.h>
  459. #include <LibJS/Runtime/GlobalObject.h>
  460. #include <LibJS/Runtime/Uint8ClampedArray.h>
  461. #include <LibJS/Runtime/Value.h>
  462. #include <LibWeb/Bindings/@wrapper_class@.h>
  463. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  464. #include <LibWeb/Bindings/CommentWrapper.h>
  465. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  466. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  467. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  468. #include <LibWeb/Bindings/DocumentWrapper.h>
  469. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  470. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  471. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  472. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  473. #include <LibWeb/Bindings/ImageDataWrapper.h>
  474. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  475. #include <LibWeb/Bindings/TextWrapper.h>
  476. #include <LibWeb/Bindings/WindowObject.h>
  477. #include <LibWeb/DOM/Element.h>
  478. #include <LibWeb/DOM/EventListener.h>
  479. #include <LibWeb/HTML/HTMLElement.h>
  480. #include <LibWeb/Origin.h>
  481. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  482. using namespace Web::DOM;
  483. using namespace Web::HTML;
  484. namespace Web::Bindings {
  485. )~~~");
  486. if (interface.wrapper_base_class == "Wrapper") {
  487. generator.append(R"~~~(
  488. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  489. : Wrapper(*global_object.object_prototype())
  490. , m_impl(impl)
  491. {
  492. }
  493. )~~~");
  494. } else {
  495. generator.append(R"~~~(
  496. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  497. : @wrapper_base_class@(global_object, impl)
  498. {
  499. }
  500. )~~~");
  501. }
  502. generator.append(R"~~~(
  503. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  504. {
  505. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;
  506. @wrapper_base_class@::initialize(global_object);
  507. )~~~");
  508. for (auto& attribute : interface.attributes) {
  509. auto attribute_generator = generator.fork();
  510. attribute_generator.set("attribute.name", attribute.name);
  511. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  512. if (attribute.readonly)
  513. attribute_generator.set("attribute.setter_callback", "nullptr");
  514. else
  515. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  516. attribute_generator.append(R"~~~(
  517. define_native_property("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  518. )~~~");
  519. }
  520. for (auto& function : interface.functions) {
  521. auto function_generator = generator.fork();
  522. function_generator.set("function.name", function.name);
  523. function_generator.set("function.name:snakecase", snake_name(function.name));
  524. function_generator.set("function.name:length", String::number(function.name.length()));
  525. function_generator.append(R"~~~(
  526. define_native_function("@function.name@", @function.name:snakecase@, @function.name:length@, default_attributes);
  527. )~~~");
  528. }
  529. generator.append(R"~~~(
  530. }
  531. @wrapper_class@::~@wrapper_class@()
  532. {
  533. }
  534. )~~~");
  535. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  536. generator.append(R"~~~(
  537. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  538. {
  539. auto* this_object = vm.this_value(global_object).to_object(global_object);
  540. if (!this_object)
  541. return {};
  542. if (!this_object->inherits("@wrapper_class@")) {
  543. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  544. return nullptr;
  545. }
  546. return &static_cast<@wrapper_class@*>(this_object)->impl();
  547. }
  548. )~~~");
  549. }
  550. 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) {
  551. auto scoped_generator = generator.fork();
  552. scoped_generator.set("cpp_name", cpp_name);
  553. scoped_generator.set("js_name", js_name);
  554. scoped_generator.set("js_suffix", js_suffix);
  555. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  556. scoped_generator.set("parameter.type.name", parameter.type.name);
  557. if (return_void)
  558. scoped_generator.set("return_statement", "return;");
  559. else
  560. scoped_generator.set("return_statement", "return {};");
  561. // FIXME: Add support for optional to all types
  562. if (parameter.type.name == "DOMString") {
  563. if (!optional) {
  564. scoped_generator.append(R"~~~(
  565. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  566. if (vm.exception())
  567. @return_statement@
  568. )~~~");
  569. } else {
  570. scoped_generator.append(R"~~~(
  571. String @cpp_name@;
  572. if (!@js_name@@js_suffix@.is_undefined()) {
  573. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  574. if (vm.exception())
  575. @return_statement@
  576. }
  577. )~~~");
  578. }
  579. } else if (parameter.type.name == "EventListener") {
  580. scoped_generator.append(R"~~~(
  581. if (!@js_name@@js_suffix@.is_function()) {
  582. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "Function");
  583. @return_statement@
  584. }
  585. auto @cpp_name@ = adopt(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  586. )~~~");
  587. } else if (is_wrappable_type(parameter.type)) {
  588. scoped_generator.append(R"~~~(
  589. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  590. if (vm.exception())
  591. @return_statement@
  592. if (!@cpp_name@_object->inherits("@parameter.type.name@Wrapper")) {
  593. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  594. @return_statement@
  595. }
  596. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  597. )~~~");
  598. } else if (parameter.type.name == "double") {
  599. scoped_generator.append(R"~~~(
  600. auto @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  601. if (vm.exception())
  602. @return_statement@
  603. )~~~");
  604. } else if (parameter.type.name == "boolean") {
  605. scoped_generator.append(R"~~~(
  606. auto @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  607. )~~~");
  608. } else {
  609. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  610. ASSERT_NOT_REACHED();
  611. }
  612. };
  613. auto generate_arguments = [&](auto& parameters, auto& arguments_builder, bool return_void = false) {
  614. auto arguments_generator = generator.fork();
  615. Vector<String> parameter_names;
  616. size_t argument_index = 0;
  617. for (auto& parameter : parameters) {
  618. parameter_names.append(snake_name(parameter.name));
  619. arguments_generator.set("argument.index", String::number(argument_index));
  620. arguments_generator.append(R"~~~(
  621. auto arg@argument.index@ = vm.argument(@argument.index@);
  622. )~~~");
  623. // FIXME: Parameters can have [LegacyNullToEmptyString] attached.
  624. generate_to_cpp(parameter, "arg", String::number(argument_index), snake_name(parameter.name), return_void, false, parameter.optional);
  625. ++argument_index;
  626. }
  627. arguments_builder.join(", ", parameter_names);
  628. };
  629. auto generate_return_statement = [&](auto& return_type) {
  630. auto scoped_generator = generator.fork();
  631. scoped_generator.set("return_type", return_type.name);
  632. if (return_type.name == "void") {
  633. scoped_generator.append(R"~~~(
  634. return JS::js_undefined();
  635. )~~~");
  636. return;
  637. }
  638. if (return_type.nullable) {
  639. if (return_type.name == "DOMString") {
  640. scoped_generator.append(R"~~~(
  641. if (retval.is_null())
  642. return JS::js_null();
  643. )~~~");
  644. } else {
  645. scoped_generator.append(R"~~~(
  646. if (!retval)
  647. return JS::js_null();
  648. )~~~");
  649. }
  650. }
  651. if (return_type.name == "DOMString") {
  652. scoped_generator.append(R"~~~(
  653. return JS::js_string(vm, retval);
  654. )~~~");
  655. } else if (return_type.name == "ArrayFromVector") {
  656. // FIXME: Remove this fake type hack once it's no longer needed.
  657. // Basically once we have NodeList we can throw this out.
  658. scoped_generator.append(R"~~~(
  659. auto* new_array = JS::Array::create(global_object);
  660. for (auto& element : retval)
  661. new_array->indexed_properties().append(wrap(global_object, element));
  662. return new_array;
  663. )~~~");
  664. } else if (return_type.name == "long" || return_type.name == "double" || return_type.name == "boolean" || return_type.name == "short") {
  665. scoped_generator.append(R"~~~(
  666. return JS::Value(retval);
  667. )~~~");
  668. } else if (return_type.name == "Uint8ClampedArray") {
  669. scoped_generator.append(R"~~~(
  670. return retval;
  671. )~~~");
  672. } else {
  673. scoped_generator.append(R"~~~(
  674. return wrap(global_object, const_cast<@return_type@&>(*retval));
  675. )~~~");
  676. }
  677. };
  678. for (auto& attribute : interface.attributes) {
  679. auto attribute_generator = generator.fork();
  680. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  681. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  682. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  683. if (attribute.extended_attributes.contains("Reflect")) {
  684. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  685. if (attribute_name.is_null())
  686. attribute_name = attribute.name;
  687. attribute_name = make_input_acceptable_cpp(attribute_name);
  688. attribute_generator.set("attribute.reflect_name", attribute_name);
  689. } else {
  690. attribute_generator.set("attribute.reflect_name", snake_name(attribute.name));
  691. }
  692. attribute_generator.append(R"~~~(
  693. JS_DEFINE_NATIVE_GETTER(@wrapper_class@::@attribute.getter_callback@)
  694. {
  695. auto* impl = impl_from(vm, global_object);
  696. if (!impl)
  697. return {};
  698. )~~~");
  699. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  700. attribute_generator.append(R"~~~(
  701. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  702. return JS::js_null();
  703. )~~~");
  704. }
  705. if (attribute.extended_attributes.contains("Reflect")) {
  706. if (attribute.type.name != "boolean") {
  707. attribute_generator.append(R"~~~(
  708. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  709. )~~~");
  710. } else {
  711. attribute_generator.append(R"~~~(
  712. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  713. )~~~");
  714. }
  715. } else {
  716. attribute_generator.append(R"~~~(
  717. auto retval = impl->@attribute.name:snakecase@();
  718. )~~~");
  719. }
  720. generate_return_statement(attribute.type);
  721. attribute_generator.append(R"~~~(
  722. }
  723. )~~~");
  724. if (!attribute.readonly) {
  725. attribute_generator.append(R"~~~(
  726. JS_DEFINE_NATIVE_SETTER(@wrapper_class@::@attribute.setter_callback@)
  727. {
  728. auto* impl = impl_from(vm, global_object);
  729. if (!impl)
  730. return;
  731. )~~~");
  732. generate_to_cpp(attribute, "value", "", "cpp_value", true, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  733. if (attribute.extended_attributes.contains("Reflect")) {
  734. if (attribute.type.name != "boolean") {
  735. attribute_generator.append(R"~~~(
  736. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  737. )~~~");
  738. } else {
  739. attribute_generator.append(R"~~~(
  740. if (!cpp_value)
  741. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  742. else
  743. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  744. )~~~");
  745. }
  746. } else {
  747. attribute_generator.append(R"~~~(
  748. impl->set_@attribute.name:snakecase@(cpp_value);
  749. )~~~");
  750. }
  751. attribute_generator.append(R"~~~(
  752. }
  753. )~~~");
  754. }
  755. }
  756. // Implementation: Functions
  757. for (auto& function : interface.functions) {
  758. auto function_generator = generator.fork();
  759. function_generator.set("function.name", function.name);
  760. function_generator.set("function.name:snakecase", snake_name(function.name));
  761. function_generator.set("function.nargs", String::number(function.length()));
  762. function_generator.append(R"~~~(\
  763. JS_DEFINE_NATIVE_FUNCTION(@wrapper_class@::@function.name:snakecase@)
  764. {
  765. auto* impl = impl_from(vm, global_object);
  766. if (!impl)
  767. return {};
  768. )~~~");
  769. if (function.length() > 0) {
  770. if (function.length() == 1) {
  771. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  772. function_generator.set(".arg_count_suffix", "");
  773. } else {
  774. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  775. function_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  776. }
  777. function_generator.append(R"~~~(
  778. if (vm.argument_count() < @function.nargs@) {
  779. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  780. return {};
  781. }
  782. )~~~");
  783. }
  784. StringBuilder arguments_builder;
  785. generate_arguments(function.parameters, arguments_builder);
  786. function_generator.set(".arguments", arguments_builder.string_view());
  787. if (function.return_type.name != "void") {
  788. function_generator.append(R"~~~(
  789. auto retval = impl->@function.name:snakecase@(@.arguments@);
  790. )~~~");
  791. } else {
  792. function_generator.append(R"~~~(
  793. impl->@function.name:snakecase@(@.arguments@);
  794. )~~~");
  795. }
  796. generate_return_statement(function.return_type);
  797. function_generator.append(R"~~~(
  798. }
  799. )~~~");
  800. }
  801. if (should_emit_wrapper_factory(interface)) {
  802. generator.append(R"~~~(
  803. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  804. {
  805. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  806. }
  807. )~~~");
  808. }
  809. generator.append(R"~~~(
  810. } // namespace Web::Bindings
  811. )~~~");
  812. outln("{}", generator.as_string_view());
  813. }