WrapperGenerator.cpp 27 KB

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