WrapperGenerator.cpp 29 KB

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