WrapperGenerator.cpp 29 KB

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