WrapperGenerator.cpp 52 KB

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