WrapperGenerator.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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/HashMap.h>
  28. #include <AK/LexicalPath.h>
  29. #include <AK/StringBuilder.h>
  30. #include <LibCore/ArgsParser.h>
  31. #include <LibCore/File.h>
  32. #include <ctype.h>
  33. static String snake_name(const StringView& title_name)
  34. {
  35. StringBuilder builder;
  36. bool first = true;
  37. bool last_was_uppercase = false;
  38. for (auto ch : title_name) {
  39. if (isupper(ch)) {
  40. if (!first && !last_was_uppercase)
  41. builder.append('_');
  42. builder.append(tolower(ch));
  43. } else {
  44. builder.append(ch);
  45. }
  46. first = false;
  47. last_was_uppercase = isupper(ch);
  48. }
  49. return builder.to_string();
  50. }
  51. static String add_underscore_to_cpp_keywords(const String& input)
  52. {
  53. if (input == "class" || input == "template") {
  54. StringBuilder builder;
  55. builder.append(input);
  56. builder.append('_');
  57. return builder.to_string();
  58. }
  59. return input;
  60. }
  61. namespace IDL {
  62. struct Type {
  63. String name;
  64. bool nullable { false };
  65. };
  66. struct Parameter {
  67. Type type;
  68. String name;
  69. };
  70. struct Function {
  71. Type return_type;
  72. String name;
  73. Vector<Parameter> parameters;
  74. HashMap<String, String> extended_attributes;
  75. size_t length() const
  76. {
  77. // FIXME: Take optional arguments into account
  78. return parameters.size();
  79. }
  80. };
  81. struct Attribute {
  82. bool readonly { false };
  83. bool unsigned_ { false };
  84. Type type;
  85. String name;
  86. HashMap<String, String> extended_attributes;
  87. // Added for convenience after parsing
  88. String getter_callback_name;
  89. String setter_callback_name;
  90. };
  91. struct Interface {
  92. String name;
  93. String parent_name;
  94. Vector<Attribute> attributes;
  95. Vector<Function> functions;
  96. // Added for convenience after parsing
  97. String wrapper_class;
  98. String wrapper_base_class;
  99. String fully_qualified_name;
  100. };
  101. OwnPtr<Interface> parse_interface(const StringView& input)
  102. {
  103. auto interface = make<Interface>();
  104. size_t index = 0;
  105. auto peek = [&](size_t offset = 0) -> char {
  106. if (index + offset > input.length())
  107. return 0;
  108. return input[index + offset];
  109. };
  110. auto consume = [&] {
  111. return input[index++];
  112. };
  113. auto consume_if = [&](auto ch) {
  114. if (peek() == ch) {
  115. consume();
  116. return true;
  117. }
  118. return false;
  119. };
  120. auto consume_specific = [&](char ch) {
  121. auto consumed = consume();
  122. if (consumed != ch) {
  123. dbg() << "Expected '" << ch << "' at offset " << index << " but got '" << consumed << "'";
  124. ASSERT_NOT_REACHED();
  125. }
  126. };
  127. auto consume_whitespace = [&] {
  128. while (isspace(peek()))
  129. consume();
  130. };
  131. auto consume_string = [&](const StringView& string) {
  132. for (size_t i = 0; i < string.length(); ++i) {
  133. ASSERT(consume() == string[i]);
  134. }
  135. };
  136. auto next_is = [&](const StringView& string) {
  137. for (size_t i = 0; i < string.length(); ++i) {
  138. if (peek(i) != string[i])
  139. return false;
  140. }
  141. return true;
  142. };
  143. auto consume_while = [&](auto condition) {
  144. StringBuilder builder;
  145. while (index < input.length() && condition(peek())) {
  146. builder.append(consume());
  147. }
  148. return builder.to_string();
  149. };
  150. consume_string("interface");
  151. consume_whitespace();
  152. interface->name = consume_while([](auto ch) { return !isspace(ch); });
  153. consume_whitespace();
  154. if (consume_if(':')) {
  155. consume_whitespace();
  156. interface->parent_name = consume_while([](auto ch) { return !isspace(ch); });
  157. consume_whitespace();
  158. }
  159. consume_specific('{');
  160. auto parse_type = [&] {
  161. auto name = consume_while([](auto ch) { return !isspace(ch) && ch != '?'; });
  162. auto nullable = peek() == '?';
  163. if (nullable)
  164. consume_specific('?');
  165. return Type { name, nullable };
  166. };
  167. auto parse_attribute = [&](HashMap<String, String>& extended_attributes) {
  168. bool readonly = false;
  169. bool unsigned_ = false;
  170. if (next_is("readonly")) {
  171. consume_string("readonly");
  172. readonly = true;
  173. consume_whitespace();
  174. }
  175. if (next_is("attribute")) {
  176. consume_string("attribute");
  177. consume_whitespace();
  178. }
  179. if (next_is("unsigned")) {
  180. consume_string("unsigned");
  181. unsigned_ = true;
  182. consume_whitespace();
  183. }
  184. auto type = parse_type();
  185. consume_whitespace();
  186. auto name = consume_while([](auto ch) { return !isspace(ch) && ch != ';'; });
  187. consume_specific(';');
  188. Attribute attribute;
  189. attribute.readonly = readonly;
  190. attribute.unsigned_ = unsigned_;
  191. attribute.type = type;
  192. attribute.name = name;
  193. attribute.getter_callback_name = String::format("%s_getter", snake_name(attribute.name).characters());
  194. attribute.setter_callback_name = String::format("%s_setter", snake_name(attribute.name).characters());
  195. attribute.extended_attributes = move(extended_attributes);
  196. interface->attributes.append(move(attribute));
  197. };
  198. auto parse_function = [&](HashMap<String, String>& extended_attributes) {
  199. auto return_type = parse_type();
  200. consume_whitespace();
  201. auto name = consume_while([](auto ch) { return !isspace(ch) && ch != '('; });
  202. consume_specific('(');
  203. Vector<Parameter> parameters;
  204. for (;;) {
  205. if (consume_if(')'))
  206. break;
  207. auto type = parse_type();
  208. consume_whitespace();
  209. auto name = consume_while([](auto ch) { return !isspace(ch) && ch != ',' && ch != ')'; });
  210. parameters.append({ move(type), move(name) });
  211. if (consume_if(')'))
  212. break;
  213. consume_specific(',');
  214. consume_whitespace();
  215. }
  216. consume_specific(';');
  217. interface->functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  218. };
  219. auto parse_extended_attributes = [&] {
  220. HashMap<String, String> extended_attributes;
  221. for (;;) {
  222. consume_whitespace();
  223. if (consume_if(']'))
  224. break;
  225. auto name = consume_while([](auto ch) { return ch != ']' && ch != '=' && ch != ','; });
  226. if (consume_if('=')) {
  227. auto value = consume_while([](auto ch) { return ch != ']' && ch != ','; });
  228. extended_attributes.set(name, value);
  229. } else {
  230. extended_attributes.set(name, {});
  231. }
  232. }
  233. consume_whitespace();
  234. return extended_attributes;
  235. };
  236. for (;;) {
  237. HashMap<String, String> extended_attributes;
  238. consume_whitespace();
  239. if (consume_if('}'))
  240. break;
  241. if (consume_if('[')) {
  242. extended_attributes = parse_extended_attributes();
  243. }
  244. if (next_is("readonly") || next_is("attribute")) {
  245. parse_attribute(extended_attributes);
  246. continue;
  247. }
  248. parse_function(extended_attributes);
  249. }
  250. interface->wrapper_class = String::format("%sWrapper", interface->name.characters());
  251. interface->wrapper_base_class = String::format("%sWrapper", interface->parent_name.is_empty() ? "" : interface->parent_name.characters());
  252. return interface;
  253. }
  254. }
  255. static void generate_header(const IDL::Interface&);
  256. static void generate_implementation(const IDL::Interface&);
  257. int main(int argc, char** argv)
  258. {
  259. Core::ArgsParser args_parser;
  260. const char* path = nullptr;
  261. bool header_mode = false;
  262. bool implementation_mode = false;
  263. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  264. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  265. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  266. args_parser.parse(argc, argv);
  267. auto file_or_error = Core::File::open(path, Core::IODevice::ReadOnly);
  268. if (file_or_error.is_error()) {
  269. fprintf(stderr, "Cannot open %s\n", path);
  270. return 1;
  271. }
  272. LexicalPath lexical_path(path);
  273. auto namespace_ = lexical_path.parts().at(lexical_path.parts().size() - 2);
  274. auto data = file_or_error.value()->read_all();
  275. auto interface = IDL::parse_interface(data);
  276. if (!interface) {
  277. fprintf(stderr, "Cannot parse %s\n", path);
  278. return 1;
  279. }
  280. if (namespace_ == "DOM") {
  281. StringBuilder builder;
  282. builder.append(namespace_);
  283. builder.append("::");
  284. builder.append(interface->name);
  285. interface->fully_qualified_name = builder.to_string();
  286. } else {
  287. interface->fully_qualified_name = interface->name;
  288. }
  289. #if 0
  290. dbg() << "Attributes:";
  291. for (auto& attribute : interface->attributes) {
  292. dbg() << " " << (attribute.readonly ? "Readonly " : "")
  293. << attribute.type.name << (attribute.type.nullable ? "?" : "")
  294. << " " << attribute.name;
  295. }
  296. dbg() << "Functions:";
  297. for (auto& function : interface->functions) {
  298. dbg() << " " << function.return_type.name << (function.return_type.nullable ? "?" : "")
  299. << " " << function.name;
  300. for (auto& parameter : function.parameters) {
  301. dbg() << " " << parameter.type.name << (parameter.type.nullable ? "?" : "") << " " << parameter.name;
  302. }
  303. }
  304. #endif
  305. if (header_mode)
  306. generate_header(*interface);
  307. if (implementation_mode)
  308. generate_implementation(*interface);
  309. return 0;
  310. }
  311. static bool should_emit_wrapper_factory(const IDL::Interface& interface)
  312. {
  313. // FIXME: This is very hackish.
  314. if (interface.name == "EventTarget")
  315. return false;
  316. if (interface.name == "Node")
  317. return false;
  318. if (interface.name == "Text")
  319. return false;
  320. if (interface.name == "Document")
  321. return false;
  322. if (interface.name == "DocumentType")
  323. return false;
  324. if (interface.name.ends_with("Element"))
  325. return false;
  326. if (interface.name.ends_with("Event"))
  327. return false;
  328. return true;
  329. }
  330. static bool is_wrappable_type(const IDL::Type& type)
  331. {
  332. if (type.name == "Node")
  333. return true;
  334. if (type.name == "Document")
  335. return true;
  336. if (type.name == "Text")
  337. return true;
  338. if (type.name == "DocumentType")
  339. return true;
  340. if (type.name.ends_with("Element"))
  341. return true;
  342. if (type.name == "ImageData")
  343. return true;
  344. return false;
  345. }
  346. static void generate_header(const IDL::Interface& interface)
  347. {
  348. auto& wrapper_class = interface.wrapper_class;
  349. auto& wrapper_base_class = interface.wrapper_base_class;
  350. out() << "#pragma once";
  351. out() << "#include <LibWeb/Bindings/Wrapper.h>";
  352. // FIXME: This is very strange.
  353. out() << "#if __has_include(<LibWeb/DOM/" << interface.name << ".h>)";
  354. out() << "#include <LibWeb/DOM/" << interface.name << ".h>";
  355. out() << "#else";
  356. out() << "#include <LibWeb/HTML/" << interface.name << ".h>";
  357. out() << "#endif";
  358. if (wrapper_base_class != "Wrapper")
  359. out() << "#include <LibWeb/Bindings/" << wrapper_base_class << ".h>";
  360. out() << "namespace Web::Bindings {";
  361. out() << "class " << wrapper_class << " : public " << wrapper_base_class << " {";
  362. out() << " JS_OBJECT(" << wrapper_class << ", " << wrapper_base_class << ");";
  363. out() << "public:";
  364. out() << " " << wrapper_class << "(JS::GlobalObject&, " << interface.fully_qualified_name << "&);";
  365. out() << " virtual void initialize(JS::GlobalObject&) override;";
  366. out() << " virtual ~" << wrapper_class << "() override;";
  367. if (wrapper_base_class == "Wrapper") {
  368. out() << " " << interface.fully_qualified_name << "& impl() { return *m_impl; }";
  369. out() << " const " << interface.fully_qualified_name << "& impl() const { return *m_impl; }";
  370. } else {
  371. out() << " " << interface.fully_qualified_name << "& impl() { return static_cast<" << interface.fully_qualified_name << "&>(" << wrapper_base_class << "::impl()); }";
  372. out() << " const " << interface.fully_qualified_name << "& impl() const { return static_cast<const " << interface.fully_qualified_name << "&>(" << wrapper_base_class << "::impl()); }";
  373. }
  374. auto is_foo_wrapper_name = snake_name(String::format("Is%s", wrapper_class.characters()));
  375. out() << " virtual bool " << is_foo_wrapper_name << "() const final { return true; }";
  376. out() << "private:";
  377. for (auto& function : interface.functions) {
  378. out() << " JS_DECLARE_NATIVE_FUNCTION(" << snake_name(function.name) << ");";
  379. }
  380. for (auto& attribute : interface.attributes) {
  381. out() << " JS_DECLARE_NATIVE_GETTER(" << snake_name(attribute.name) << "_getter);";
  382. if (!attribute.readonly)
  383. out() << " JS_DECLARE_NATIVE_SETTER(" << snake_name(attribute.name) << "_setter);";
  384. }
  385. if (wrapper_base_class == "Wrapper") {
  386. out() << " NonnullRefPtr<" << interface.fully_qualified_name << "> m_impl;";
  387. }
  388. out() << "};";
  389. if (should_emit_wrapper_factory(interface)) {
  390. out() << wrapper_class << "* wrap(JS::GlobalObject&, " << interface.fully_qualified_name << "&);";
  391. }
  392. out() << "}";
  393. }
  394. void generate_implementation(const IDL::Interface& interface)
  395. {
  396. auto& wrapper_class = interface.wrapper_class;
  397. auto& wrapper_base_class = interface.wrapper_base_class;
  398. out() << "#include <AK/FlyString.h>";
  399. out() << "#include <LibJS/Interpreter.h>";
  400. out() << "#include <LibJS/Runtime/Array.h>";
  401. out() << "#include <LibJS/Runtime/Value.h>";
  402. out() << "#include <LibJS/Runtime/GlobalObject.h>";
  403. out() << "#include <LibJS/Runtime/Error.h>";
  404. out() << "#include <LibJS/Runtime/Function.h>";
  405. out() << "#include <LibJS/Runtime/Uint8ClampedArray.h>";
  406. out() << "#include <LibWeb/Bindings/NodeWrapperFactory.h>";
  407. out() << "#include <LibWeb/Bindings/" << wrapper_class << ".h>";
  408. out() << "#include <LibWeb/DOM/Element.h>";
  409. out() << "#include <LibWeb/HTML/HTMLElement.h>";
  410. out() << "#include <LibWeb/DOM/EventListener.h>";
  411. out() << "#include <LibWeb/Bindings/DocumentWrapper.h>";
  412. out() << "#include <LibWeb/Bindings/DocumentTypeWrapper.h>";
  413. out() << "#include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>";
  414. out() << "#include <LibWeb/Bindings/HTMLImageElementWrapper.h>";
  415. out() << "#include <LibWeb/Bindings/ImageDataWrapper.h>";
  416. out() << "#include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>";
  417. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  418. out() << "using Web::DOM::Node;";
  419. out() << "using Web::DOM::Document;";
  420. out() << "using Web::DOM::DocumentType;";
  421. out() << "using Web::DOM::Element;";
  422. out() << "using Web::DOM::EventListener;";
  423. out() << "namespace Web::Bindings {";
  424. // Implementation: Wrapper constructor
  425. out() << wrapper_class << "::" << wrapper_class << "(JS::GlobalObject& global_object, " << interface.fully_qualified_name << "& impl)";
  426. if (wrapper_base_class == "Wrapper") {
  427. out() << " : Wrapper(*global_object.object_prototype())";
  428. out() << " , m_impl(impl)";
  429. } else {
  430. out() << " : " << wrapper_base_class << "(global_object, impl)";
  431. }
  432. out() << "{";
  433. out() << "}";
  434. // Implementation: Wrapper initialize()
  435. out() << "void " << wrapper_class << "::initialize(JS::GlobalObject& global_object)";
  436. out() << "{";
  437. out() << " [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;";
  438. out() << " " << wrapper_base_class << "::initialize(global_object);";
  439. for (auto& attribute : interface.attributes) {
  440. out() << " define_native_property(\"" << attribute.name << "\", " << attribute.getter_callback_name << ", " << (attribute.readonly ? "nullptr" : attribute.setter_callback_name) << ", default_attributes);";
  441. }
  442. for (auto& function : interface.functions) {
  443. out() << " define_native_function(\"" << function.name << "\", " << snake_name(function.name) << ", " << function.length() << ", default_attributes);";
  444. }
  445. out() << "}";
  446. // Implementation: Wrapper destructor
  447. out() << wrapper_class << "::~" << wrapper_class << "()";
  448. out() << "{";
  449. out() << "}";
  450. // Implementation: impl_from()
  451. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  452. out() << "static " << interface.fully_qualified_name << "* impl_from(JS::Interpreter& interpreter, JS::GlobalObject& global_object)";
  453. out() << "{";
  454. out() << " auto* this_object = interpreter.this_value(global_object).to_object(interpreter, global_object);";
  455. out() << " if (!this_object)";
  456. out() << " return {};";
  457. out() << " if (!this_object->inherits(\"" << wrapper_class << "\")) {";
  458. out() << " interpreter.throw_exception<JS::TypeError>(JS::ErrorType::NotA, \"" << interface.fully_qualified_name << "\");";
  459. out() << " return nullptr;";
  460. out() << " }";
  461. out() << " return &static_cast<" << wrapper_class << "*>(this_object)->impl();";
  462. out() << "}";
  463. }
  464. auto generate_to_cpp = [&](auto& parameter, auto& js_name, auto& js_suffix, auto cpp_name, bool return_void = false) {
  465. auto generate_return = [&] {
  466. if (return_void)
  467. out() << " return;";
  468. else
  469. out() << " return {};";
  470. };
  471. if (parameter.type.name == "DOMString") {
  472. out() << " auto " << cpp_name << " = " << js_name << js_suffix << ".to_string(interpreter);";
  473. out() << " if (interpreter.exception())";
  474. generate_return();
  475. } else if (parameter.type.name == "EventListener") {
  476. out() << " if (!" << js_name << js_suffix << ".is_function()) {";
  477. out() << " interpreter.throw_exception<JS::TypeError>(JS::ErrorType::NotA, \"Function\");";
  478. generate_return();
  479. out() << " }";
  480. out() << " auto " << cpp_name << " = adopt(*new EventListener(JS::make_handle(&" << js_name << js_suffix << ".as_function())));";
  481. } else if (is_wrappable_type(parameter.type)) {
  482. out() << " auto " << cpp_name << "_object = " << js_name << js_suffix << ".to_object(interpreter, global_object);";
  483. out() << " if (interpreter.exception())";
  484. generate_return();
  485. out() << " if (!" << cpp_name << "_object->inherits(\"" << parameter.type.name << "Wrapper\")) {";
  486. out() << " interpreter.throw_exception<JS::TypeError>(JS::ErrorType::NotA, \"" << parameter.type.name << "\");";
  487. generate_return();
  488. out() << " }";
  489. out() << " auto& " << cpp_name << " = static_cast<" << parameter.type.name << "Wrapper*>(" << cpp_name << "_object)->impl();";
  490. } else if (parameter.type.name == "double") {
  491. out() << " auto " << cpp_name << " = " << js_name << js_suffix << ".to_double(interpreter);";
  492. out() << " if (interpreter.exception())";
  493. generate_return();
  494. } else {
  495. dbg() << "Unimplemented JS-to-C++ conversion: " << parameter.type.name;
  496. ASSERT_NOT_REACHED();
  497. }
  498. };
  499. auto generate_arguments = [&](auto& parameters, auto& arguments_builder, bool return_void = false) {
  500. Vector<String> parameter_names;
  501. size_t argument_index = 0;
  502. for (auto& parameter : parameters) {
  503. parameter_names.append(snake_name(parameter.name));
  504. out() << " auto arg" << argument_index << " = interpreter.argument(" << argument_index << ");";
  505. generate_to_cpp(parameter, "arg", argument_index, snake_name(parameter.name), return_void);
  506. ++argument_index;
  507. }
  508. arguments_builder.join(", ", parameter_names);
  509. };
  510. auto generate_return_statement = [&](auto& return_type) {
  511. if (return_type.name == "void") {
  512. out() << " return JS::js_undefined();";
  513. return;
  514. }
  515. if (return_type.nullable) {
  516. if (return_type.name == "DOMString") {
  517. out() << " if (retval.is_null())";
  518. } else {
  519. out() << " if (!retval)";
  520. }
  521. out() << " return JS::js_null();";
  522. }
  523. if (return_type.name == "DOMString") {
  524. out() << " return JS::js_string(interpreter, retval);";
  525. } else if (return_type.name == "ArrayFromVector") {
  526. // FIXME: Remove this fake type hack once it's no longer needed.
  527. // Basically once we have NodeList we can throw this out.
  528. out() << " auto* new_array = JS::Array::create(global_object);";
  529. out() << " for (auto& element : retval) {";
  530. out() << " new_array->indexed_properties().append(wrap(global_object, element));";
  531. out() << " }";
  532. out() << " return new_array;";
  533. } else if (return_type.name == "long" || return_type.name == "double") {
  534. out() << " return JS::Value(retval);";
  535. } else if (return_type.name == "Uint8ClampedArray") {
  536. out() << " return retval;";
  537. } else {
  538. out() << " return wrap(global_object, const_cast<" << return_type.name << "&>(*retval));";
  539. }
  540. };
  541. // Implementation: Attributes
  542. for (auto& attribute : interface.attributes) {
  543. out() << "JS_DEFINE_NATIVE_GETTER(" << wrapper_class << "::" << attribute.getter_callback_name << ")";
  544. out() << "{";
  545. out() << " auto* impl = impl_from(interpreter, global_object);";
  546. out() << " if (!impl)";
  547. out() << " return {};";
  548. if (attribute.extended_attributes.contains("Reflect")) {
  549. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  550. if (attribute_name.is_null())
  551. attribute_name = attribute.name;
  552. attribute_name = add_underscore_to_cpp_keywords(attribute_name);
  553. out() << " auto retval = impl->attribute(HTML::AttributeNames::" << attribute_name << ");";
  554. } else {
  555. out() << " auto retval = impl->" << snake_name(attribute.name) << "();";
  556. }
  557. generate_return_statement(attribute.type);
  558. out() << "}";
  559. if (!attribute.readonly) {
  560. out() << "JS_DEFINE_NATIVE_SETTER(" << wrapper_class << "::" << attribute.setter_callback_name << ")";
  561. out() << "{";
  562. out() << " auto* impl = impl_from(interpreter, global_object);";
  563. out() << " if (!impl)";
  564. out() << " return;";
  565. generate_to_cpp(attribute, "value", "", "cpp_value", true);
  566. if (attribute.extended_attributes.contains("Reflect")) {
  567. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  568. if (attribute_name.is_null())
  569. attribute_name = attribute.name;
  570. attribute_name = add_underscore_to_cpp_keywords(attribute_name);
  571. out() << " impl->set_attribute(HTML::AttributeNames::" << attribute_name << ", cpp_value);";
  572. } else {
  573. out() << " impl->set_" << snake_name(attribute.name) << "(cpp_value);";
  574. }
  575. out() << "}";
  576. }
  577. }
  578. // Implementation: Functions
  579. for (auto& function : interface.functions) {
  580. out() << "JS_DEFINE_NATIVE_FUNCTION(" << wrapper_class << "::" << snake_name(function.name) << ")";
  581. out() << "{";
  582. out() << " auto* impl = impl_from(interpreter, global_object);";
  583. out() << " if (!impl)";
  584. out() << " return {};";
  585. if (function.length() > 0) {
  586. out() << " if (interpreter.argument_count() < " << function.length() << ")";
  587. out() << " return interpreter.throw_exception<JS::TypeError>(JS::ErrorType::BadArgCountMany, \"" << function.name << "\", \"" << function.length() << "\");";
  588. }
  589. StringBuilder arguments_builder;
  590. generate_arguments(function.parameters, arguments_builder);
  591. if (function.return_type.name != "void") {
  592. out() << " auto retval = impl->" << snake_name(function.name) << "(" << arguments_builder.to_string() << ");";
  593. } else {
  594. out() << " impl->" << snake_name(function.name) << "(" << arguments_builder.to_string() << ");";
  595. }
  596. generate_return_statement(function.return_type);
  597. out() << "}";
  598. }
  599. // Implementation: Wrapper factory
  600. if (should_emit_wrapper_factory(interface)) {
  601. out() << wrapper_class << "* wrap(JS::GlobalObject& global_object, " << interface.fully_qualified_name << "& impl)";
  602. out() << "{";
  603. out() << " return static_cast<" << wrapper_class << "*>(wrap_impl(global_object, impl));";
  604. out() << "}";
  605. }
  606. out() << "}";
  607. }