WrapperGenerator.cpp 54 KB

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