WrapperGenerator.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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 == "long") {
  580. scoped_generator.append(R"~~~(
  581. auto @cpp_name@ = @js_name@@js_suffix@.to_i32(global_object);
  582. if (vm.exception())
  583. @return_statement@
  584. )~~~");
  585. } else if (parameter.type.name == "EventHandler") {
  586. // x.onfoo = function() { ... }
  587. scoped_generator.append(R"~~~(
  588. HTML::EventHandler @cpp_name@;
  589. if (@js_name@@js_suffix@.is_function()) {
  590. @cpp_name@.callback = JS::make_handle(&@js_name@@js_suffix@.as_function());
  591. } else if (@js_name@@js_suffix@.is_string()) {
  592. @cpp_name@.string = @js_name@@js_suffix@.as_string().string();
  593. } else {
  594. @return_statement@
  595. }
  596. )~~~");
  597. } else {
  598. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  599. VERIFY_NOT_REACHED();
  600. }
  601. }
  602. template<typename FunctionType>
  603. static void generate_argument_count_check(SourceGenerator& generator, FunctionType& function)
  604. {
  605. auto argument_count_check_generator = generator.fork();
  606. argument_count_check_generator.set("function.name", function.name);
  607. argument_count_check_generator.set("function.nargs", String::number(function.length()));
  608. if (function.length() == 0)
  609. return;
  610. if (function.length() == 1) {
  611. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  612. argument_count_check_generator.set(".arg_count_suffix", "");
  613. } else {
  614. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  615. argument_count_check_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  616. }
  617. argument_count_check_generator.append(R"~~~(
  618. if (vm.argument_count() < @function.nargs@) {
  619. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  620. return {};
  621. }
  622. )~~~");
  623. }
  624. static void generate_arguments(SourceGenerator& generator, const Vector<IDL::Parameter>& parameters, StringBuilder& arguments_builder, bool return_void = false)
  625. {
  626. auto arguments_generator = generator.fork();
  627. Vector<String> parameter_names;
  628. size_t argument_index = 0;
  629. for (auto& parameter : parameters) {
  630. parameter_names.append(make_input_acceptable_cpp(parameter.name.to_snakecase()));
  631. arguments_generator.set("argument.index", String::number(argument_index));
  632. arguments_generator.append(R"~~~(
  633. auto arg@argument.index@ = vm.argument(@argument.index@);
  634. )~~~");
  635. bool legacy_null_to_empty_string = parameter.extended_attributes.contains("LegacyNullToEmptyString");
  636. 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);
  637. ++argument_index;
  638. }
  639. arguments_builder.join(", ", parameter_names);
  640. }
  641. static void generate_header(const IDL::Interface& interface)
  642. {
  643. StringBuilder builder;
  644. SourceGenerator generator { builder };
  645. generator.set("name", interface.name);
  646. generator.set("fully_qualified_name", interface.fully_qualified_name);
  647. generator.set("wrapper_base_class", interface.wrapper_base_class);
  648. generator.set("wrapper_class", interface.wrapper_class);
  649. generator.set("wrapper_class:snakecase", interface.wrapper_class.to_snakecase());
  650. generator.append(R"~~~(
  651. #pragma once
  652. #include <LibWeb/Bindings/Wrapper.h>
  653. // FIXME: This is very strange.
  654. #if __has_include(<LibWeb/CSS/@name@.h>)
  655. # include <LibWeb/CSS/@name@.h>
  656. #elif __has_include(<LibWeb/DOM/@name@.h>)
  657. # include <LibWeb/DOM/@name@.h>
  658. #elif __has_include(<LibWeb/HTML/@name@.h>)
  659. # include <LibWeb/HTML/@name@.h>
  660. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  661. # include <LibWeb/UIEvents/@name@.h>
  662. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  663. # include <LibWeb/HighResolutionTime/@name@.h>
  664. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  665. # include <LibWeb/NavigationTiming/@name@.h>
  666. #elif __has_include(<LibWeb/SVG/@name@.h>)
  667. # include <LibWeb/SVG/@name@.h>
  668. #elif __has_include(<LibWeb/XHR/@name@.h>)
  669. # include <LibWeb/XHR/@name@.h>
  670. #endif
  671. )~~~");
  672. if (interface.wrapper_base_class != "Wrapper") {
  673. generator.append(R"~~~(
  674. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  675. )~~~");
  676. }
  677. generator.append(R"~~~(
  678. namespace Web::Bindings {
  679. class @wrapper_class@ : public @wrapper_base_class@ {
  680. JS_OBJECT(@name@, @wrapper_base_class@);
  681. public:
  682. static @wrapper_class@* create(JS::GlobalObject&, @fully_qualified_name@&);
  683. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  684. virtual void initialize(JS::GlobalObject&) override;
  685. virtual ~@wrapper_class@() override;
  686. )~~~");
  687. if (interface.extended_attributes.contains("CustomGet")) {
  688. generator.append(R"~~~(
  689. virtual JS::Value get(const JS::PropertyName&, JS::Value receiver = {}, bool without_side_effects = false) const override;
  690. )~~~");
  691. }
  692. if (interface.extended_attributes.contains("CustomGetByIndex")) {
  693. generator.append(R"~~~(
  694. virtual JS::Value get_by_index(u32 property_index) const override;
  695. )~~~");
  696. }
  697. if (interface.extended_attributes.contains("CustomPut")) {
  698. generator.append(R"~~~(
  699. virtual bool put(const JS::PropertyName&, JS::Value, JS::Value receiver = {}) override;
  700. )~~~");
  701. }
  702. if (interface.wrapper_base_class == "Wrapper") {
  703. generator.append(R"~~~(
  704. @fully_qualified_name@& impl() { return *m_impl; }
  705. const @fully_qualified_name@& impl() const { return *m_impl; }
  706. )~~~");
  707. } else {
  708. generator.append(R"~~~(
  709. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  710. const @fully_qualified_name@& impl() const { return static_cast<const @fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  711. )~~~");
  712. }
  713. generator.append(R"~~~(
  714. private:
  715. )~~~");
  716. if (interface.wrapper_base_class == "Wrapper") {
  717. generator.append(R"~~~(
  718. NonnullRefPtr<@fully_qualified_name@> m_impl;
  719. )~~~");
  720. }
  721. generator.append(R"~~~(
  722. };
  723. )~~~");
  724. if (should_emit_wrapper_factory(interface)) {
  725. generator.append(R"~~~(
  726. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  727. )~~~");
  728. }
  729. generator.append(R"~~~(
  730. } // namespace Web::Bindings
  731. )~~~");
  732. outln("{}", generator.as_string_view());
  733. }
  734. void generate_implementation(const IDL::Interface& interface)
  735. {
  736. StringBuilder builder;
  737. SourceGenerator generator { builder };
  738. generator.set("name", interface.name);
  739. generator.set("wrapper_class", interface.wrapper_class);
  740. generator.set("wrapper_base_class", interface.wrapper_base_class);
  741. generator.set("prototype_class", interface.prototype_class);
  742. generator.set("fully_qualified_name", interface.fully_qualified_name);
  743. generator.append(R"~~~(
  744. #include <AK/FlyString.h>
  745. #include <LibJS/Runtime/Array.h>
  746. #include <LibJS/Runtime/Error.h>
  747. #include <LibJS/Runtime/Function.h>
  748. #include <LibJS/Runtime/GlobalObject.h>
  749. #include <LibJS/Runtime/Uint8ClampedArray.h>
  750. #include <LibJS/Runtime/Value.h>
  751. #include <LibWeb/Bindings/@prototype_class@.h>
  752. #include <LibWeb/Bindings/@wrapper_class@.h>
  753. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  754. #include <LibWeb/Bindings/CommentWrapper.h>
  755. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  756. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  757. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  758. #include <LibWeb/Bindings/DocumentWrapper.h>
  759. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  760. #include <LibWeb/Bindings/EventWrapperFactory.h>
  761. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  762. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  763. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  764. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  765. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  766. #include <LibWeb/Bindings/ImageDataWrapper.h>
  767. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  768. #include <LibWeb/Bindings/TextWrapper.h>
  769. #include <LibWeb/Bindings/WindowObject.h>
  770. #include <LibWeb/DOM/Element.h>
  771. #include <LibWeb/DOM/EventListener.h>
  772. #include <LibWeb/HTML/HTMLElement.h>
  773. #include <LibWeb/Origin.h>
  774. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  775. using namespace Web::CSS;
  776. using namespace Web::DOM;
  777. using namespace Web::HTML;
  778. namespace Web::Bindings {
  779. @wrapper_class@* @wrapper_class@::create(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  780. {
  781. return global_object.heap().allocate<@wrapper_class@>(global_object, global_object, impl);
  782. }
  783. )~~~");
  784. if (interface.wrapper_base_class == "Wrapper") {
  785. generator.append(R"~~~(
  786. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  787. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  788. , m_impl(impl)
  789. {
  790. }
  791. )~~~");
  792. } else {
  793. generator.append(R"~~~(
  794. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  795. : @wrapper_base_class@(global_object, impl)
  796. {
  797. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  798. }
  799. )~~~");
  800. }
  801. generator.append(R"~~~(
  802. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  803. {
  804. @wrapper_base_class@::initialize(global_object);
  805. }
  806. @wrapper_class@::~@wrapper_class@()
  807. {
  808. }
  809. )~~~");
  810. if (should_emit_wrapper_factory(interface)) {
  811. generator.append(R"~~~(
  812. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  813. {
  814. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  815. }
  816. )~~~");
  817. }
  818. generator.append(R"~~~(
  819. } // namespace Web::Bindings
  820. )~~~");
  821. outln("{}", generator.as_string_view());
  822. }
  823. static void generate_constructor_header(const IDL::Interface& interface)
  824. {
  825. StringBuilder builder;
  826. SourceGenerator generator { builder };
  827. generator.set("name", interface.name);
  828. generator.set("fully_qualified_name", interface.fully_qualified_name);
  829. generator.set("constructor_class", interface.constructor_class);
  830. generator.set("constructor_class:snakecase", interface.constructor_class.to_snakecase());
  831. generator.append(R"~~~(
  832. #pragma once
  833. #include <LibJS/Runtime/NativeFunction.h>
  834. namespace Web::Bindings {
  835. class @constructor_class@ : public JS::NativeFunction {
  836. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  837. public:
  838. explicit @constructor_class@(JS::GlobalObject&);
  839. virtual void initialize(JS::GlobalObject&) override;
  840. virtual ~@constructor_class@() override;
  841. virtual JS::Value call() override;
  842. virtual JS::Value construct(JS::Function& new_target) override;
  843. private:
  844. virtual bool has_constructor() const override { return true; }
  845. };
  846. } // namespace Web::Bindings
  847. )~~~");
  848. outln("{}", generator.as_string_view());
  849. }
  850. void generate_constructor_implementation(const IDL::Interface& interface)
  851. {
  852. StringBuilder builder;
  853. SourceGenerator generator { builder };
  854. generator.set("name", interface.name);
  855. generator.set("prototype_class", interface.prototype_class);
  856. generator.set("wrapper_class", interface.wrapper_class);
  857. generator.set("constructor_class", interface.constructor_class);
  858. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  859. generator.set("fully_qualified_name", interface.fully_qualified_name);
  860. generator.append(R"~~~(
  861. #include <LibJS/Heap/Heap.h>
  862. #include <LibJS/Runtime/GlobalObject.h>
  863. #include <LibWeb/Bindings/@constructor_class@.h>
  864. #include <LibWeb/Bindings/@prototype_class@.h>
  865. #include <LibWeb/Bindings/@wrapper_class@.h>
  866. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  867. #include <LibWeb/Bindings/WindowObject.h>
  868. #if __has_include(<LibWeb/CSS/@name@.h>)
  869. # include <LibWeb/CSS/@name@.h>
  870. #elif __has_include(<LibWeb/DOM/@name@.h>)
  871. # include <LibWeb/DOM/@name@.h>
  872. #elif __has_include(<LibWeb/HTML/@name@.h>)
  873. # include <LibWeb/HTML/@name@.h>
  874. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  875. # include <LibWeb/UIEvents/@name@.h>
  876. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  877. # include <LibWeb/HighResolutionTime/@name@.h>
  878. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  879. # include <LibWeb/NavigationTiming/@name@.h>
  880. #elif __has_include(<LibWeb/SVG/@name@.h>)
  881. # include <LibWeb/SVG/@name@.h>
  882. #elif __has_include(<LibWeb/XHR/@name@.h>)
  883. # include <LibWeb/XHR/@name@.h>
  884. #endif
  885. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  886. using namespace Web::CSS;
  887. using namespace Web::DOM;
  888. using namespace Web::HTML;
  889. namespace Web::Bindings {
  890. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  891. : NativeFunction(*global_object.function_prototype())
  892. {
  893. }
  894. @constructor_class@::~@constructor_class@()
  895. {
  896. }
  897. JS::Value @constructor_class@::call()
  898. {
  899. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  900. return {};
  901. }
  902. JS::Value @constructor_class@::construct(Function&)
  903. {
  904. )~~~");
  905. if (interface.constructors.is_empty()) {
  906. // No constructor
  907. generator.set("constructor.length", "0");
  908. generator.append(R"~~~(
  909. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::NotAConstructor, "@name@");
  910. return {};
  911. )~~~");
  912. } else if (interface.constructors.size() == 1) {
  913. // Single constructor
  914. auto& constructor = interface.constructors[0];
  915. generator.set("constructor.length", String::number(constructor.length()));
  916. generator.append(R"~~~(
  917. [[maybe_unused]] auto& vm = this->vm();
  918. auto& global_object = this->global_object();
  919. auto& window = static_cast<WindowObject&>(global_object);
  920. )~~~");
  921. if (!constructor.parameters.is_empty()) {
  922. generate_argument_count_check(generator, constructor);
  923. StringBuilder arguments_builder;
  924. generate_arguments(generator, constructor.parameters, arguments_builder);
  925. generator.set(".constructor_arguments", arguments_builder.string_view());
  926. generator.append(R"~~~(
  927. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window, @.constructor_arguments@); });
  928. )~~~");
  929. } else {
  930. generator.append(R"~~~(
  931. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window); });
  932. )~~~");
  933. }
  934. generator.append(R"~~~(
  935. if (should_return_empty(impl))
  936. return JS::Value();
  937. return @wrapper_class@::create(global_object, impl.release_value());
  938. )~~~");
  939. } else {
  940. // Multiple constructor overloads - can't do that yet.
  941. TODO();
  942. }
  943. generator.append(R"~~~(
  944. }
  945. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  946. {
  947. auto& vm = this->vm();
  948. auto& window = static_cast<WindowObject&>(global_object);
  949. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  950. NativeFunction::initialize(global_object);
  951. define_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  952. define_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  953. )~~~");
  954. for (auto& constant : interface.constants) {
  955. auto constant_generator = generator.fork();
  956. constant_generator.set("constant.name", constant.name);
  957. constant_generator.set("constant.value", constant.value);
  958. constant_generator.append(R"~~~(
  959. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  960. )~~~");
  961. }
  962. generator.append(R"~~~(
  963. }
  964. } // namespace Web::Bindings
  965. )~~~");
  966. outln("{}", generator.as_string_view());
  967. }
  968. static void generate_prototype_header(const IDL::Interface& interface)
  969. {
  970. StringBuilder builder;
  971. SourceGenerator generator { builder };
  972. generator.set("name", interface.name);
  973. generator.set("fully_qualified_name", interface.fully_qualified_name);
  974. generator.set("prototype_class", interface.prototype_class);
  975. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  976. generator.append(R"~~~(
  977. #pragma once
  978. #include <LibJS/Runtime/Object.h>
  979. namespace Web::Bindings {
  980. class @prototype_class@ : public JS::Object {
  981. JS_OBJECT(@prototype_class@, JS::Object);
  982. public:
  983. explicit @prototype_class@(JS::GlobalObject&);
  984. virtual void initialize(JS::GlobalObject&) override;
  985. virtual ~@prototype_class@() override;
  986. private:
  987. )~~~");
  988. for (auto& function : interface.functions) {
  989. auto function_generator = generator.fork();
  990. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  991. function_generator.append(R"~~~(
  992. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  993. )~~~");
  994. }
  995. for (auto& attribute : interface.attributes) {
  996. auto attribute_generator = generator.fork();
  997. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  998. attribute_generator.append(R"~~~(
  999. JS_DECLARE_NATIVE_GETTER(@attribute.name:snakecase@_getter);
  1000. )~~~");
  1001. if (!attribute.readonly) {
  1002. attribute_generator.append(R"~~~(
  1003. JS_DECLARE_NATIVE_SETTER(@attribute.name:snakecase@_setter);
  1004. )~~~");
  1005. }
  1006. }
  1007. generator.append(R"~~~(
  1008. };
  1009. } // namespace Web::Bindings
  1010. )~~~");
  1011. outln("{}", generator.as_string_view());
  1012. }
  1013. void generate_prototype_implementation(const IDL::Interface& interface)
  1014. {
  1015. StringBuilder builder;
  1016. SourceGenerator generator { builder };
  1017. generator.set("name", interface.name);
  1018. generator.set("parent_name", interface.parent_name);
  1019. generator.set("prototype_class", interface.prototype_class);
  1020. generator.set("prototype_base_class", interface.prototype_base_class);
  1021. generator.set("wrapper_class", interface.wrapper_class);
  1022. generator.set("constructor_class", interface.constructor_class);
  1023. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1024. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1025. generator.append(R"~~~(
  1026. #include <AK/Function.h>
  1027. #include <LibJS/Runtime/Array.h>
  1028. #include <LibJS/Runtime/Error.h>
  1029. #include <LibJS/Runtime/Function.h>
  1030. #include <LibJS/Runtime/GlobalObject.h>
  1031. #include <LibJS/Runtime/Uint8ClampedArray.h>
  1032. #include <LibWeb/Bindings/@prototype_class@.h>
  1033. #include <LibWeb/Bindings/@wrapper_class@.h>
  1034. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  1035. #include <LibWeb/Bindings/CSSStyleSheetWrapper.h>
  1036. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  1037. #include <LibWeb/Bindings/CommentWrapper.h>
  1038. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  1039. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  1040. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  1041. #include <LibWeb/Bindings/DocumentWrapper.h>
  1042. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  1043. #include <LibWeb/Bindings/EventWrapper.h>
  1044. #include <LibWeb/Bindings/EventWrapperFactory.h>
  1045. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1046. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  1047. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  1048. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  1049. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  1050. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  1051. #include <LibWeb/Bindings/ImageDataWrapper.h>
  1052. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  1053. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  1054. #include <LibWeb/Bindings/RangeWrapper.h>
  1055. #include <LibWeb/Bindings/StyleSheetListWrapper.h>
  1056. #include <LibWeb/Bindings/TextWrapper.h>
  1057. #include <LibWeb/Bindings/WindowObject.h>
  1058. #include <LibWeb/DOM/Element.h>
  1059. #include <LibWeb/DOM/EventListener.h>
  1060. #include <LibWeb/DOM/Range.h>
  1061. #include <LibWeb/DOM/Window.h>
  1062. #include <LibWeb/HTML/EventHandler.h>
  1063. #include <LibWeb/HTML/HTMLElement.h>
  1064. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  1065. #include <LibWeb/Origin.h>
  1066. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  1067. # include <LibWeb/Bindings/@prototype_base_class@.h>
  1068. #endif
  1069. #if __has_include(<LibWeb/CSS/@name@.h>)
  1070. # include <LibWeb/CSS/@name@.h>
  1071. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1072. # include <LibWeb/DOM/@name@.h>
  1073. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1074. # include <LibWeb/HTML/@name@.h>
  1075. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1076. # include <LibWeb/UIEvents/@name@.h>
  1077. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1078. # include <LibWeb/HighResolutionTime/@name@.h>
  1079. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1080. # include <LibWeb/NavigationTiming/@name@.h>
  1081. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1082. # include <LibWeb/SVG/@name@.h>
  1083. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1084. # include <LibWeb/XHR/@name@.h>
  1085. #endif
  1086. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1087. using namespace Web::CSS;
  1088. using namespace Web::DOM;
  1089. using namespace Web::HTML;
  1090. using namespace Web::NavigationTiming;
  1091. using namespace Web::XHR;
  1092. namespace Web::Bindings {
  1093. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  1094. : Object(*global_object.object_prototype())
  1095. {
  1096. )~~~");
  1097. if (interface.name == "DOMException") {
  1098. // https://heycam.github.io/webidl/#es-DOMException-specialness
  1099. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  1100. generator.append(R"~~~(
  1101. set_prototype(global_object.error_prototype());
  1102. )~~~");
  1103. } else if (!interface.parent_name.is_empty()) {
  1104. generator.append(R"~~~(
  1105. set_prototype(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  1106. )~~~");
  1107. }
  1108. generator.append(R"~~~(
  1109. }
  1110. @prototype_class@::~@prototype_class@()
  1111. {
  1112. }
  1113. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  1114. {
  1115. [[maybe_unused]] auto& vm = this->vm();
  1116. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;
  1117. )~~~");
  1118. for (auto& attribute : interface.attributes) {
  1119. auto attribute_generator = generator.fork();
  1120. attribute_generator.set("attribute.name", attribute.name);
  1121. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1122. if (attribute.readonly)
  1123. attribute_generator.set("attribute.setter_callback", "nullptr");
  1124. else
  1125. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1126. attribute_generator.append(R"~~~(
  1127. define_native_property("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  1128. )~~~");
  1129. }
  1130. for (auto& constant : interface.constants) {
  1131. auto constant_generator = generator.fork();
  1132. constant_generator.set("constant.name", constant.name);
  1133. constant_generator.set("constant.value", constant.value);
  1134. constant_generator.append(R"~~~(
  1135. define_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1136. )~~~");
  1137. }
  1138. for (auto& function : interface.functions) {
  1139. auto function_generator = generator.fork();
  1140. function_generator.set("function.name", function.name);
  1141. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1142. function_generator.set("function.length", String::number(function.length()));
  1143. function_generator.append(R"~~~(
  1144. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1145. )~~~");
  1146. }
  1147. generator.append(R"~~~(
  1148. Object::initialize(global_object);
  1149. }
  1150. )~~~");
  1151. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  1152. generator.append(R"~~~(
  1153. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  1154. {
  1155. auto* this_object = vm.this_value(global_object).to_object(global_object);
  1156. if (!this_object)
  1157. return {};
  1158. )~~~");
  1159. if (interface.name == "EventTarget") {
  1160. generator.append(R"~~~(
  1161. if (is<WindowObject>(this_object)) {
  1162. return &static_cast<WindowObject*>(this_object)->impl();
  1163. }
  1164. )~~~");
  1165. }
  1166. generator.append(R"~~~(
  1167. if (!is<@wrapper_class@>(this_object)) {
  1168. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  1169. return nullptr;
  1170. }
  1171. return &static_cast<@wrapper_class@*>(this_object)->impl();
  1172. }
  1173. )~~~");
  1174. }
  1175. auto generate_return_statement = [&](auto& return_type) {
  1176. auto scoped_generator = generator.fork();
  1177. scoped_generator.set("return_type", return_type.name);
  1178. if (return_type.name == "undefined") {
  1179. scoped_generator.append(R"~~~(
  1180. return JS::js_undefined();
  1181. )~~~");
  1182. return;
  1183. }
  1184. if (return_type.nullable) {
  1185. if (return_type.is_string()) {
  1186. scoped_generator.append(R"~~~(
  1187. if (retval.is_null())
  1188. return JS::js_null();
  1189. )~~~");
  1190. } else {
  1191. scoped_generator.append(R"~~~(
  1192. if (!retval)
  1193. return JS::js_null();
  1194. )~~~");
  1195. }
  1196. }
  1197. if (return_type.is_string()) {
  1198. scoped_generator.append(R"~~~(
  1199. return JS::js_string(vm, retval);
  1200. )~~~");
  1201. } else if (return_type.name == "ArrayFromVector") {
  1202. // FIXME: Remove this fake type hack once it's no longer needed.
  1203. // Basically once we have NodeList we can throw this out.
  1204. scoped_generator.append(R"~~~(
  1205. auto* new_array = JS::Array::create(global_object);
  1206. for (auto& element : retval)
  1207. new_array->indexed_properties().append(wrap(global_object, element));
  1208. return new_array;
  1209. )~~~");
  1210. } else if (return_type.name == "boolean" || return_type.name == "double") {
  1211. scoped_generator.append(R"~~~(
  1212. return JS::Value(retval);
  1213. )~~~");
  1214. } else if (return_type.name == "short" || return_type.name == "unsigned short" || return_type.name == "long" || return_type.name == "unsigned long") {
  1215. scoped_generator.append(R"~~~(
  1216. return JS::Value((i32)retval);
  1217. )~~~");
  1218. } else if (return_type.name == "Uint8ClampedArray") {
  1219. scoped_generator.append(R"~~~(
  1220. return retval;
  1221. )~~~");
  1222. } else if (return_type.name == "EventHandler") {
  1223. scoped_generator.append(R"~~~(
  1224. return retval.callback.cell();
  1225. )~~~");
  1226. } else {
  1227. scoped_generator.append(R"~~~(
  1228. return wrap(global_object, const_cast<@return_type@&>(*retval));
  1229. )~~~");
  1230. }
  1231. };
  1232. for (auto& attribute : interface.attributes) {
  1233. auto attribute_generator = generator.fork();
  1234. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1235. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1236. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1237. if (attribute.extended_attributes.contains("ImplementedAs")) {
  1238. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  1239. attribute_generator.set("attribute.cpp_getter_name", implemented_as);
  1240. } else {
  1241. attribute_generator.set("attribute.cpp_getter_name", attribute.name.to_snakecase());
  1242. }
  1243. if (attribute.extended_attributes.contains("Reflect")) {
  1244. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1245. if (attribute_name.is_null())
  1246. attribute_name = attribute.name;
  1247. attribute_name = make_input_acceptable_cpp(attribute_name);
  1248. attribute_generator.set("attribute.reflect_name", attribute_name);
  1249. } else {
  1250. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  1251. }
  1252. attribute_generator.append(R"~~~(
  1253. JS_DEFINE_NATIVE_GETTER(@prototype_class@::@attribute.getter_callback@)
  1254. {
  1255. auto* impl = impl_from(vm, global_object);
  1256. if (!impl)
  1257. return {};
  1258. )~~~");
  1259. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1260. attribute_generator.append(R"~~~(
  1261. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1262. return JS::js_null();
  1263. )~~~");
  1264. }
  1265. if (attribute.extended_attributes.contains("Reflect")) {
  1266. if (attribute.type.name != "boolean") {
  1267. attribute_generator.append(R"~~~(
  1268. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1269. )~~~");
  1270. } else {
  1271. attribute_generator.append(R"~~~(
  1272. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1273. )~~~");
  1274. }
  1275. } else {
  1276. attribute_generator.append(R"~~~(
  1277. auto retval = impl->@attribute.cpp_getter_name@();
  1278. )~~~");
  1279. }
  1280. generate_return_statement(attribute.type);
  1281. attribute_generator.append(R"~~~(
  1282. }
  1283. )~~~");
  1284. if (!attribute.readonly) {
  1285. attribute_generator.append(R"~~~(
  1286. JS_DEFINE_NATIVE_SETTER(@prototype_class@::@attribute.setter_callback@)
  1287. {
  1288. auto* impl = impl_from(vm, global_object);
  1289. if (!impl)
  1290. return;
  1291. )~~~");
  1292. generate_to_cpp(generator, attribute, "value", "", "cpp_value", true, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1293. if (attribute.extended_attributes.contains("Reflect")) {
  1294. if (attribute.type.name != "boolean") {
  1295. attribute_generator.append(R"~~~(
  1296. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1297. )~~~");
  1298. } else {
  1299. attribute_generator.append(R"~~~(
  1300. if (!cpp_value)
  1301. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1302. else
  1303. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1304. )~~~");
  1305. }
  1306. } else {
  1307. attribute_generator.append(R"~~~(
  1308. impl->set_@attribute.name:snakecase@(cpp_value);
  1309. )~~~");
  1310. }
  1311. attribute_generator.append(R"~~~(
  1312. }
  1313. )~~~");
  1314. }
  1315. }
  1316. // Implementation: Functions
  1317. for (auto& function : interface.functions) {
  1318. auto function_generator = generator.fork();
  1319. function_generator.set("function.name", function.name);
  1320. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1321. if (function.extended_attributes.contains("ImplementedAs")) {
  1322. auto implemented_as = function.extended_attributes.get("ImplementedAs").value();
  1323. function_generator.set("function.cpp_name", implemented_as);
  1324. } else {
  1325. function_generator.set("function.cpp_name", function.name.to_snakecase());
  1326. }
  1327. function_generator.append(R"~~~(
  1328. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@function.name:snakecase@)
  1329. {
  1330. auto* impl = impl_from(vm, global_object);
  1331. if (!impl)
  1332. return {};
  1333. )~~~");
  1334. generate_argument_count_check(generator, function);
  1335. StringBuilder arguments_builder;
  1336. generate_arguments(generator, function.parameters, arguments_builder);
  1337. function_generator.set(".arguments", arguments_builder.string_view());
  1338. function_generator.append(R"~~~(
  1339. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->@function.cpp_name@(@.arguments@); });
  1340. if (should_return_empty(result))
  1341. return JS::Value();
  1342. [[maybe_unused]] auto retval = result.release_value();
  1343. )~~~");
  1344. generate_return_statement(function.return_type);
  1345. function_generator.append(R"~~~(
  1346. }
  1347. )~~~");
  1348. }
  1349. generator.append(R"~~~(
  1350. } // namespace Web::Bindings
  1351. )~~~");
  1352. outln("{}", generator.as_string_view());
  1353. }