WrapperGenerator.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 void generate_header(const IDL::Interface& interface)
  262. {
  263. auto& wrapper_class = interface.wrapper_class;
  264. auto& wrapper_base_class = interface.wrapper_base_class;
  265. out() << "#pragma once";
  266. out() << "#include <LibWeb/Bindings/Wrapper.h>";
  267. out() << "#include <LibWeb/DOM/" << interface.name << ".h>";
  268. if (wrapper_base_class != "Wrapper")
  269. out() << "#include <LibWeb/Bindings/" << wrapper_base_class << ".h>";
  270. out() << "namespace Web {";
  271. out() << "namespace Bindings {";
  272. out() << "class " << wrapper_class << " : public " << wrapper_base_class << " {";
  273. out() << " JS_OBJECT(" << wrapper_class << ", " << wrapper_base_class << ");";
  274. out() << "public:";
  275. out() << " " << wrapper_class << "(JS::GlobalObject&, " << interface.name << "&);";
  276. out() << " virtual void initialize(JS::Interpreter&, JS::GlobalObject&) override;";
  277. out() << " virtual ~" << wrapper_class << "() override;";
  278. if (wrapper_base_class == "Wrapper") {
  279. out() << " " << interface.name << "& impl() { return *m_impl; }";
  280. out() << " const " << interface.name << "& impl() const { return *m_impl; }";
  281. } else {
  282. out() << " " << interface.name << "& impl() { return static_cast<" << interface.name << "&>(" << wrapper_base_class << "::impl()); }";
  283. out() << " const " << interface.name << "& impl() const { return static_cast<const " << interface.name << "&>(" << wrapper_base_class << "::impl()); }";
  284. }
  285. auto is_foo_wrapper_name = snake_name(String::format("Is%s", wrapper_class.characters()));
  286. out() << " virtual bool " << is_foo_wrapper_name << "() const final { return true; }";
  287. out() << "private:";
  288. for (auto& function : interface.functions) {
  289. out() << " JS_DECLARE_NATIVE_FUNCTION(" << snake_name(function.name) << ");";
  290. }
  291. for (auto& attribute : interface.attributes) {
  292. out() << " JS_DECLARE_NATIVE_GETTER(" << snake_name(attribute.name) << "_getter);";
  293. if (!attribute.readonly)
  294. out() << " JS_DECLARE_NATIVE_SETTER(" << snake_name(attribute.name) << "_setter);";
  295. }
  296. if (wrapper_base_class == "Wrapper") {
  297. out() << " NonnullRefPtr<" << interface.name << "> m_impl;";
  298. }
  299. out() << "};";
  300. out() << "}";
  301. out() << "}";
  302. }
  303. void generate_implementation(const IDL::Interface& interface)
  304. {
  305. auto& wrapper_class = interface.wrapper_class;
  306. auto& wrapper_base_class = interface.wrapper_base_class;
  307. out() << "#include <AK/FlyString.h>";
  308. out() << "#include <LibJS/Interpreter.h>";
  309. out() << "#include <LibJS/Runtime/Array.h>";
  310. out() << "#include <LibJS/Runtime/Value.h>";
  311. out() << "#include <LibJS/Runtime/GlobalObject.h>";
  312. out() << "#include <LibJS/Runtime/Error.h>";
  313. out() << "#include <LibJS/Runtime/Function.h>";
  314. out() << "#include <LibWeb/Bindings/NodeWrapperFactory.h>";
  315. out() << "#include <LibWeb/Bindings/" << wrapper_class << ".h>";
  316. out() << "#include <LibWeb/DOM/Element.h>";
  317. out() << "#include <LibWeb/DOM/HTMLElement.h>";
  318. out() << "#include <LibWeb/DOM/EventListener.h>";
  319. out() << "#include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>";
  320. out() << "namespace Web {";
  321. out() << "namespace Bindings {";
  322. // Implementation: Wrapper constructor
  323. out() << wrapper_class << "::" << wrapper_class << "(JS::GlobalObject& global_object, " << interface.name << "& impl)";
  324. if (wrapper_base_class == "Wrapper") {
  325. out() << " : Wrapper(*global_object.object_prototype())";
  326. out() << " , m_impl(impl)";
  327. } else {
  328. out() << " : " << wrapper_base_class << "(global_object, impl)";
  329. }
  330. out() << "{";
  331. out() << "}";
  332. // Implementation: Wrapper initialize()
  333. out() << "void " << wrapper_class << "::initialize(JS::Interpreter& interpreter, JS::GlobalObject& global_object)";
  334. out() << "{";
  335. out() << " [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;";
  336. out() << " " << wrapper_base_class << "::initialize(interpreter, global_object);";
  337. for (auto& attribute : interface.attributes) {
  338. out() << " define_native_property(\"" << attribute.name << "\", " << attribute.getter_callback_name << ", " << (attribute.readonly ? "nullptr" : attribute.setter_callback_name) << ", default_attributes);";
  339. }
  340. for (auto& function : interface.functions) {
  341. out() << " define_native_function(\"" << function.name << "\", " << snake_name(function.name) << ", " << function.length() << ", default_attributes);";
  342. }
  343. out() << "}";
  344. // Implementation: Wrapper destructor
  345. out() << wrapper_class << "::~" << wrapper_class << "()";
  346. out() << "{";
  347. out() << "}";
  348. // Implementation: impl_from()
  349. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  350. out() << "static " << interface.name << "* impl_from(JS::Interpreter& interpreter, JS::GlobalObject& global_object)";
  351. out() << "{";
  352. out() << " auto* this_object = interpreter.this_value(global_object).to_object(interpreter, global_object);";
  353. out() << " if (!this_object)";
  354. out() << " return {};";
  355. out() << " if (!this_object->inherits(\"" << wrapper_class << "\")) {";
  356. out() << " interpreter.throw_exception<JS::TypeError>(JS::ErrorType::NotA, \"" << interface.name << "\");";
  357. out() << " return nullptr;";
  358. out() << " }";
  359. out() << " return &static_cast<" << wrapper_class << "*>(this_object)->impl();";
  360. out() << "}";
  361. }
  362. auto generate_to_cpp = [&](auto& parameter, auto& js_name, auto& js_suffix, auto cpp_name, bool return_void = false) {
  363. auto generate_return = [&] {
  364. if (return_void)
  365. out() << " return;";
  366. else
  367. out() << " return {};";
  368. };
  369. if (parameter.type.name == "DOMString") {
  370. out() << " auto " << cpp_name << " = " << js_name << js_suffix << ".to_string(interpreter);";
  371. out() << " if (interpreter.exception())";
  372. generate_return();
  373. } else if (parameter.type.name == "EventListener") {
  374. out() << " if (!" << js_name << js_suffix << ".is_function()) {";
  375. out() << " interpreter.throw_exception<JS::TypeError>(JS::ErrorType::NotA, \"Function\");";
  376. generate_return();
  377. out() << " }";
  378. out() << " auto " << cpp_name << " = adopt(*new EventListener(JS::make_handle(&" << js_name << js_suffix << ".as_function())));";
  379. } else if (parameter.type.name == "Node") {
  380. out() << " auto " << cpp_name << "_object = " << js_name << js_suffix << ".to_object(interpreter, global_object);";
  381. out() << " if (interpreter.exception())";
  382. generate_return();
  383. out() << " if (!" << cpp_name << "_object->inherits(\"" << parameter.type.name << "Wrapper\")) {";
  384. out() << " interpreter.throw_exception<JS::TypeError>(JS::ErrorType::NotA, \"" << parameter.type.name << "\");";
  385. generate_return();
  386. out() << " }";
  387. out() << " auto& " << cpp_name << " = static_cast<" << parameter.type.name << "Wrapper*>(" << cpp_name << "_object)->impl();";
  388. }
  389. };
  390. auto generate_arguments = [&](auto& parameters, auto& arguments_builder, bool return_void = false) {
  391. Vector<String> parameter_names;
  392. size_t argument_index = 0;
  393. for (auto& parameter : parameters) {
  394. parameter_names.append(snake_name(parameter.name));
  395. out() << " auto arg" << argument_index << " = interpreter.argument(" << argument_index << ");";
  396. generate_to_cpp(parameter, "arg", argument_index, snake_name(parameter.name), return_void);
  397. ++argument_index;
  398. }
  399. arguments_builder.join(", ", parameter_names);
  400. };
  401. auto generate_return_statement = [&](auto& return_type) {
  402. if (return_type.name == "void") {
  403. out() << " return JS::js_undefined();";
  404. return;
  405. }
  406. if (return_type.nullable) {
  407. if (return_type.name == "DOMString") {
  408. out() << " if (retval.is_null())";
  409. } else {
  410. out() << " if (!retval)";
  411. }
  412. out() << " return JS::js_null();";
  413. }
  414. if (return_type.name == "DOMString") {
  415. out() << " return JS::js_string(interpreter, retval);";
  416. } else if (return_type.name == "ArrayFromVector") {
  417. // FIXME: Remove this fake type hack once it's no longer needed.
  418. // Basically once we have NodeList we can throw this out.
  419. out() << " auto* new_array = JS::Array::create(global_object);";
  420. out() << " for (auto& element : retval) {";
  421. out() << " new_array->indexed_properties().append(wrap(interpreter.heap(), element));";
  422. out() << " }";
  423. out() << " return new_array;";
  424. } else if (return_type.name == "long") {
  425. out() << " return JS::Value(retval);";
  426. } else {
  427. out() << " return wrap(interpreter.heap(), const_cast<" << return_type.name << "&>(*retval));";
  428. }
  429. };
  430. // Implementation: Attributes
  431. for (auto& attribute : interface.attributes) {
  432. out() << "JS_DEFINE_NATIVE_GETTER(" << wrapper_class << "::" << attribute.getter_callback_name << ")";
  433. out() << "{";
  434. out() << " auto* impl = impl_from(interpreter, global_object);";
  435. out() << " if (!impl)";
  436. out() << " return {};";
  437. out() << " auto retval = impl->" << snake_name(attribute.name) << "();";
  438. generate_return_statement(attribute.type);
  439. out() << "}";
  440. if (!attribute.readonly) {
  441. out() << "JS_DEFINE_NATIVE_SETTER(" << wrapper_class << "::" << attribute.setter_callback_name << ")";
  442. out() << "{";
  443. out() << " auto* impl = impl_from(interpreter, global_object);";
  444. out() << " if (!impl)";
  445. out() << " return;";
  446. generate_to_cpp(attribute, "value", "", "cpp_value", true);
  447. out() << " impl->set_" << snake_name(attribute.name) << "(cpp_value);";
  448. out() << "}";
  449. }
  450. }
  451. // Implementation: Functions
  452. for (auto& function : interface.functions) {
  453. out() << "JS_DEFINE_NATIVE_FUNCTION(" << wrapper_class << "::" << snake_name(function.name) << ")";
  454. out() << "{";
  455. out() << " auto* impl = impl_from(interpreter, global_object);";
  456. out() << " if (!impl)";
  457. out() << " return {};";
  458. out() << " if (interpreter.argument_count() < " << function.length() << ")";
  459. out() << " return interpreter.throw_exception<JS::TypeError>(JS::ErrorType::BadArgCountMany, \"" << function.name << "\", \"" << function.length() << "\");";
  460. StringBuilder arguments_builder;
  461. generate_arguments(function.parameters, arguments_builder);
  462. if (function.return_type.name != "void") {
  463. out() << " auto retval = impl->" << snake_name(function.name) << "(" << arguments_builder.to_string() << ");";
  464. } else {
  465. out() << " impl->" << snake_name(function.name) << "(" << arguments_builder.to_string() << ");";
  466. }
  467. generate_return_statement(function.return_type);
  468. out() << "}";
  469. }
  470. out() << "}";
  471. out() << "}";
  472. }