WrapperGenerator.cpp 53 KB

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