WrapperGenerator.cpp 48 KB

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