WrapperGenerator.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. consume_whitespace();
  251. assert_specific(';');
  252. break;
  253. }
  254. if (lexer.consume_specific('[')) {
  255. extended_attributes = parse_extended_attributes();
  256. }
  257. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  258. parse_attribute(extended_attributes);
  259. continue;
  260. }
  261. parse_function(extended_attributes);
  262. }
  263. interface->wrapper_class = String::format("%sWrapper", interface->name.characters());
  264. interface->wrapper_base_class = String::format("%sWrapper", interface->parent_name.is_empty() ? "" : interface->parent_name.characters());
  265. return interface;
  266. }
  267. }
  268. static void generate_header(const IDL::Interface&);
  269. static void generate_implementation(const IDL::Interface&);
  270. int main(int argc, char** argv)
  271. {
  272. Core::ArgsParser args_parser;
  273. const char* path = nullptr;
  274. bool header_mode = false;
  275. bool implementation_mode = false;
  276. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  277. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  278. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  279. args_parser.parse(argc, argv);
  280. auto file_or_error = Core::File::open(path, Core::IODevice::ReadOnly);
  281. if (file_or_error.is_error()) {
  282. fprintf(stderr, "Cannot open %s\n", path);
  283. return 1;
  284. }
  285. LexicalPath lexical_path(path);
  286. auto namespace_ = lexical_path.parts().at(lexical_path.parts().size() - 2);
  287. auto data = file_or_error.value()->read_all();
  288. auto interface = IDL::parse_interface(path, data);
  289. if (!interface) {
  290. warnln("Cannot parse {}", path);
  291. return 1;
  292. }
  293. if (namespace_.is_one_of("DOM", "HTML", "UIEvents", "HighResolutionTime", "SVG")) {
  294. StringBuilder builder;
  295. builder.append(namespace_);
  296. builder.append("::");
  297. builder.append(interface->name);
  298. interface->fully_qualified_name = builder.to_string();
  299. } else {
  300. interface->fully_qualified_name = interface->name;
  301. }
  302. #if 0
  303. dbg() << "Attributes:";
  304. for (auto& attribute : interface->attributes) {
  305. dbg() << " " << (attribute.readonly ? "Readonly " : "")
  306. << attribute.type.name << (attribute.type.nullable ? "?" : "")
  307. << " " << attribute.name;
  308. }
  309. dbg() << "Functions:";
  310. for (auto& function : interface->functions) {
  311. dbg() << " " << function.return_type.name << (function.return_type.nullable ? "?" : "")
  312. << " " << function.name;
  313. for (auto& parameter : function.parameters) {
  314. dbg() << " " << parameter.type.name << (parameter.type.nullable ? "?" : "") << " " << parameter.name;
  315. }
  316. }
  317. #endif
  318. if (header_mode)
  319. generate_header(*interface);
  320. if (implementation_mode)
  321. generate_implementation(*interface);
  322. return 0;
  323. }
  324. static bool should_emit_wrapper_factory(const IDL::Interface& interface)
  325. {
  326. // FIXME: This is very hackish.
  327. if (interface.name == "Event")
  328. return false;
  329. if (interface.name == "EventTarget")
  330. return false;
  331. if (interface.name == "Node")
  332. return false;
  333. if (interface.name == "Text")
  334. return false;
  335. if (interface.name == "Document")
  336. return false;
  337. if (interface.name == "DocumentType")
  338. return false;
  339. if (interface.name.ends_with("Element"))
  340. return false;
  341. return true;
  342. }
  343. static bool is_wrappable_type(const IDL::Type& type)
  344. {
  345. if (type.name == "Node")
  346. return true;
  347. if (type.name == "Document")
  348. return true;
  349. if (type.name == "Text")
  350. return true;
  351. if (type.name == "DocumentType")
  352. return true;
  353. if (type.name.ends_with("Element"))
  354. return true;
  355. if (type.name == "ImageData")
  356. return true;
  357. return false;
  358. }
  359. static void generate_header(const IDL::Interface& interface)
  360. {
  361. StringBuilder builder;
  362. SourceGenerator generator { builder };
  363. generator.set("name", interface.name);
  364. generator.set("fully_qualified_name", interface.fully_qualified_name);
  365. generator.set("wrapper_base_class", interface.wrapper_base_class);
  366. generator.set("wrapper_class", interface.wrapper_class);
  367. generator.set("wrapper_class:snakecase", snake_name(interface.wrapper_class));
  368. generator.append(R"~~~(
  369. #pragma once
  370. #include <LibWeb/Bindings/Wrapper.h>
  371. // FIXME: This is very strange.
  372. #if __has_include(<LibWeb/DOM/@name@.h>)
  373. # include <LibWeb/DOM/@name@.h>
  374. #elif __has_include(<LibWeb/HTML/@name@.h>)
  375. # include <LibWeb/HTML/@name@.h>
  376. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  377. # include <LibWeb/UIEvents/@name@.h>
  378. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  379. # include <LibWeb/HighResolutionTime/@name@.h>
  380. #elif __has_include(<LibWeb/SVG/@name@.h>)
  381. # include <LibWeb/SVG/@name@.h>
  382. #endif
  383. )~~~");
  384. if (interface.wrapper_base_class != "Wrapper") {
  385. generator.append(R"~~~(
  386. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  387. )~~~");
  388. }
  389. generator.append(R"~~~(
  390. namespace Web::Bindings {
  391. class @wrapper_class@ : public @wrapper_base_class@ {
  392. JS_OBJECT(@wrapper_class@, @wrapper_base_class@);
  393. public:
  394. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  395. virtual void initialize(JS::GlobalObject&) override;
  396. virtual ~@wrapper_class@() override;
  397. )~~~");
  398. if (interface.wrapper_base_class == "Wrapper") {
  399. generator.append(R"~~~(
  400. @fully_qualified_name@& impl() { return *m_impl; }
  401. const @fully_qualified_name@& impl() const { return *m_impl; }
  402. )~~~");
  403. } else {
  404. generator.append(R"~~~(
  405. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  406. const @fully_qualified_name@& impl() const { return static_cast<const @fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  407. )~~~");
  408. }
  409. generator.append(R"~~~(
  410. private:
  411. )~~~");
  412. for (auto& function : interface.functions) {
  413. auto function_generator = generator.fork();
  414. function_generator.set("function.name:snakecase", snake_name(function.name));
  415. function_generator.append(R"~~~(
  416. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  417. )~~~");
  418. }
  419. for (auto& attribute : interface.attributes) {
  420. auto attribute_generator = generator.fork();
  421. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  422. attribute_generator.append(R"~~~(
  423. JS_DECLARE_NATIVE_GETTER(@attribute.name:snakecase@_getter);
  424. )~~~");
  425. if (!attribute.readonly) {
  426. attribute_generator.append(R"~~~(
  427. JS_DECLARE_NATIVE_SETTER(@attribute.name:snakecase@_setter);
  428. )~~~");
  429. }
  430. }
  431. if (interface.wrapper_base_class == "Wrapper") {
  432. generator.append(R"~~~(
  433. NonnullRefPtr<@fully_qualified_name@> m_impl;
  434. )~~~");
  435. }
  436. generator.append(R"~~~(
  437. };
  438. )~~~");
  439. if (should_emit_wrapper_factory(interface)) {
  440. generator.append(R"~~~(
  441. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  442. )~~~");
  443. }
  444. generator.append(R"~~~(
  445. } // namespace Web::Bindings
  446. )~~~");
  447. outln("{}", generator.as_string_view());
  448. }
  449. void generate_implementation(const IDL::Interface& interface)
  450. {
  451. StringBuilder builder;
  452. SourceGenerator generator { builder };
  453. generator.set("wrapper_class", interface.wrapper_class);
  454. generator.set("wrapper_base_class", interface.wrapper_base_class);
  455. generator.set("fully_qualified_name", interface.fully_qualified_name);
  456. generator.append(R"~~~(
  457. #include <AK/FlyString.h>
  458. #include <LibJS/Runtime/Array.h>
  459. #include <LibJS/Runtime/Error.h>
  460. #include <LibJS/Runtime/Function.h>
  461. #include <LibJS/Runtime/GlobalObject.h>
  462. #include <LibJS/Runtime/Uint8ClampedArray.h>
  463. #include <LibJS/Runtime/Value.h>
  464. #include <LibWeb/Bindings/@wrapper_class@.h>
  465. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  466. #include <LibWeb/Bindings/CommentWrapper.h>
  467. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  468. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  469. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  470. #include <LibWeb/Bindings/DocumentWrapper.h>
  471. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  472. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  473. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  474. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  475. #include <LibWeb/Bindings/ImageDataWrapper.h>
  476. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  477. #include <LibWeb/Bindings/TextWrapper.h>
  478. #include <LibWeb/Bindings/WindowObject.h>
  479. #include <LibWeb/DOM/Element.h>
  480. #include <LibWeb/DOM/EventListener.h>
  481. #include <LibWeb/HTML/HTMLElement.h>
  482. #include <LibWeb/Origin.h>
  483. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  484. using namespace Web::DOM;
  485. using namespace Web::HTML;
  486. namespace Web::Bindings {
  487. )~~~");
  488. if (interface.wrapper_base_class == "Wrapper") {
  489. generator.append(R"~~~(
  490. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  491. : Wrapper(*global_object.object_prototype())
  492. , m_impl(impl)
  493. {
  494. }
  495. )~~~");
  496. } else {
  497. generator.append(R"~~~(
  498. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  499. : @wrapper_base_class@(global_object, impl)
  500. {
  501. }
  502. )~~~");
  503. }
  504. generator.append(R"~~~(
  505. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  506. {
  507. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;
  508. @wrapper_base_class@::initialize(global_object);
  509. )~~~");
  510. for (auto& attribute : interface.attributes) {
  511. auto attribute_generator = generator.fork();
  512. attribute_generator.set("attribute.name", attribute.name);
  513. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  514. if (attribute.readonly)
  515. attribute_generator.set("attribute.setter_callback", "nullptr");
  516. else
  517. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  518. attribute_generator.append(R"~~~(
  519. define_native_property("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  520. )~~~");
  521. }
  522. for (auto& function : interface.functions) {
  523. auto function_generator = generator.fork();
  524. function_generator.set("function.name", function.name);
  525. function_generator.set("function.name:snakecase", snake_name(function.name));
  526. function_generator.set("function.name:length", String::number(function.name.length()));
  527. function_generator.append(R"~~~(
  528. define_native_function("@function.name@", @function.name:snakecase@, @function.name:length@, default_attributes);
  529. )~~~");
  530. }
  531. generator.append(R"~~~(
  532. }
  533. @wrapper_class@::~@wrapper_class@()
  534. {
  535. }
  536. )~~~");
  537. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  538. generator.append(R"~~~(
  539. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  540. {
  541. auto* this_object = vm.this_value(global_object).to_object(global_object);
  542. if (!this_object)
  543. return {};
  544. if (!is<@wrapper_class@>(this_object)) {
  545. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  546. return nullptr;
  547. }
  548. return &static_cast<@wrapper_class@*>(this_object)->impl();
  549. }
  550. )~~~");
  551. }
  552. 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) {
  553. auto scoped_generator = generator.fork();
  554. scoped_generator.set("cpp_name", cpp_name);
  555. scoped_generator.set("js_name", js_name);
  556. scoped_generator.set("js_suffix", js_suffix);
  557. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  558. scoped_generator.set("parameter.type.name", parameter.type.name);
  559. if (return_void)
  560. scoped_generator.set("return_statement", "return;");
  561. else
  562. scoped_generator.set("return_statement", "return {};");
  563. // FIXME: Add support for optional to all types
  564. if (parameter.type.name == "DOMString") {
  565. if (!optional) {
  566. scoped_generator.append(R"~~~(
  567. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  568. if (vm.exception())
  569. @return_statement@
  570. )~~~");
  571. } else {
  572. scoped_generator.append(R"~~~(
  573. String @cpp_name@;
  574. if (!@js_name@@js_suffix@.is_undefined()) {
  575. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  576. if (vm.exception())
  577. @return_statement@
  578. }
  579. )~~~");
  580. }
  581. } else if (parameter.type.name == "EventListener") {
  582. scoped_generator.append(R"~~~(
  583. if (!@js_name@@js_suffix@.is_function()) {
  584. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "Function");
  585. @return_statement@
  586. }
  587. auto @cpp_name@ = adopt(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  588. )~~~");
  589. } else if (is_wrappable_type(parameter.type)) {
  590. scoped_generator.append(R"~~~(
  591. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  592. if (vm.exception())
  593. @return_statement@
  594. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  595. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  596. @return_statement@
  597. }
  598. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  599. )~~~");
  600. } else if (parameter.type.name == "double") {
  601. scoped_generator.append(R"~~~(
  602. auto @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  603. if (vm.exception())
  604. @return_statement@
  605. )~~~");
  606. } else if (parameter.type.name == "boolean") {
  607. scoped_generator.append(R"~~~(
  608. auto @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  609. )~~~");
  610. } else {
  611. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  612. ASSERT_NOT_REACHED();
  613. }
  614. };
  615. auto generate_arguments = [&](auto& parameters, auto& arguments_builder, bool return_void = false) {
  616. auto arguments_generator = generator.fork();
  617. Vector<String> parameter_names;
  618. size_t argument_index = 0;
  619. for (auto& parameter : parameters) {
  620. parameter_names.append(snake_name(parameter.name));
  621. arguments_generator.set("argument.index", String::number(argument_index));
  622. arguments_generator.append(R"~~~(
  623. auto arg@argument.index@ = vm.argument(@argument.index@);
  624. )~~~");
  625. // FIXME: Parameters can have [LegacyNullToEmptyString] attached.
  626. generate_to_cpp(parameter, "arg", String::number(argument_index), snake_name(parameter.name), return_void, false, parameter.optional);
  627. ++argument_index;
  628. }
  629. arguments_builder.join(", ", parameter_names);
  630. };
  631. auto generate_return_statement = [&](auto& return_type) {
  632. auto scoped_generator = generator.fork();
  633. scoped_generator.set("return_type", return_type.name);
  634. if (return_type.name == "undefined") {
  635. scoped_generator.append(R"~~~(
  636. return JS::js_undefined();
  637. )~~~");
  638. return;
  639. }
  640. if (return_type.nullable) {
  641. if (return_type.name == "DOMString") {
  642. scoped_generator.append(R"~~~(
  643. if (retval.is_null())
  644. return JS::js_null();
  645. )~~~");
  646. } else {
  647. scoped_generator.append(R"~~~(
  648. if (!retval)
  649. return JS::js_null();
  650. )~~~");
  651. }
  652. }
  653. if (return_type.name == "DOMString") {
  654. scoped_generator.append(R"~~~(
  655. return JS::js_string(vm, retval);
  656. )~~~");
  657. } else if (return_type.name == "ArrayFromVector") {
  658. // FIXME: Remove this fake type hack once it's no longer needed.
  659. // Basically once we have NodeList we can throw this out.
  660. scoped_generator.append(R"~~~(
  661. auto* new_array = JS::Array::create(global_object);
  662. for (auto& element : retval)
  663. new_array->indexed_properties().append(wrap(global_object, element));
  664. return new_array;
  665. )~~~");
  666. } else if (return_type.name == "long" || return_type.name == "double" || return_type.name == "boolean" || return_type.name == "short") {
  667. scoped_generator.append(R"~~~(
  668. return JS::Value(retval);
  669. )~~~");
  670. } else if (return_type.name == "Uint8ClampedArray") {
  671. scoped_generator.append(R"~~~(
  672. return retval;
  673. )~~~");
  674. } else {
  675. scoped_generator.append(R"~~~(
  676. return wrap(global_object, const_cast<@return_type@&>(*retval));
  677. )~~~");
  678. }
  679. };
  680. for (auto& attribute : interface.attributes) {
  681. auto attribute_generator = generator.fork();
  682. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  683. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  684. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  685. if (attribute.extended_attributes.contains("Reflect")) {
  686. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  687. if (attribute_name.is_null())
  688. attribute_name = attribute.name;
  689. attribute_name = make_input_acceptable_cpp(attribute_name);
  690. attribute_generator.set("attribute.reflect_name", attribute_name);
  691. } else {
  692. attribute_generator.set("attribute.reflect_name", snake_name(attribute.name));
  693. }
  694. attribute_generator.append(R"~~~(
  695. JS_DEFINE_NATIVE_GETTER(@wrapper_class@::@attribute.getter_callback@)
  696. {
  697. auto* impl = impl_from(vm, global_object);
  698. if (!impl)
  699. return {};
  700. )~~~");
  701. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  702. attribute_generator.append(R"~~~(
  703. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  704. return JS::js_null();
  705. )~~~");
  706. }
  707. if (attribute.extended_attributes.contains("Reflect")) {
  708. if (attribute.type.name != "boolean") {
  709. attribute_generator.append(R"~~~(
  710. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  711. )~~~");
  712. } else {
  713. attribute_generator.append(R"~~~(
  714. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  715. )~~~");
  716. }
  717. } else {
  718. attribute_generator.append(R"~~~(
  719. auto retval = impl->@attribute.name:snakecase@();
  720. )~~~");
  721. }
  722. generate_return_statement(attribute.type);
  723. attribute_generator.append(R"~~~(
  724. }
  725. )~~~");
  726. if (!attribute.readonly) {
  727. attribute_generator.append(R"~~~(
  728. JS_DEFINE_NATIVE_SETTER(@wrapper_class@::@attribute.setter_callback@)
  729. {
  730. auto* impl = impl_from(vm, global_object);
  731. if (!impl)
  732. return;
  733. )~~~");
  734. generate_to_cpp(attribute, "value", "", "cpp_value", true, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  735. if (attribute.extended_attributes.contains("Reflect")) {
  736. if (attribute.type.name != "boolean") {
  737. attribute_generator.append(R"~~~(
  738. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  739. )~~~");
  740. } else {
  741. attribute_generator.append(R"~~~(
  742. if (!cpp_value)
  743. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  744. else
  745. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  746. )~~~");
  747. }
  748. } else {
  749. attribute_generator.append(R"~~~(
  750. impl->set_@attribute.name:snakecase@(cpp_value);
  751. )~~~");
  752. }
  753. attribute_generator.append(R"~~~(
  754. }
  755. )~~~");
  756. }
  757. }
  758. // Implementation: Functions
  759. for (auto& function : interface.functions) {
  760. auto function_generator = generator.fork();
  761. function_generator.set("function.name", function.name);
  762. function_generator.set("function.name:snakecase", snake_name(function.name));
  763. function_generator.set("function.nargs", String::number(function.length()));
  764. function_generator.append(R"~~~(\
  765. JS_DEFINE_NATIVE_FUNCTION(@wrapper_class@::@function.name:snakecase@)
  766. {
  767. auto* impl = impl_from(vm, global_object);
  768. if (!impl)
  769. return {};
  770. )~~~");
  771. if (function.length() > 0) {
  772. if (function.length() == 1) {
  773. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  774. function_generator.set(".arg_count_suffix", "");
  775. } else {
  776. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  777. function_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  778. }
  779. function_generator.append(R"~~~(
  780. if (vm.argument_count() < @function.nargs@) {
  781. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  782. return {};
  783. }
  784. )~~~");
  785. }
  786. StringBuilder arguments_builder;
  787. generate_arguments(function.parameters, arguments_builder);
  788. function_generator.set(".arguments", arguments_builder.string_view());
  789. if (function.return_type.name != "undefined") {
  790. function_generator.append(R"~~~(
  791. auto retval = impl->@function.name:snakecase@(@.arguments@);
  792. )~~~");
  793. } else {
  794. function_generator.append(R"~~~(
  795. impl->@function.name:snakecase@(@.arguments@);
  796. )~~~");
  797. }
  798. generate_return_statement(function.return_type);
  799. function_generator.append(R"~~~(
  800. }
  801. )~~~");
  802. }
  803. if (should_emit_wrapper_factory(interface)) {
  804. generator.append(R"~~~(
  805. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  806. {
  807. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  808. }
  809. )~~~");
  810. }
  811. generator.append(R"~~~(
  812. } // namespace Web::Bindings
  813. )~~~");
  814. outln("{}", generator.as_string_view());
  815. }