WrapperGenerator.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/Debug.h>
  29. #include <AK/GenericLexer.h>
  30. #include <AK/HashMap.h>
  31. #include <AK/LexicalPath.h>
  32. #include <AK/SourceGenerator.h>
  33. #include <AK/StringBuilder.h>
  34. #include <LibCore/ArgsParser.h>
  35. #include <LibCore/File.h>
  36. #include <ctype.h>
  37. static String make_input_acceptable_cpp(const String& input)
  38. {
  39. if (input.is_one_of("class", "template", "for", "default", "char", "namespace")) {
  40. StringBuilder builder;
  41. builder.append(input);
  42. builder.append('_');
  43. return builder.to_string();
  44. }
  45. String input_without_dashes = input;
  46. input_without_dashes.replace("-", "_");
  47. return input_without_dashes;
  48. }
  49. static void report_parsing_error(StringView message, StringView filename, StringView input, size_t offset)
  50. {
  51. // FIXME: Spaghetti code ahead.
  52. size_t lineno = 1;
  53. size_t colno = 1;
  54. size_t start_line = 0;
  55. size_t line_length = 0;
  56. for (size_t index = 0; index < input.length(); ++index) {
  57. if (offset == index)
  58. colno = index - start_line + 1;
  59. if (input[index] == '\n') {
  60. if (index >= offset)
  61. break;
  62. start_line = index + 1;
  63. line_length = 0;
  64. ++lineno;
  65. } else {
  66. ++line_length;
  67. }
  68. }
  69. StringBuilder error_message;
  70. error_message.appendff("{}\n", input.substring_view(start_line, line_length));
  71. for (size_t i = 0; i < colno - 1; ++i)
  72. error_message.append(' ');
  73. error_message.append("\033[1;31m^\n");
  74. error_message.appendff("{}:{}: error: {}\033[0m\n", filename, lineno, message);
  75. warnln("{}", error_message.string_view());
  76. exit(EXIT_FAILURE);
  77. }
  78. namespace IDL {
  79. template<typename FunctionType>
  80. static size_t get_function_length(FunctionType& function)
  81. {
  82. size_t length = 0;
  83. for (auto& parameter : function.parameters) {
  84. if (!parameter.optional)
  85. length++;
  86. }
  87. return length;
  88. }
  89. struct Type {
  90. String name;
  91. bool nullable { false };
  92. bool is_string() const { return name.is_one_of("DOMString", "USVString", "CSSOMString"); }
  93. };
  94. struct Parameter {
  95. Type type;
  96. String name;
  97. bool optional { false };
  98. };
  99. struct Function {
  100. Type return_type;
  101. String name;
  102. Vector<Parameter> parameters;
  103. HashMap<String, String> extended_attributes;
  104. size_t length() const { return get_function_length(*this); }
  105. };
  106. struct Constructor {
  107. String name;
  108. Vector<Parameter> parameters;
  109. size_t length() const { return get_function_length(*this); }
  110. };
  111. struct Constant {
  112. Type type;
  113. String name;
  114. String value;
  115. };
  116. struct Attribute {
  117. bool readonly { false };
  118. Type type;
  119. String name;
  120. HashMap<String, String> extended_attributes;
  121. // Added for convenience after parsing
  122. String getter_callback_name;
  123. String setter_callback_name;
  124. };
  125. struct Interface {
  126. String name;
  127. String parent_name;
  128. HashMap<String, String> extended_attributes;
  129. Vector<Attribute> attributes;
  130. Vector<Constant> constants;
  131. Vector<Constructor> constructors;
  132. Vector<Function> functions;
  133. // Added for convenience after parsing
  134. String wrapper_class;
  135. String wrapper_base_class;
  136. String fully_qualified_name;
  137. String constructor_class;
  138. String prototype_class;
  139. String prototype_base_class;
  140. };
  141. static OwnPtr<Interface> parse_interface(StringView filename, const StringView& input)
  142. {
  143. auto interface = make<Interface>();
  144. GenericLexer lexer(input);
  145. auto assert_specific = [&](char ch) {
  146. if (!lexer.consume_specific(ch))
  147. report_parsing_error(String::formatted("expected '{}'", ch), filename, input, lexer.tell());
  148. };
  149. auto consume_whitespace = [&] {
  150. bool consumed = true;
  151. while (consumed) {
  152. consumed = lexer.consume_while([](char ch) { return isspace(ch); }).length() > 0;
  153. if (lexer.consume_specific("//")) {
  154. lexer.consume_until('\n');
  155. consumed = true;
  156. }
  157. }
  158. };
  159. auto assert_string = [&](const StringView& expected) {
  160. if (!lexer.consume_specific(expected))
  161. report_parsing_error(String::formatted("expected '{}'", expected), filename, input, lexer.tell());
  162. };
  163. auto parse_extended_attributes = [&] {
  164. HashMap<String, String> extended_attributes;
  165. for (;;) {
  166. consume_whitespace();
  167. if (lexer.consume_specific(']'))
  168. break;
  169. auto name = lexer.consume_until([](auto ch) { return ch == ']' || ch == '=' || ch == ','; });
  170. if (lexer.consume_specific('=')) {
  171. auto value = lexer.consume_until([](auto ch) { return ch == ']' || ch == ','; });
  172. extended_attributes.set(name, value);
  173. } else {
  174. extended_attributes.set(name, {});
  175. }
  176. lexer.consume_specific(',');
  177. }
  178. consume_whitespace();
  179. return extended_attributes;
  180. };
  181. if (lexer.consume_specific('['))
  182. interface->extended_attributes = parse_extended_attributes();
  183. assert_string("interface");
  184. consume_whitespace();
  185. interface->name = lexer.consume_until([](auto ch) { return isspace(ch); });
  186. consume_whitespace();
  187. if (lexer.consume_specific(':')) {
  188. consume_whitespace();
  189. interface->parent_name = lexer.consume_until([](auto ch) { return isspace(ch); });
  190. consume_whitespace();
  191. }
  192. assert_specific('{');
  193. auto parse_type = [&] {
  194. bool unsigned_ = lexer.consume_specific("unsigned");
  195. if (unsigned_)
  196. consume_whitespace();
  197. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '?'; });
  198. auto nullable = lexer.consume_specific('?');
  199. StringBuilder builder;
  200. if (unsigned_)
  201. builder.append("unsigned ");
  202. builder.append(name);
  203. return Type { builder.to_string(), nullable };
  204. };
  205. auto parse_attribute = [&](HashMap<String, String>& extended_attributes) {
  206. bool readonly = lexer.consume_specific("readonly");
  207. if (readonly)
  208. consume_whitespace();
  209. if (lexer.consume_specific("attribute"))
  210. consume_whitespace();
  211. auto type = parse_type();
  212. consume_whitespace();
  213. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ';'; });
  214. consume_whitespace();
  215. assert_specific(';');
  216. Attribute attribute;
  217. attribute.readonly = readonly;
  218. attribute.type = type;
  219. attribute.name = name;
  220. attribute.getter_callback_name = String::formatted("{}_getter", attribute.name.to_snakecase());
  221. attribute.setter_callback_name = String::formatted("{}_setter", attribute.name.to_snakecase());
  222. attribute.extended_attributes = move(extended_attributes);
  223. interface->attributes.append(move(attribute));
  224. };
  225. auto parse_constant = [&] {
  226. lexer.consume_specific("const");
  227. consume_whitespace();
  228. Constant constant;
  229. constant.type = parse_type();
  230. consume_whitespace();
  231. constant.name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '='; });
  232. consume_whitespace();
  233. lexer.consume_specific('=');
  234. consume_whitespace();
  235. constant.value = lexer.consume_while([](auto ch) { return !isspace(ch) && ch != ';'; });
  236. consume_whitespace();
  237. assert_specific(';');
  238. interface->constants.append(move(constant));
  239. };
  240. auto parse_parameters = [&] {
  241. consume_whitespace();
  242. Vector<Parameter> parameters;
  243. for (;;) {
  244. if (lexer.next_is(')'))
  245. break;
  246. bool optional = lexer.consume_specific("optional");
  247. if (optional)
  248. consume_whitespace();
  249. auto type = parse_type();
  250. consume_whitespace();
  251. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ',' || ch == ')'; });
  252. parameters.append({ move(type), move(name), optional });
  253. if (lexer.next_is(')'))
  254. break;
  255. assert_specific(',');
  256. consume_whitespace();
  257. }
  258. return parameters;
  259. };
  260. auto parse_function = [&](HashMap<String, String>& extended_attributes) {
  261. auto return_type = parse_type();
  262. consume_whitespace();
  263. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '('; });
  264. consume_whitespace();
  265. assert_specific('(');
  266. auto parameters = parse_parameters();
  267. assert_specific(')');
  268. consume_whitespace();
  269. assert_specific(';');
  270. interface->functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  271. };
  272. auto parse_constructor = [&] {
  273. assert_string("constructor");
  274. consume_whitespace();
  275. assert_specific('(');
  276. auto parameters = parse_parameters();
  277. assert_specific(')');
  278. consume_whitespace();
  279. assert_specific(';');
  280. interface->constructors.append(Constructor { interface->name, move(parameters) });
  281. };
  282. for (;;) {
  283. HashMap<String, String> extended_attributes;
  284. consume_whitespace();
  285. if (lexer.consume_specific('}')) {
  286. consume_whitespace();
  287. assert_specific(';');
  288. break;
  289. }
  290. if (lexer.consume_specific('[')) {
  291. extended_attributes = parse_extended_attributes();
  292. }
  293. if (lexer.next_is("constructor")) {
  294. parse_constructor();
  295. continue;
  296. }
  297. if (lexer.next_is("const")) {
  298. parse_constant();
  299. continue;
  300. }
  301. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  302. parse_attribute(extended_attributes);
  303. continue;
  304. }
  305. parse_function(extended_attributes);
  306. }
  307. interface->wrapper_class = String::formatted("{}Wrapper", interface->name);
  308. interface->wrapper_base_class = String::formatted("{}Wrapper", interface->parent_name.is_empty() ? String::empty() : interface->parent_name);
  309. interface->constructor_class = String::formatted("{}Constructor", interface->name);
  310. interface->prototype_class = String::formatted("{}Prototype", interface->name);
  311. interface->prototype_base_class = String::formatted("{}Prototype", interface->parent_name.is_empty() ? "Object" : interface->parent_name);
  312. return interface;
  313. }
  314. }
  315. static void generate_constructor_header(const IDL::Interface&);
  316. static void generate_constructor_implementation(const IDL::Interface&);
  317. static void generate_prototype_header(const IDL::Interface&);
  318. static void generate_prototype_implementation(const IDL::Interface&);
  319. static void generate_header(const IDL::Interface&);
  320. static void generate_implementation(const IDL::Interface&);
  321. int main(int argc, char** argv)
  322. {
  323. Core::ArgsParser args_parser;
  324. const char* path = nullptr;
  325. bool header_mode = false;
  326. bool implementation_mode = false;
  327. bool constructor_header_mode = false;
  328. bool constructor_implementation_mode = false;
  329. bool prototype_header_mode = false;
  330. bool prototype_implementation_mode = false;
  331. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  332. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  333. args_parser.add_option(constructor_header_mode, "Generate the constructor .h file", "constructor-header", 'C');
  334. args_parser.add_option(constructor_implementation_mode, "Generate the constructor .cpp file", "constructor-implementation", 'O');
  335. args_parser.add_option(prototype_header_mode, "Generate the prototype .h file", "prototype-header", 'P');
  336. args_parser.add_option(prototype_implementation_mode, "Generate the prototype .cpp file", "prototype-implementation", 'R');
  337. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  338. args_parser.parse(argc, argv);
  339. auto file_or_error = Core::File::open(path, Core::IODevice::ReadOnly);
  340. if (file_or_error.is_error()) {
  341. fprintf(stderr, "Cannot open %s\n", path);
  342. return 1;
  343. }
  344. LexicalPath lexical_path(path);
  345. auto namespace_ = lexical_path.parts().at(lexical_path.parts().size() - 2);
  346. auto data = file_or_error.value()->read_all();
  347. auto interface = IDL::parse_interface(path, data);
  348. if (!interface) {
  349. warnln("Cannot parse {}", path);
  350. return 1;
  351. }
  352. if (namespace_.is_one_of("CSS", "DOM", "HTML", "UIEvents", "HighResolutionTime", "NavigationTiming", "SVG", "XHR")) {
  353. StringBuilder builder;
  354. builder.append(namespace_);
  355. builder.append("::");
  356. builder.append(interface->name);
  357. interface->fully_qualified_name = builder.to_string();
  358. } else {
  359. interface->fully_qualified_name = interface->name;
  360. }
  361. if constexpr (WRAPPER_GENERATOR_DEBUG) {
  362. dbgln("Attributes:");
  363. for (auto& attribute : interface->attributes) {
  364. dbgln(" {}{}{} {}",
  365. attribute.readonly ? "readonly " : "",
  366. attribute.type.name,
  367. attribute.type.nullable ? "?" : "",
  368. attribute.name);
  369. }
  370. dbgln("Functions:");
  371. for (auto& function : interface->functions) {
  372. dbgln(" {}{} {}",
  373. function.return_type.name,
  374. function.return_type.nullable ? "?" : "",
  375. function.name);
  376. for (auto& parameter : function.parameters) {
  377. dbgln(" {}{} {}",
  378. parameter.type.name,
  379. parameter.type.nullable ? "?" : "",
  380. parameter.name);
  381. }
  382. }
  383. }
  384. if (header_mode)
  385. generate_header(*interface);
  386. if (implementation_mode)
  387. generate_implementation(*interface);
  388. if (constructor_header_mode)
  389. generate_constructor_header(*interface);
  390. if (constructor_implementation_mode)
  391. generate_constructor_implementation(*interface);
  392. if (prototype_header_mode)
  393. generate_prototype_header(*interface);
  394. if (prototype_implementation_mode)
  395. generate_prototype_implementation(*interface);
  396. return 0;
  397. }
  398. static bool should_emit_wrapper_factory(const IDL::Interface& interface)
  399. {
  400. // FIXME: This is very hackish.
  401. if (interface.name == "Event")
  402. return false;
  403. if (interface.name == "EventTarget")
  404. return false;
  405. if (interface.name == "Node")
  406. return false;
  407. if (interface.name == "Text")
  408. return false;
  409. if (interface.name == "Document")
  410. return false;
  411. if (interface.name == "DocumentType")
  412. return false;
  413. if (interface.name.ends_with("Element"))
  414. return false;
  415. return true;
  416. }
  417. static bool is_wrappable_type(const IDL::Type& type)
  418. {
  419. if (type.name == "Node")
  420. return true;
  421. if (type.name == "Document")
  422. return true;
  423. if (type.name == "Text")
  424. return true;
  425. if (type.name == "DocumentType")
  426. return true;
  427. if (type.name.ends_with("Element"))
  428. return true;
  429. if (type.name == "ImageData")
  430. return true;
  431. return false;
  432. }
  433. template<typename ParameterType>
  434. static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter, const String& js_name, const String& js_suffix, const String& cpp_name, bool return_void = false, bool legacy_null_to_empty_string = false, bool optional = false)
  435. {
  436. auto scoped_generator = generator.fork();
  437. scoped_generator.set("cpp_name", make_input_acceptable_cpp(cpp_name));
  438. scoped_generator.set("js_name", js_name);
  439. scoped_generator.set("js_suffix", js_suffix);
  440. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  441. scoped_generator.set("parameter.type.name", parameter.type.name);
  442. if (return_void)
  443. scoped_generator.set("return_statement", "return;");
  444. else
  445. scoped_generator.set("return_statement", "return {};");
  446. // FIXME: Add support for optional to all types
  447. if (parameter.type.is_string()) {
  448. if (!optional) {
  449. scoped_generator.append(R"~~~(
  450. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  451. if (vm.exception())
  452. @return_statement@
  453. )~~~");
  454. } else {
  455. scoped_generator.append(R"~~~(
  456. String @cpp_name@;
  457. if (!@js_name@@js_suffix@.is_undefined()) {
  458. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  459. if (vm.exception())
  460. @return_statement@
  461. }
  462. )~~~");
  463. }
  464. } else if (parameter.type.name == "EventListener") {
  465. scoped_generator.append(R"~~~(
  466. if (!@js_name@@js_suffix@.is_function()) {
  467. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "Function");
  468. @return_statement@
  469. }
  470. auto @cpp_name@ = adopt(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  471. )~~~");
  472. } else if (is_wrappable_type(parameter.type)) {
  473. scoped_generator.append(R"~~~(
  474. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  475. if (vm.exception())
  476. @return_statement@
  477. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  478. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  479. @return_statement@
  480. }
  481. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  482. )~~~");
  483. } else if (parameter.type.name == "double") {
  484. scoped_generator.append(R"~~~(
  485. auto @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  486. if (vm.exception())
  487. @return_statement@
  488. )~~~");
  489. } else if (parameter.type.name == "boolean") {
  490. scoped_generator.append(R"~~~(
  491. auto @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  492. )~~~");
  493. } else if (parameter.type.name == "unsigned long") {
  494. scoped_generator.append(R"~~~(
  495. auto @cpp_name@ = @js_name@@js_suffix@.to_u32(global_object);
  496. if (vm.exception())
  497. @return_statement@
  498. )~~~");
  499. } else if (parameter.type.name == "EventHandler") {
  500. // x.onfoo = function() { ... }
  501. scoped_generator.append(R"~~~(
  502. HTML::EventHandler @cpp_name@;
  503. if (@js_name@@js_suffix@.is_function()) {
  504. @cpp_name@.callback = JS::make_handle(&@js_name@@js_suffix@.as_function());
  505. } else if (@js_name@@js_suffix@.is_string()) {
  506. @cpp_name@.string = @js_name@@js_suffix@.as_string().string();
  507. } else {
  508. @return_statement@
  509. }
  510. )~~~");
  511. } else {
  512. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  513. VERIFY_NOT_REACHED();
  514. }
  515. };
  516. template<typename FunctionType>
  517. static void generate_argument_count_check(SourceGenerator& generator, FunctionType& function)
  518. {
  519. auto argument_count_check_generator = generator.fork();
  520. argument_count_check_generator.set("function.name", function.name);
  521. argument_count_check_generator.set("function.nargs", String::number(function.length()));
  522. if (function.length() == 0)
  523. return;
  524. if (function.length() == 1) {
  525. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  526. argument_count_check_generator.set(".arg_count_suffix", "");
  527. } else {
  528. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  529. argument_count_check_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  530. }
  531. argument_count_check_generator.append(R"~~~(
  532. if (vm.argument_count() < @function.nargs@) {
  533. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  534. return {};
  535. }
  536. )~~~");
  537. };
  538. static void generate_arguments(SourceGenerator& generator, const Vector<IDL::Parameter>& parameters, StringBuilder& arguments_builder, bool return_void = false)
  539. {
  540. auto arguments_generator = generator.fork();
  541. Vector<String> parameter_names;
  542. size_t argument_index = 0;
  543. for (auto& parameter : parameters) {
  544. parameter_names.append(make_input_acceptable_cpp(parameter.name.to_snakecase()));
  545. arguments_generator.set("argument.index", String::number(argument_index));
  546. arguments_generator.append(R"~~~(
  547. auto arg@argument.index@ = vm.argument(@argument.index@);
  548. )~~~");
  549. // FIXME: Parameters can have [LegacyNullToEmptyString] attached.
  550. generate_to_cpp(generator, parameter, "arg", String::number(argument_index), parameter.name.to_snakecase(), return_void, false, parameter.optional);
  551. ++argument_index;
  552. }
  553. arguments_builder.join(", ", parameter_names);
  554. };
  555. static void generate_header(const IDL::Interface& interface)
  556. {
  557. StringBuilder builder;
  558. SourceGenerator generator { builder };
  559. generator.set("name", interface.name);
  560. generator.set("fully_qualified_name", interface.fully_qualified_name);
  561. generator.set("wrapper_base_class", interface.wrapper_base_class);
  562. generator.set("wrapper_class", interface.wrapper_class);
  563. generator.set("wrapper_class:snakecase", interface.wrapper_class.to_snakecase());
  564. generator.append(R"~~~(
  565. #pragma once
  566. #include <LibWeb/Bindings/Wrapper.h>
  567. // FIXME: This is very strange.
  568. #if __has_include(<LibWeb/CSS/@name@.h>)
  569. # include <LibWeb/CSS/@name@.h>
  570. #elif __has_include(<LibWeb/DOM/@name@.h>)
  571. # include <LibWeb/DOM/@name@.h>
  572. #elif __has_include(<LibWeb/HTML/@name@.h>)
  573. # include <LibWeb/HTML/@name@.h>
  574. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  575. # include <LibWeb/UIEvents/@name@.h>
  576. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  577. # include <LibWeb/HighResolutionTime/@name@.h>
  578. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  579. # include <LibWeb/NavigationTiming/@name@.h>
  580. #elif __has_include(<LibWeb/SVG/@name@.h>)
  581. # include <LibWeb/SVG/@name@.h>
  582. #elif __has_include(<LibWeb/XHR/@name@.h>)
  583. # include <LibWeb/XHR/@name@.h>
  584. #endif
  585. )~~~");
  586. if (interface.wrapper_base_class != "Wrapper") {
  587. generator.append(R"~~~(
  588. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  589. )~~~");
  590. }
  591. generator.append(R"~~~(
  592. namespace Web::Bindings {
  593. class @wrapper_class@ : public @wrapper_base_class@ {
  594. JS_OBJECT(@wrapper_class@, @wrapper_base_class@);
  595. public:
  596. static @wrapper_class@* create(JS::GlobalObject&, @fully_qualified_name@&);
  597. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  598. virtual void initialize(JS::GlobalObject&) override;
  599. virtual ~@wrapper_class@() override;
  600. )~~~");
  601. if (interface.extended_attributes.contains("CustomGet")) {
  602. generator.append(R"~~~(
  603. virtual JS::Value get(const JS::PropertyName&, JS::Value receiver = {}) const override;
  604. )~~~");
  605. }
  606. if (interface.extended_attributes.contains("CustomPut")) {
  607. generator.append(R"~~~(
  608. virtual bool put(const JS::PropertyName&, JS::Value, JS::Value receiver = {}) override;
  609. )~~~");
  610. }
  611. if (interface.wrapper_base_class == "Wrapper") {
  612. generator.append(R"~~~(
  613. @fully_qualified_name@& impl() { return *m_impl; }
  614. const @fully_qualified_name@& impl() const { return *m_impl; }
  615. )~~~");
  616. } else {
  617. generator.append(R"~~~(
  618. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  619. const @fully_qualified_name@& impl() const { return static_cast<const @fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  620. )~~~");
  621. }
  622. generator.append(R"~~~(
  623. private:
  624. )~~~");
  625. if (interface.wrapper_base_class == "Wrapper") {
  626. generator.append(R"~~~(
  627. NonnullRefPtr<@fully_qualified_name@> m_impl;
  628. )~~~");
  629. }
  630. generator.append(R"~~~(
  631. };
  632. )~~~");
  633. if (should_emit_wrapper_factory(interface)) {
  634. generator.append(R"~~~(
  635. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  636. )~~~");
  637. }
  638. generator.append(R"~~~(
  639. } // namespace Web::Bindings
  640. )~~~");
  641. outln("{}", generator.as_string_view());
  642. }
  643. void generate_implementation(const IDL::Interface& interface)
  644. {
  645. StringBuilder builder;
  646. SourceGenerator generator { builder };
  647. generator.set("name", interface.name);
  648. generator.set("wrapper_class", interface.wrapper_class);
  649. generator.set("wrapper_base_class", interface.wrapper_base_class);
  650. generator.set("prototype_class", interface.prototype_class);
  651. generator.set("fully_qualified_name", interface.fully_qualified_name);
  652. generator.append(R"~~~(
  653. #include <AK/FlyString.h>
  654. #include <LibJS/Runtime/Array.h>
  655. #include <LibJS/Runtime/Error.h>
  656. #include <LibJS/Runtime/Function.h>
  657. #include <LibJS/Runtime/GlobalObject.h>
  658. #include <LibJS/Runtime/Uint8ClampedArray.h>
  659. #include <LibJS/Runtime/Value.h>
  660. #include <LibWeb/Bindings/@prototype_class@.h>
  661. #include <LibWeb/Bindings/@wrapper_class@.h>
  662. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  663. #include <LibWeb/Bindings/CommentWrapper.h>
  664. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  665. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  666. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  667. #include <LibWeb/Bindings/DocumentWrapper.h>
  668. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  669. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  670. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  671. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  672. #include <LibWeb/Bindings/ImageDataWrapper.h>
  673. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  674. #include <LibWeb/Bindings/TextWrapper.h>
  675. #include <LibWeb/Bindings/WindowObject.h>
  676. #include <LibWeb/DOM/Element.h>
  677. #include <LibWeb/DOM/EventListener.h>
  678. #include <LibWeb/HTML/HTMLElement.h>
  679. #include <LibWeb/Origin.h>
  680. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  681. using namespace Web::CSS;
  682. using namespace Web::DOM;
  683. using namespace Web::HTML;
  684. namespace Web::Bindings {
  685. @wrapper_class@* @wrapper_class@::create(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  686. {
  687. return global_object.heap().allocate<@wrapper_class@>(global_object, global_object, impl);
  688. }
  689. )~~~");
  690. if (interface.wrapper_base_class == "Wrapper") {
  691. generator.append(R"~~~(
  692. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  693. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  694. , m_impl(impl)
  695. {
  696. }
  697. )~~~");
  698. } else {
  699. generator.append(R"~~~(
  700. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  701. : @wrapper_base_class@(global_object, impl)
  702. {
  703. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  704. }
  705. )~~~");
  706. }
  707. generator.append(R"~~~(
  708. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  709. {
  710. @wrapper_base_class@::initialize(global_object);
  711. }
  712. @wrapper_class@::~@wrapper_class@()
  713. {
  714. }
  715. )~~~");
  716. if (should_emit_wrapper_factory(interface)) {
  717. generator.append(R"~~~(
  718. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  719. {
  720. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  721. }
  722. )~~~");
  723. }
  724. generator.append(R"~~~(
  725. } // namespace Web::Bindings
  726. )~~~");
  727. outln("{}", generator.as_string_view());
  728. }
  729. static void generate_constructor_header(const IDL::Interface& interface)
  730. {
  731. StringBuilder builder;
  732. SourceGenerator generator { builder };
  733. generator.set("name", interface.name);
  734. generator.set("fully_qualified_name", interface.fully_qualified_name);
  735. generator.set("constructor_class", interface.constructor_class);
  736. generator.set("constructor_class:snakecase", interface.constructor_class.to_snakecase());
  737. generator.append(R"~~~(
  738. #pragma once
  739. #include <LibJS/Runtime/NativeFunction.h>
  740. namespace Web::Bindings {
  741. class @constructor_class@ : public JS::NativeFunction {
  742. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  743. public:
  744. explicit @constructor_class@(JS::GlobalObject&);
  745. virtual void initialize(JS::GlobalObject&) override;
  746. virtual ~@constructor_class@() override;
  747. virtual JS::Value call() override;
  748. virtual JS::Value construct(JS::Function& new_target) override;
  749. private:
  750. virtual bool has_constructor() const override { return true; }
  751. };
  752. } // namespace Web::Bindings
  753. )~~~");
  754. outln("{}", generator.as_string_view());
  755. }
  756. void generate_constructor_implementation(const IDL::Interface& interface)
  757. {
  758. StringBuilder builder;
  759. SourceGenerator generator { builder };
  760. generator.set("name", interface.name);
  761. generator.set("prototype_class", interface.prototype_class);
  762. generator.set("wrapper_class", interface.wrapper_class);
  763. generator.set("constructor_class", interface.constructor_class);
  764. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  765. generator.set("fully_qualified_name", interface.fully_qualified_name);
  766. generator.append(R"~~~(
  767. #include <LibJS/Heap/Heap.h>
  768. #include <LibJS/Runtime/GlobalObject.h>
  769. #include <LibWeb/Bindings/@constructor_class@.h>
  770. #include <LibWeb/Bindings/@prototype_class@.h>
  771. #include <LibWeb/Bindings/@wrapper_class@.h>
  772. #include <LibWeb/Bindings/WindowObject.h>
  773. #if __has_include(<LibWeb/CSS/@name@.h>)
  774. # include <LibWeb/CSS/@name@.h>
  775. #elif __has_include(<LibWeb/DOM/@name@.h>)
  776. # include <LibWeb/DOM/@name@.h>
  777. #elif __has_include(<LibWeb/HTML/@name@.h>)
  778. # include <LibWeb/HTML/@name@.h>
  779. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  780. # include <LibWeb/UIEvents/@name@.h>
  781. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  782. # include <LibWeb/HighResolutionTime/@name@.h>
  783. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  784. # include <LibWeb/NavigationTiming/@name@.h>
  785. #elif __has_include(<LibWeb/SVG/@name@.h>)
  786. # include <LibWeb/SVG/@name@.h>
  787. #elif __has_include(<LibWeb/XHR/@name@.h>)
  788. # include <LibWeb/XHR/@name@.h>
  789. #endif
  790. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  791. using namespace Web::CSS;
  792. using namespace Web::DOM;
  793. using namespace Web::HTML;
  794. namespace Web::Bindings {
  795. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  796. : NativeFunction(*global_object.function_prototype())
  797. {
  798. }
  799. @constructor_class@::~@constructor_class@()
  800. {
  801. }
  802. JS::Value @constructor_class@::call()
  803. {
  804. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  805. return {};
  806. }
  807. JS::Value @constructor_class@::construct(Function&)
  808. {
  809. )~~~");
  810. if (interface.constructors.is_empty()) {
  811. // No constructor
  812. generator.set("constructor.length", "0");
  813. generator.append(R"~~~(
  814. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::NotAConstructor, "@name@");
  815. return {};
  816. )~~~");
  817. } else if (interface.constructors.size() == 1) {
  818. // Single constructor
  819. auto& constructor = interface.constructors[0];
  820. generator.set("constructor.length", String::number(constructor.length()));
  821. generator.append(R"~~~(
  822. [[maybe_unused]] auto& vm = this->vm();
  823. auto& global_object = this->global_object();
  824. auto& window = static_cast<WindowObject&>(global_object);
  825. )~~~");
  826. if (!constructor.parameters.is_empty()) {
  827. generate_argument_count_check(generator, constructor);
  828. StringBuilder arguments_builder;
  829. generate_arguments(generator, constructor.parameters, arguments_builder);
  830. generator.set(".constructor_arguments", arguments_builder.string_view());
  831. generator.append(R"~~~(
  832. auto impl = @fully_qualified_name@::create_with_global_object(window, @.constructor_arguments@);
  833. )~~~");
  834. } else {
  835. generator.append(R"~~~(
  836. auto impl = @fully_qualified_name@::create_with_global_object(window);
  837. )~~~");
  838. }
  839. generator.append(R"~~~(
  840. return @wrapper_class@::create(global_object, impl);
  841. )~~~");
  842. } else {
  843. // Multiple constructor overloads - can't do that yet.
  844. TODO();
  845. }
  846. generator.append(R"~~~(
  847. }
  848. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  849. {
  850. auto& vm = this->vm();
  851. auto& window = static_cast<WindowObject&>(global_object);
  852. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  853. NativeFunction::initialize(global_object);
  854. define_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  855. define_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  856. )~~~");
  857. for (auto& constant : interface.constants) {
  858. auto constant_generator = generator.fork();
  859. constant_generator.set("constant.name", constant.name);
  860. constant_generator.set("constant.value", constant.value);
  861. constant_generator.append(R"~~~(
  862. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  863. )~~~");
  864. }
  865. generator.append(R"~~~(
  866. }
  867. } // namespace Web::Bindings
  868. )~~~");
  869. outln("{}", generator.as_string_view());
  870. }
  871. static void generate_prototype_header(const IDL::Interface& interface)
  872. {
  873. StringBuilder builder;
  874. SourceGenerator generator { builder };
  875. generator.set("name", interface.name);
  876. generator.set("fully_qualified_name", interface.fully_qualified_name);
  877. generator.set("prototype_class", interface.prototype_class);
  878. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  879. generator.append(R"~~~(
  880. #pragma once
  881. #include <LibJS/Runtime/Object.h>
  882. namespace Web::Bindings {
  883. class @prototype_class@ : public JS::Object {
  884. JS_OBJECT(@prototype_class@, JS::Object);
  885. public:
  886. explicit @prototype_class@(JS::GlobalObject&);
  887. virtual void initialize(JS::GlobalObject&) override;
  888. virtual ~@prototype_class@() override;
  889. private:
  890. )~~~");
  891. for (auto& function : interface.functions) {
  892. auto function_generator = generator.fork();
  893. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  894. function_generator.append(R"~~~(
  895. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  896. )~~~");
  897. }
  898. for (auto& attribute : interface.attributes) {
  899. auto attribute_generator = generator.fork();
  900. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  901. attribute_generator.append(R"~~~(
  902. JS_DECLARE_NATIVE_GETTER(@attribute.name:snakecase@_getter);
  903. )~~~");
  904. if (!attribute.readonly) {
  905. attribute_generator.append(R"~~~(
  906. JS_DECLARE_NATIVE_SETTER(@attribute.name:snakecase@_setter);
  907. )~~~");
  908. }
  909. }
  910. generator.append(R"~~~(
  911. };
  912. } // namespace Web::Bindings
  913. )~~~");
  914. outln("{}", generator.as_string_view());
  915. }
  916. void generate_prototype_implementation(const IDL::Interface& interface)
  917. {
  918. StringBuilder builder;
  919. SourceGenerator generator { builder };
  920. generator.set("name", interface.name);
  921. generator.set("parent_name", interface.parent_name);
  922. generator.set("prototype_class", interface.prototype_class);
  923. generator.set("prototype_base_class", interface.prototype_base_class);
  924. generator.set("wrapper_class", interface.wrapper_class);
  925. generator.set("constructor_class", interface.constructor_class);
  926. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  927. generator.set("fully_qualified_name", interface.fully_qualified_name);
  928. generator.append(R"~~~(
  929. #include <AK/Function.h>
  930. #include <LibJS/Runtime/Array.h>
  931. #include <LibJS/Runtime/Error.h>
  932. #include <LibJS/Runtime/Function.h>
  933. #include <LibJS/Runtime/GlobalObject.h>
  934. #include <LibJS/Runtime/Uint8ClampedArray.h>
  935. #include <LibWeb/Bindings/@prototype_class@.h>
  936. #include <LibWeb/Bindings/@wrapper_class@.h>
  937. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  938. #include <LibWeb/Bindings/CSSStyleSheetWrapper.h>
  939. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  940. #include <LibWeb/Bindings/CommentWrapper.h>
  941. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  942. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  943. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  944. #include <LibWeb/Bindings/DocumentWrapper.h>
  945. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  946. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  947. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  948. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  949. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  950. #include <LibWeb/Bindings/ImageDataWrapper.h>
  951. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  952. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  953. #include <LibWeb/Bindings/RangeWrapper.h>
  954. #include <LibWeb/Bindings/StyleSheetListWrapper.h>
  955. #include <LibWeb/Bindings/TextWrapper.h>
  956. #include <LibWeb/Bindings/WindowObject.h>
  957. #include <LibWeb/DOM/Element.h>
  958. #include <LibWeb/DOM/EventListener.h>
  959. #include <LibWeb/DOM/Range.h>
  960. #include <LibWeb/DOM/Window.h>
  961. #include <LibWeb/HTML/EventHandler.h>
  962. #include <LibWeb/HTML/HTMLElement.h>
  963. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  964. #include <LibWeb/Origin.h>
  965. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  966. # include <LibWeb/Bindings/@prototype_base_class@.h>
  967. #endif
  968. #if __has_include(<LibWeb/CSS/@name@.h>)
  969. # include <LibWeb/CSS/@name@.h>
  970. #elif __has_include(<LibWeb/DOM/@name@.h>)
  971. # include <LibWeb/DOM/@name@.h>
  972. #elif __has_include(<LibWeb/HTML/@name@.h>)
  973. # include <LibWeb/HTML/@name@.h>
  974. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  975. # include <LibWeb/UIEvents/@name@.h>
  976. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  977. # include <LibWeb/HighResolutionTime/@name@.h>
  978. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  979. # include <LibWeb/NavigationTiming/@name@.h>
  980. #elif __has_include(<LibWeb/SVG/@name@.h>)
  981. # include <LibWeb/SVG/@name@.h>
  982. #elif __has_include(<LibWeb/XHR/@name@.h>)
  983. # include <LibWeb/XHR/@name@.h>
  984. #endif
  985. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  986. using namespace Web::CSS;
  987. using namespace Web::DOM;
  988. using namespace Web::HTML;
  989. using namespace Web::NavigationTiming;
  990. using namespace Web::XHR;
  991. namespace Web::Bindings {
  992. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  993. : Object(*global_object.object_prototype())
  994. {
  995. )~~~");
  996. if (interface.name == "DOMException") {
  997. // https://heycam.github.io/webidl/#es-DOMException-specialness
  998. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  999. generator.append(R"~~~(
  1000. set_prototype(global_object.error_prototype());
  1001. )~~~");
  1002. } else if (!interface.parent_name.is_empty()) {
  1003. generator.append(R"~~~(
  1004. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  1005. )~~~");
  1006. }
  1007. generator.append(R"~~~(
  1008. }
  1009. @prototype_class@::~@prototype_class@()
  1010. {
  1011. }
  1012. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  1013. {
  1014. [[maybe_unused]] auto& vm = this->vm();
  1015. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;
  1016. )~~~");
  1017. for (auto& attribute : interface.attributes) {
  1018. auto attribute_generator = generator.fork();
  1019. attribute_generator.set("attribute.name", attribute.name);
  1020. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1021. if (attribute.readonly)
  1022. attribute_generator.set("attribute.setter_callback", "nullptr");
  1023. else
  1024. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1025. attribute_generator.append(R"~~~(
  1026. define_native_property("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  1027. )~~~");
  1028. }
  1029. for (auto& constant : interface.constants) {
  1030. auto constant_generator = generator.fork();
  1031. constant_generator.set("constant.name", constant.name);
  1032. constant_generator.set("constant.value", constant.value);
  1033. constant_generator.append(R"~~~(
  1034. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1035. )~~~");
  1036. }
  1037. for (auto& function : interface.functions) {
  1038. auto function_generator = generator.fork();
  1039. function_generator.set("function.name", function.name);
  1040. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1041. function_generator.set("function.length", String::number(function.length()));
  1042. function_generator.append(R"~~~(
  1043. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1044. )~~~");
  1045. }
  1046. generator.append(R"~~~(
  1047. Object::initialize(global_object);
  1048. }
  1049. )~~~");
  1050. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  1051. generator.append(R"~~~(
  1052. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  1053. {
  1054. auto* this_object = vm.this_value(global_object).to_object(global_object);
  1055. if (!this_object)
  1056. return {};
  1057. )~~~");
  1058. if (interface.name == "EventTarget") {
  1059. generator.append(R"~~~(
  1060. if (is<WindowObject>(this_object)) {
  1061. return &static_cast<WindowObject*>(this_object)->impl();
  1062. }
  1063. )~~~");
  1064. }
  1065. generator.append(R"~~~(
  1066. if (!is<@wrapper_class@>(this_object)) {
  1067. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  1068. return nullptr;
  1069. }
  1070. return &static_cast<@wrapper_class@*>(this_object)->impl();
  1071. }
  1072. )~~~");
  1073. }
  1074. auto generate_return_statement = [&](auto& return_type) {
  1075. auto scoped_generator = generator.fork();
  1076. scoped_generator.set("return_type", return_type.name);
  1077. if (return_type.name == "undefined") {
  1078. scoped_generator.append(R"~~~(
  1079. return JS::js_undefined();
  1080. )~~~");
  1081. return;
  1082. }
  1083. if (return_type.nullable) {
  1084. if (return_type.is_string()) {
  1085. scoped_generator.append(R"~~~(
  1086. if (retval.is_null())
  1087. return JS::js_null();
  1088. )~~~");
  1089. } else {
  1090. scoped_generator.append(R"~~~(
  1091. if (!retval)
  1092. return JS::js_null();
  1093. )~~~");
  1094. }
  1095. }
  1096. if (return_type.is_string()) {
  1097. scoped_generator.append(R"~~~(
  1098. return JS::js_string(vm, retval);
  1099. )~~~");
  1100. } else if (return_type.name == "ArrayFromVector") {
  1101. // FIXME: Remove this fake type hack once it's no longer needed.
  1102. // Basically once we have NodeList we can throw this out.
  1103. scoped_generator.append(R"~~~(
  1104. auto* new_array = JS::Array::create(global_object);
  1105. for (auto& element : retval)
  1106. new_array->indexed_properties().append(wrap(global_object, element));
  1107. return new_array;
  1108. )~~~");
  1109. } else if (return_type.name == "boolean" || return_type.name == "double") {
  1110. scoped_generator.append(R"~~~(
  1111. return JS::Value(retval);
  1112. )~~~");
  1113. } else if (return_type.name == "short" || return_type.name == "unsigned short" || return_type.name == "long" || return_type.name == "unsigned long") {
  1114. scoped_generator.append(R"~~~(
  1115. return JS::Value((i32)retval);
  1116. )~~~");
  1117. } else if (return_type.name == "Uint8ClampedArray") {
  1118. scoped_generator.append(R"~~~(
  1119. return retval;
  1120. )~~~");
  1121. } else if (return_type.name == "EventHandler") {
  1122. scoped_generator.append(R"~~~(
  1123. return retval.callback.cell();
  1124. )~~~");
  1125. } else {
  1126. scoped_generator.append(R"~~~(
  1127. return wrap(global_object, const_cast<@return_type@&>(*retval));
  1128. )~~~");
  1129. }
  1130. };
  1131. for (auto& attribute : interface.attributes) {
  1132. auto attribute_generator = generator.fork();
  1133. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1134. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1135. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1136. if (attribute.extended_attributes.contains("ImplementedAs")) {
  1137. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  1138. attribute_generator.set("attribute.cpp_getter_name", implemented_as);
  1139. } else {
  1140. attribute_generator.set("attribute.cpp_getter_name", attribute.name.to_snakecase());
  1141. }
  1142. if (attribute.extended_attributes.contains("Reflect")) {
  1143. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1144. if (attribute_name.is_null())
  1145. attribute_name = attribute.name;
  1146. attribute_name = make_input_acceptable_cpp(attribute_name);
  1147. attribute_generator.set("attribute.reflect_name", attribute_name);
  1148. } else {
  1149. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  1150. }
  1151. attribute_generator.append(R"~~~(
  1152. JS_DEFINE_NATIVE_GETTER(@prototype_class@::@attribute.getter_callback@)
  1153. {
  1154. auto* impl = impl_from(vm, global_object);
  1155. if (!impl)
  1156. return {};
  1157. )~~~");
  1158. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1159. attribute_generator.append(R"~~~(
  1160. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1161. return JS::js_null();
  1162. )~~~");
  1163. }
  1164. if (attribute.extended_attributes.contains("Reflect")) {
  1165. if (attribute.type.name != "boolean") {
  1166. attribute_generator.append(R"~~~(
  1167. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1168. )~~~");
  1169. } else {
  1170. attribute_generator.append(R"~~~(
  1171. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1172. )~~~");
  1173. }
  1174. } else {
  1175. attribute_generator.append(R"~~~(
  1176. auto retval = impl->@attribute.cpp_getter_name@();
  1177. )~~~");
  1178. }
  1179. generate_return_statement(attribute.type);
  1180. attribute_generator.append(R"~~~(
  1181. }
  1182. )~~~");
  1183. if (!attribute.readonly) {
  1184. attribute_generator.append(R"~~~(
  1185. JS_DEFINE_NATIVE_SETTER(@prototype_class@::@attribute.setter_callback@)
  1186. {
  1187. auto* impl = impl_from(vm, global_object);
  1188. if (!impl)
  1189. return;
  1190. )~~~");
  1191. generate_to_cpp(generator, attribute, "value", "", "cpp_value", true, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1192. if (attribute.extended_attributes.contains("Reflect")) {
  1193. if (attribute.type.name != "boolean") {
  1194. attribute_generator.append(R"~~~(
  1195. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1196. )~~~");
  1197. } else {
  1198. attribute_generator.append(R"~~~(
  1199. if (!cpp_value)
  1200. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1201. else
  1202. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1203. )~~~");
  1204. }
  1205. } else {
  1206. attribute_generator.append(R"~~~(
  1207. impl->set_@attribute.name:snakecase@(cpp_value);
  1208. )~~~");
  1209. }
  1210. attribute_generator.append(R"~~~(
  1211. }
  1212. )~~~");
  1213. }
  1214. }
  1215. // Implementation: Functions
  1216. for (auto& function : interface.functions) {
  1217. auto function_generator = generator.fork();
  1218. function_generator.set("function.name", function.name);
  1219. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1220. function_generator.append(R"~~~(
  1221. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@function.name:snakecase@)
  1222. {
  1223. auto* impl = impl_from(vm, global_object);
  1224. if (!impl)
  1225. return {};
  1226. )~~~");
  1227. generate_argument_count_check(generator, function);
  1228. StringBuilder arguments_builder;
  1229. generate_arguments(generator, function.parameters, arguments_builder);
  1230. function_generator.set(".arguments", arguments_builder.string_view());
  1231. function_generator.append(R"~~~(
  1232. auto retval = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->@function.name:snakecase@(@.arguments@); });
  1233. if (should_return_empty(retval))
  1234. return JS::Value();
  1235. )~~~");
  1236. generate_return_statement(function.return_type);
  1237. function_generator.append(R"~~~(
  1238. }
  1239. )~~~");
  1240. }
  1241. generator.append(R"~~~(
  1242. } // namespace Web::Bindings
  1243. )~~~");
  1244. outln("{}", generator.as_string_view());
  1245. }