WrapperGenerator.cpp 26 KB

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