WrapperGenerator.cpp 21 KB

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