WrapperGenerator.cpp 30 KB

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