WrapperGenerator.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Debug.h>
  10. #include <AK/GenericLexer.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/LexicalPath.h>
  13. #include <AK/OwnPtr.h>
  14. #include <AK/SourceGenerator.h>
  15. #include <AK/StringBuilder.h>
  16. #include <LibCore/ArgsParser.h>
  17. #include <LibCore/File.h>
  18. #include <ctype.h>
  19. static String make_input_acceptable_cpp(String const& input)
  20. {
  21. if (input.is_one_of("class", "template", "for", "default", "char", "namespace")) {
  22. StringBuilder builder;
  23. builder.append(input);
  24. builder.append('_');
  25. return builder.to_string();
  26. }
  27. return input.replace("-", "_");
  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. Optional<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. Vector<Function> static_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, StringView const& 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 = [&](StringView const& 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. bool static_ = false;
  260. if (lexer.consume_specific("static")) {
  261. static_ = true;
  262. consume_whitespace();
  263. }
  264. auto return_type = parse_type();
  265. consume_whitespace();
  266. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '('; });
  267. consume_whitespace();
  268. assert_specific('(');
  269. auto parameters = parse_parameters();
  270. assert_specific(')');
  271. consume_whitespace();
  272. assert_specific(';');
  273. if (!static_)
  274. interface->functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  275. else
  276. interface->static_functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  277. };
  278. auto parse_constructor = [&] {
  279. assert_string("constructor");
  280. consume_whitespace();
  281. assert_specific('(');
  282. auto parameters = parse_parameters();
  283. assert_specific(')');
  284. consume_whitespace();
  285. assert_specific(';');
  286. interface->constructors.append(Constructor { interface->name, move(parameters) });
  287. };
  288. for (;;) {
  289. HashMap<String, String> extended_attributes;
  290. consume_whitespace();
  291. if (lexer.consume_specific('}')) {
  292. consume_whitespace();
  293. assert_specific(';');
  294. break;
  295. }
  296. if (lexer.consume_specific('[')) {
  297. extended_attributes = parse_extended_attributes();
  298. }
  299. if (lexer.next_is("constructor")) {
  300. parse_constructor();
  301. continue;
  302. }
  303. if (lexer.next_is("const")) {
  304. parse_constant();
  305. continue;
  306. }
  307. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  308. parse_attribute(extended_attributes);
  309. continue;
  310. }
  311. parse_function(extended_attributes);
  312. }
  313. interface->wrapper_class = String::formatted("{}Wrapper", interface->name);
  314. interface->wrapper_base_class = String::formatted("{}Wrapper", interface->parent_name.is_empty() ? String::empty() : interface->parent_name);
  315. interface->constructor_class = String::formatted("{}Constructor", interface->name);
  316. interface->prototype_class = String::formatted("{}Prototype", interface->name);
  317. interface->prototype_base_class = String::formatted("{}Prototype", interface->parent_name.is_empty() ? "Object" : interface->parent_name);
  318. return interface;
  319. }
  320. }
  321. static void generate_constructor_header(IDL::Interface const&);
  322. static void generate_constructor_implementation(IDL::Interface const&);
  323. static void generate_prototype_header(IDL::Interface const&);
  324. static void generate_prototype_implementation(IDL::Interface const&);
  325. static void generate_header(IDL::Interface const&);
  326. static void generate_implementation(IDL::Interface const&);
  327. int main(int argc, char** argv)
  328. {
  329. Core::ArgsParser args_parser;
  330. char const* path = nullptr;
  331. bool header_mode = false;
  332. bool implementation_mode = false;
  333. bool constructor_header_mode = false;
  334. bool constructor_implementation_mode = false;
  335. bool prototype_header_mode = false;
  336. bool prototype_implementation_mode = false;
  337. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  338. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  339. args_parser.add_option(constructor_header_mode, "Generate the constructor .h file", "constructor-header", 'C');
  340. args_parser.add_option(constructor_implementation_mode, "Generate the constructor .cpp file", "constructor-implementation", 'O');
  341. args_parser.add_option(prototype_header_mode, "Generate the prototype .h file", "prototype-header", 'P');
  342. args_parser.add_option(prototype_implementation_mode, "Generate the prototype .cpp file", "prototype-implementation", 'R');
  343. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  344. args_parser.parse(argc, argv);
  345. auto file_or_error = Core::File::open(path, Core::OpenMode::ReadOnly);
  346. if (file_or_error.is_error()) {
  347. warnln("Failed to open {}: {}", path, file_or_error.error());
  348. return 1;
  349. }
  350. LexicalPath lexical_path(path);
  351. auto& namespace_ = lexical_path.parts_view().at(lexical_path.parts_view().size() - 2);
  352. auto data = file_or_error.value()->read_all();
  353. auto interface = IDL::parse_interface(path, data);
  354. if (!interface) {
  355. warnln("Cannot parse {}", path);
  356. return 1;
  357. }
  358. if (namespace_.is_one_of("CSS", "DOM", "HTML", "UIEvents", "HighResolutionTime", "NavigationTiming", "SVG", "XHR")) {
  359. StringBuilder builder;
  360. builder.append(namespace_);
  361. builder.append("::");
  362. builder.append(interface->name);
  363. interface->fully_qualified_name = builder.to_string();
  364. } else {
  365. interface->fully_qualified_name = interface->name;
  366. }
  367. if constexpr (WRAPPER_GENERATOR_DEBUG) {
  368. dbgln("Attributes:");
  369. for (auto& attribute : interface->attributes) {
  370. dbgln(" {}{}{} {}",
  371. attribute.readonly ? "readonly " : "",
  372. attribute.type.name,
  373. attribute.type.nullable ? "?" : "",
  374. attribute.name);
  375. }
  376. dbgln("Functions:");
  377. for (auto& function : interface->functions) {
  378. dbgln(" {}{} {}",
  379. function.return_type.name,
  380. function.return_type.nullable ? "?" : "",
  381. function.name);
  382. for (auto& parameter : function.parameters) {
  383. dbgln(" {}{} {}",
  384. parameter.type.name,
  385. parameter.type.nullable ? "?" : "",
  386. parameter.name);
  387. }
  388. }
  389. dbgln("Static Functions:");
  390. for (auto& function : interface->static_functions) {
  391. dbgln(" static {}{} {}",
  392. function.return_type.name,
  393. function.return_type.nullable ? "?" : "",
  394. function.name);
  395. for (auto& parameter : function.parameters) {
  396. dbgln(" {}{} {}",
  397. parameter.type.name,
  398. parameter.type.nullable ? "?" : "",
  399. parameter.name);
  400. }
  401. }
  402. }
  403. if (header_mode)
  404. generate_header(*interface);
  405. if (implementation_mode)
  406. generate_implementation(*interface);
  407. if (constructor_header_mode)
  408. generate_constructor_header(*interface);
  409. if (constructor_implementation_mode)
  410. generate_constructor_implementation(*interface);
  411. if (prototype_header_mode)
  412. generate_prototype_header(*interface);
  413. if (prototype_implementation_mode)
  414. generate_prototype_implementation(*interface);
  415. return 0;
  416. }
  417. static bool should_emit_wrapper_factory(IDL::Interface const& interface)
  418. {
  419. // FIXME: This is very hackish.
  420. if (interface.name == "Event")
  421. return false;
  422. if (interface.name == "EventTarget")
  423. return false;
  424. if (interface.name == "Node")
  425. return false;
  426. if (interface.name == "Text")
  427. return false;
  428. if (interface.name == "Document")
  429. return false;
  430. if (interface.name == "DocumentType")
  431. return false;
  432. if (interface.name.ends_with("Element"))
  433. return false;
  434. return true;
  435. }
  436. static bool is_wrappable_type(IDL::Type const& type)
  437. {
  438. if (type.name == "Node")
  439. return true;
  440. if (type.name == "Document")
  441. return true;
  442. if (type.name == "Text")
  443. return true;
  444. if (type.name == "DocumentType")
  445. return true;
  446. if (type.name.ends_with("Element"))
  447. return true;
  448. if (type.name.ends_with("Event"))
  449. return true;
  450. if (type.name == "ImageData")
  451. return true;
  452. return false;
  453. }
  454. template<typename ParameterType>
  455. static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter, String const& js_name, String const& js_suffix, String const& cpp_name, bool return_void = false, bool legacy_null_to_empty_string = false, bool optional = false, Optional<String> optional_default_value = {})
  456. {
  457. auto scoped_generator = generator.fork();
  458. scoped_generator.set("cpp_name", make_input_acceptable_cpp(cpp_name));
  459. scoped_generator.set("js_name", js_name);
  460. scoped_generator.set("js_suffix", js_suffix);
  461. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  462. scoped_generator.set("parameter.type.name", parameter.type.name);
  463. if (optional_default_value.has_value())
  464. scoped_generator.set("parameter.optional_default_value", *optional_default_value);
  465. if (return_void)
  466. scoped_generator.set("return_statement", "return;");
  467. else
  468. scoped_generator.set("return_statement", "return {};");
  469. // FIXME: Add support for optional, nullable and default values to all types
  470. if (parameter.type.is_string()) {
  471. if (!optional) {
  472. if (!parameter.type.nullable) {
  473. scoped_generator.append(R"~~~(
  474. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  475. if (vm.exception())
  476. @return_statement@
  477. )~~~");
  478. } else {
  479. scoped_generator.append(R"~~~(
  480. String @cpp_name@;
  481. if (!@js_name@@js_suffix@.is_nullish()) {
  482. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  483. if (vm.exception())
  484. @return_statement@
  485. }
  486. )~~~");
  487. }
  488. } else {
  489. scoped_generator.append(R"~~~(
  490. String @cpp_name@;
  491. if (!@js_name@@js_suffix@.is_undefined()) {
  492. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  493. if (vm.exception())
  494. @return_statement@
  495. })~~~");
  496. if (optional_default_value.has_value() && (!parameter.type.nullable || optional_default_value.value() != "null")) {
  497. scoped_generator.append(R"~~~( else {
  498. @cpp_name@ = @parameter.optional_default_value@;
  499. }
  500. )~~~");
  501. } else {
  502. scoped_generator.append(R"~~~(
  503. )~~~");
  504. }
  505. }
  506. } else if (parameter.type.name == "EventListener") {
  507. if (parameter.type.nullable) {
  508. scoped_generator.append(R"~~~(
  509. RefPtr<EventListener> @cpp_name@;
  510. if (!@js_name@@js_suffix@.is_nullish()) {
  511. if (!@js_name@@js_suffix@.is_function()) {
  512. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "Function");
  513. @return_statement@
  514. }
  515. @cpp_name@ = adopt_ref(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  516. }
  517. )~~~");
  518. } else {
  519. scoped_generator.append(R"~~~(
  520. if (!@js_name@@js_suffix@.is_function()) {
  521. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "Function");
  522. @return_statement@
  523. }
  524. auto @cpp_name@ = adopt_ref(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  525. )~~~");
  526. }
  527. } else if (is_wrappable_type(parameter.type)) {
  528. if (!parameter.type.nullable) {
  529. scoped_generator.append(R"~~~(
  530. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  531. if (vm.exception())
  532. @return_statement@
  533. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  534. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  535. @return_statement@
  536. }
  537. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  538. )~~~");
  539. } else {
  540. scoped_generator.append(R"~~~(
  541. @parameter.type.name@* @cpp_name@ = nullptr;
  542. if (!@js_name@@js_suffix@.is_nullish()) {
  543. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  544. if (vm.exception())
  545. @return_statement@
  546. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  547. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@parameter.type.name@");
  548. @return_statement@
  549. }
  550. @cpp_name@ = &static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  551. }
  552. )~~~");
  553. }
  554. } else if (parameter.type.name == "double") {
  555. if (!optional) {
  556. scoped_generator.append(R"~~~(
  557. double @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  558. if (vm.exception())
  559. @return_statement@
  560. )~~~");
  561. } else {
  562. if (optional_default_value.has_value()) {
  563. scoped_generator.append(R"~~~(
  564. double @cpp_name@;
  565. )~~~");
  566. } else {
  567. scoped_generator.append(R"~~~(
  568. Optional<double> @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_double(global_object);
  574. if (vm.exception())
  575. @return_statement@
  576. }
  577. )~~~");
  578. if (optional_default_value.has_value()) {
  579. scoped_generator.append(R"~~~(
  580. else
  581. @cpp_name@ = @parameter.optional_default_value@;
  582. )~~~");
  583. } else {
  584. scoped_generator.append(R"~~~(
  585. )~~~");
  586. }
  587. }
  588. } else if (parameter.type.name == "boolean") {
  589. if (!optional) {
  590. scoped_generator.append(R"~~~(
  591. bool @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  592. )~~~");
  593. } else {
  594. if (optional_default_value.has_value()) {
  595. scoped_generator.append(R"~~~(
  596. bool @cpp_name@;
  597. )~~~");
  598. } else {
  599. scoped_generator.append(R"~~~(
  600. Optional<bool> @cpp_name@;
  601. )~~~");
  602. }
  603. scoped_generator.append(R"~~~(
  604. if (!@js_name@@js_suffix@.is_undefined())
  605. @cpp_name@ = @js_name@@js_suffix@.to_boolean();)~~~");
  606. if (optional_default_value.has_value()) {
  607. scoped_generator.append(R"~~~(
  608. else
  609. @cpp_name@ = @parameter.optional_default_value@;
  610. )~~~");
  611. } else {
  612. scoped_generator.append(R"~~~(
  613. )~~~");
  614. }
  615. }
  616. } else if (parameter.type.name == "unsigned long") {
  617. scoped_generator.append(R"~~~(
  618. auto @cpp_name@ = @js_name@@js_suffix@.to_u32(global_object);
  619. if (vm.exception())
  620. @return_statement@
  621. )~~~");
  622. } else if (parameter.type.name == "unsigned short") {
  623. scoped_generator.append(R"~~~(
  624. auto @cpp_name@ = (u16)@js_name@@js_suffix@.to_u32(global_object);
  625. if (vm.exception())
  626. @return_statement@
  627. )~~~");
  628. } else if (parameter.type.name == "long") {
  629. scoped_generator.append(R"~~~(
  630. auto @cpp_name@ = @js_name@@js_suffix@.to_i32(global_object);
  631. if (vm.exception())
  632. @return_statement@
  633. )~~~");
  634. } else if (parameter.type.name == "EventHandler") {
  635. // x.onfoo = function() { ... }
  636. scoped_generator.append(R"~~~(
  637. HTML::EventHandler @cpp_name@;
  638. if (@js_name@@js_suffix@.is_function()) {
  639. @cpp_name@.callback = JS::make_handle(&@js_name@@js_suffix@.as_function());
  640. } else if (@js_name@@js_suffix@.is_string()) {
  641. @cpp_name@.string = @js_name@@js_suffix@.as_string().string();
  642. } else {
  643. @return_statement@
  644. }
  645. )~~~");
  646. } else if (parameter.type.name == "any") {
  647. scoped_generator.append(R"~~~(
  648. auto @cpp_name@ = @js_name@@js_suffix@;
  649. )~~~");
  650. } else {
  651. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  652. VERIFY_NOT_REACHED();
  653. }
  654. }
  655. template<typename FunctionType>
  656. static void generate_argument_count_check(SourceGenerator& generator, FunctionType& function)
  657. {
  658. auto argument_count_check_generator = generator.fork();
  659. argument_count_check_generator.set("function.name", function.name);
  660. argument_count_check_generator.set("function.nargs", String::number(function.length()));
  661. if (function.length() == 0)
  662. return;
  663. if (function.length() == 1) {
  664. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  665. argument_count_check_generator.set(".arg_count_suffix", "");
  666. } else {
  667. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  668. argument_count_check_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  669. }
  670. argument_count_check_generator.append(R"~~~(
  671. if (vm.argument_count() < @function.nargs@) {
  672. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  673. return {};
  674. }
  675. )~~~");
  676. }
  677. static void generate_arguments(SourceGenerator& generator, Vector<IDL::Parameter> const& parameters, StringBuilder& arguments_builder, bool return_void = false)
  678. {
  679. auto arguments_generator = generator.fork();
  680. Vector<String> parameter_names;
  681. size_t argument_index = 0;
  682. for (auto& parameter : parameters) {
  683. parameter_names.append(make_input_acceptable_cpp(parameter.name.to_snakecase()));
  684. arguments_generator.set("argument.index", String::number(argument_index));
  685. arguments_generator.append(R"~~~(
  686. auto arg@argument.index@ = vm.argument(@argument.index@);
  687. )~~~");
  688. bool legacy_null_to_empty_string = parameter.extended_attributes.contains("LegacyNullToEmptyString");
  689. 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);
  690. ++argument_index;
  691. }
  692. arguments_builder.join(", ", parameter_names);
  693. }
  694. static void generate_return_statement(SourceGenerator& generator, IDL::Type const& return_type)
  695. {
  696. auto scoped_generator = generator.fork();
  697. scoped_generator.set("return_type", return_type.name);
  698. if (return_type.name == "undefined") {
  699. scoped_generator.append(R"~~~(
  700. return JS::js_undefined();
  701. )~~~");
  702. return;
  703. }
  704. if (return_type.nullable) {
  705. if (return_type.is_string()) {
  706. scoped_generator.append(R"~~~(
  707. if (retval.is_null())
  708. return JS::js_null();
  709. )~~~");
  710. } else {
  711. scoped_generator.append(R"~~~(
  712. if (!retval)
  713. return JS::js_null();
  714. )~~~");
  715. }
  716. }
  717. if (return_type.is_string()) {
  718. scoped_generator.append(R"~~~(
  719. return JS::js_string(vm, retval);
  720. )~~~");
  721. } else if (return_type.name == "ArrayFromVector") {
  722. // FIXME: Remove this fake type hack once it's no longer needed.
  723. // Basically once we have NodeList we can throw this out.
  724. scoped_generator.append(R"~~~(
  725. auto* new_array = JS::Array::create(global_object, 0);
  726. for (auto& element : retval)
  727. new_array->indexed_properties().append(wrap(global_object, element));
  728. return new_array;
  729. )~~~");
  730. } else if (return_type.name == "boolean" || return_type.name == "double") {
  731. scoped_generator.append(R"~~~(
  732. return JS::Value(retval);
  733. )~~~");
  734. } else if (return_type.name == "short" || return_type.name == "unsigned short" || return_type.name == "long" || return_type.name == "unsigned long") {
  735. scoped_generator.append(R"~~~(
  736. return JS::Value((i32)retval);
  737. )~~~");
  738. } else if (return_type.name == "Uint8ClampedArray") {
  739. scoped_generator.append(R"~~~(
  740. return retval;
  741. )~~~");
  742. } else if (return_type.name == "EventHandler") {
  743. scoped_generator.append(R"~~~(
  744. if (retval.callback.is_null())
  745. return JS::js_null();
  746. return retval.callback.cell();
  747. )~~~");
  748. } else {
  749. scoped_generator.append(R"~~~(
  750. return wrap(global_object, const_cast<@return_type@&>(*retval));
  751. )~~~");
  752. }
  753. }
  754. enum class StaticFunction {
  755. No,
  756. Yes,
  757. };
  758. static void generate_function(SourceGenerator& generator, IDL::Function const& function, StaticFunction is_static_function, String const& class_name, String const& interface_fully_qualified_name)
  759. {
  760. auto function_generator = generator.fork();
  761. function_generator.set("class_name", class_name);
  762. function_generator.set("interface_fully_qualified_name", interface_fully_qualified_name);
  763. function_generator.set("function.name", function.name);
  764. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  765. if (function.extended_attributes.contains("ImplementedAs")) {
  766. auto implemented_as = function.extended_attributes.get("ImplementedAs").value();
  767. function_generator.set("function.cpp_name", implemented_as);
  768. } else {
  769. function_generator.set("function.cpp_name", function.name.to_snakecase());
  770. }
  771. function_generator.append(R"~~~(
  772. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@function.name:snakecase@)
  773. {
  774. )~~~");
  775. if (is_static_function == StaticFunction::No) {
  776. function_generator.append(R"~~~(
  777. auto* impl = impl_from(vm, global_object);
  778. if (!impl)
  779. return {};
  780. )~~~");
  781. }
  782. generate_argument_count_check(generator, function);
  783. StringBuilder arguments_builder;
  784. generate_arguments(generator, function.parameters, arguments_builder);
  785. function_generator.set(".arguments", arguments_builder.string_view());
  786. if (is_static_function == StaticFunction::No) {
  787. function_generator.append(R"~~~(
  788. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->@function.cpp_name@(@.arguments@); });
  789. )~~~");
  790. } else {
  791. function_generator.append(R"~~~(
  792. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return @interface_fully_qualified_name@::@function.cpp_name@(@.arguments@); });
  793. )~~~");
  794. }
  795. function_generator.append(R"~~~(
  796. if (should_return_empty(result))
  797. return JS::Value();
  798. [[maybe_unused]] auto retval = result.release_value();
  799. )~~~");
  800. generate_return_statement(generator, function.return_type);
  801. function_generator.append(R"~~~(
  802. }
  803. )~~~");
  804. }
  805. static void generate_header(IDL::Interface const& interface)
  806. {
  807. StringBuilder builder;
  808. SourceGenerator generator { builder };
  809. generator.set("name", interface.name);
  810. generator.set("fully_qualified_name", interface.fully_qualified_name);
  811. generator.set("wrapper_base_class", interface.wrapper_base_class);
  812. generator.set("wrapper_class", interface.wrapper_class);
  813. generator.set("wrapper_class:snakecase", interface.wrapper_class.to_snakecase());
  814. generator.append(R"~~~(
  815. #pragma once
  816. #include <LibWeb/Bindings/Wrapper.h>
  817. // FIXME: This is very strange.
  818. #if __has_include(<LibWeb/CSS/@name@.h>)
  819. # include <LibWeb/CSS/@name@.h>
  820. #elif __has_include(<LibWeb/DOM/@name@.h>)
  821. # include <LibWeb/DOM/@name@.h>
  822. #elif __has_include(<LibWeb/HTML/@name@.h>)
  823. # include <LibWeb/HTML/@name@.h>
  824. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  825. # include <LibWeb/UIEvents/@name@.h>
  826. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  827. # include <LibWeb/HighResolutionTime/@name@.h>
  828. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  829. # include <LibWeb/NavigationTiming/@name@.h>
  830. #elif __has_include(<LibWeb/SVG/@name@.h>)
  831. # include <LibWeb/SVG/@name@.h>
  832. #elif __has_include(<LibWeb/XHR/@name@.h>)
  833. # include <LibWeb/XHR/@name@.h>
  834. #endif
  835. )~~~");
  836. if (interface.wrapper_base_class != "Wrapper") {
  837. generator.append(R"~~~(
  838. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  839. )~~~");
  840. }
  841. generator.append(R"~~~(
  842. namespace Web::Bindings {
  843. class @wrapper_class@ : public @wrapper_base_class@ {
  844. JS_OBJECT(@name@, @wrapper_base_class@);
  845. public:
  846. static @wrapper_class@* create(JS::GlobalObject&, @fully_qualified_name@&);
  847. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  848. virtual void initialize(JS::GlobalObject&) override;
  849. virtual ~@wrapper_class@() override;
  850. )~~~");
  851. if (interface.extended_attributes.contains("CustomGet")) {
  852. generator.append(R"~~~(
  853. virtual JS::Value internal_get(JS::PropertyName const&, JS::Value receiver) const override;
  854. )~~~");
  855. }
  856. if (interface.extended_attributes.contains("CustomSet")) {
  857. generator.append(R"~~~(
  858. virtual bool internal_set(JS::PropertyName const&, JS::Value, JS::Value receiver) override;
  859. )~~~");
  860. }
  861. if (interface.extended_attributes.contains("CustomHasProperty")) {
  862. generator.append(R"~~~(
  863. virtual bool internal_has_property(JS::PropertyName const&) const override;
  864. )~~~");
  865. }
  866. if (interface.wrapper_base_class == "Wrapper") {
  867. generator.append(R"~~~(
  868. @fully_qualified_name@& impl() { return *m_impl; }
  869. @fully_qualified_name@ const& impl() const { return *m_impl; }
  870. )~~~");
  871. } else {
  872. generator.append(R"~~~(
  873. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  874. @fully_qualified_name@ const& impl() const { return static_cast<@fully_qualified_name@ const&>(@wrapper_base_class@::impl()); }
  875. )~~~");
  876. }
  877. generator.append(R"~~~(
  878. private:
  879. )~~~");
  880. if (interface.wrapper_base_class == "Wrapper") {
  881. generator.append(R"~~~(
  882. NonnullRefPtr<@fully_qualified_name@> m_impl;
  883. )~~~");
  884. }
  885. generator.append(R"~~~(
  886. };
  887. )~~~");
  888. if (should_emit_wrapper_factory(interface)) {
  889. generator.append(R"~~~(
  890. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  891. )~~~");
  892. }
  893. generator.append(R"~~~(
  894. } // namespace Web::Bindings
  895. )~~~");
  896. outln("{}", generator.as_string_view());
  897. }
  898. void generate_implementation(IDL::Interface const& interface)
  899. {
  900. StringBuilder builder;
  901. SourceGenerator generator { builder };
  902. generator.set("name", interface.name);
  903. generator.set("wrapper_class", interface.wrapper_class);
  904. generator.set("wrapper_base_class", interface.wrapper_base_class);
  905. generator.set("prototype_class", interface.prototype_class);
  906. generator.set("fully_qualified_name", interface.fully_qualified_name);
  907. generator.append(R"~~~(
  908. #include <AK/FlyString.h>
  909. #include <LibJS/Runtime/Array.h>
  910. #include <LibJS/Runtime/Error.h>
  911. #include <LibJS/Runtime/FunctionObject.h>
  912. #include <LibJS/Runtime/GlobalObject.h>
  913. #include <LibJS/Runtime/TypedArray.h>
  914. #include <LibJS/Runtime/Value.h>
  915. #include <LibWeb/Bindings/@prototype_class@.h>
  916. #include <LibWeb/Bindings/@wrapper_class@.h>
  917. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  918. #include <LibWeb/Bindings/CommentWrapper.h>
  919. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  920. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  921. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  922. #include <LibWeb/Bindings/DocumentWrapper.h>
  923. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  924. #include <LibWeb/Bindings/EventWrapperFactory.h>
  925. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  926. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  927. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  928. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  929. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  930. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  931. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  932. #include <LibWeb/Bindings/ImageDataWrapper.h>
  933. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  934. #include <LibWeb/Bindings/TextWrapper.h>
  935. #include <LibWeb/Bindings/WindowObject.h>
  936. #include <LibWeb/DOM/Element.h>
  937. #include <LibWeb/DOM/EventListener.h>
  938. #include <LibWeb/HTML/HTMLElement.h>
  939. #include <LibWeb/Origin.h>
  940. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  941. using namespace Web::CSS;
  942. using namespace Web::DOM;
  943. using namespace Web::HTML;
  944. namespace Web::Bindings {
  945. @wrapper_class@* @wrapper_class@::create(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  946. {
  947. return global_object.heap().allocate<@wrapper_class@>(global_object, global_object, impl);
  948. }
  949. )~~~");
  950. if (interface.wrapper_base_class == "Wrapper") {
  951. generator.append(R"~~~(
  952. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  953. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  954. , m_impl(impl)
  955. {
  956. }
  957. )~~~");
  958. } else {
  959. generator.append(R"~~~(
  960. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  961. : @wrapper_base_class@(global_object, impl)
  962. {
  963. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  964. VERIFY(success);
  965. }
  966. )~~~");
  967. }
  968. generator.append(R"~~~(
  969. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  970. {
  971. @wrapper_base_class@::initialize(global_object);
  972. }
  973. @wrapper_class@::~@wrapper_class@()
  974. {
  975. }
  976. )~~~");
  977. if (should_emit_wrapper_factory(interface)) {
  978. generator.append(R"~~~(
  979. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  980. {
  981. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  982. }
  983. )~~~");
  984. }
  985. generator.append(R"~~~(
  986. } // namespace Web::Bindings
  987. )~~~");
  988. outln("{}", generator.as_string_view());
  989. }
  990. static void generate_constructor_header(IDL::Interface const& interface)
  991. {
  992. StringBuilder builder;
  993. SourceGenerator generator { builder };
  994. generator.set("name", interface.name);
  995. generator.set("fully_qualified_name", interface.fully_qualified_name);
  996. generator.set("constructor_class", interface.constructor_class);
  997. generator.set("constructor_class:snakecase", interface.constructor_class.to_snakecase());
  998. generator.append(R"~~~(
  999. #pragma once
  1000. #include <LibJS/Runtime/NativeFunction.h>
  1001. namespace Web::Bindings {
  1002. class @constructor_class@ : public JS::NativeFunction {
  1003. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  1004. public:
  1005. explicit @constructor_class@(JS::GlobalObject&);
  1006. virtual void initialize(JS::GlobalObject&) override;
  1007. virtual ~@constructor_class@() override;
  1008. virtual JS::Value call() override;
  1009. virtual JS::Value construct(JS::FunctionObject& new_target) override;
  1010. private:
  1011. virtual bool has_constructor() const override { return true; }
  1012. )~~~");
  1013. for (auto& function : interface.static_functions) {
  1014. auto function_generator = generator.fork();
  1015. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1016. function_generator.append(R"~~~(
  1017. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1018. )~~~");
  1019. }
  1020. generator.append(R"~~~(
  1021. };
  1022. } // namespace Web::Bindings
  1023. )~~~");
  1024. outln("{}", generator.as_string_view());
  1025. }
  1026. void generate_constructor_implementation(IDL::Interface const& interface)
  1027. {
  1028. StringBuilder builder;
  1029. SourceGenerator generator { builder };
  1030. generator.set("name", interface.name);
  1031. generator.set("prototype_class", interface.prototype_class);
  1032. generator.set("wrapper_class", interface.wrapper_class);
  1033. generator.set("constructor_class", interface.constructor_class);
  1034. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1035. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1036. generator.append(R"~~~(
  1037. #include <LibJS/Heap/Heap.h>
  1038. #include <LibJS/Runtime/GlobalObject.h>
  1039. #include <LibWeb/Bindings/@constructor_class@.h>
  1040. #include <LibWeb/Bindings/@prototype_class@.h>
  1041. #include <LibWeb/Bindings/@wrapper_class@.h>
  1042. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1043. #include <LibWeb/Bindings/WindowObject.h>
  1044. #if __has_include(<LibWeb/CSS/@name@.h>)
  1045. # include <LibWeb/CSS/@name@.h>
  1046. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1047. # include <LibWeb/DOM/@name@.h>
  1048. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1049. # include <LibWeb/HTML/@name@.h>
  1050. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1051. # include <LibWeb/UIEvents/@name@.h>
  1052. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1053. # include <LibWeb/HighResolutionTime/@name@.h>
  1054. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1055. # include <LibWeb/NavigationTiming/@name@.h>
  1056. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1057. # include <LibWeb/SVG/@name@.h>
  1058. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1059. # include <LibWeb/XHR/@name@.h>
  1060. #endif
  1061. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1062. using namespace Web::CSS;
  1063. using namespace Web::DOM;
  1064. using namespace Web::HTML;
  1065. namespace Web::Bindings {
  1066. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  1067. : NativeFunction(*global_object.function_prototype())
  1068. {
  1069. }
  1070. @constructor_class@::~@constructor_class@()
  1071. {
  1072. }
  1073. JS::Value @constructor_class@::call()
  1074. {
  1075. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  1076. return {};
  1077. }
  1078. JS::Value @constructor_class@::construct(FunctionObject&)
  1079. {
  1080. )~~~");
  1081. if (interface.constructors.is_empty()) {
  1082. // No constructor
  1083. generator.set("constructor.length", "0");
  1084. generator.append(R"~~~(
  1085. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::NotAConstructor, "@name@");
  1086. return {};
  1087. )~~~");
  1088. } else if (interface.constructors.size() == 1) {
  1089. // Single constructor
  1090. auto& constructor = interface.constructors[0];
  1091. generator.set("constructor.length", String::number(constructor.length()));
  1092. generator.append(R"~~~(
  1093. [[maybe_unused]] auto& vm = this->vm();
  1094. auto& global_object = this->global_object();
  1095. auto& window = static_cast<WindowObject&>(global_object);
  1096. )~~~");
  1097. if (!constructor.parameters.is_empty()) {
  1098. generate_argument_count_check(generator, constructor);
  1099. StringBuilder arguments_builder;
  1100. generate_arguments(generator, constructor.parameters, arguments_builder);
  1101. generator.set(".constructor_arguments", arguments_builder.string_view());
  1102. generator.append(R"~~~(
  1103. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window, @.constructor_arguments@); });
  1104. )~~~");
  1105. } else {
  1106. generator.append(R"~~~(
  1107. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window); });
  1108. )~~~");
  1109. }
  1110. generator.append(R"~~~(
  1111. if (should_return_empty(impl))
  1112. return JS::Value();
  1113. return @wrapper_class@::create(global_object, impl.release_value());
  1114. )~~~");
  1115. } else {
  1116. // Multiple constructor overloads - can't do that yet.
  1117. TODO();
  1118. }
  1119. generator.append(R"~~~(
  1120. }
  1121. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  1122. {
  1123. auto& vm = this->vm();
  1124. auto& window = static_cast<WindowObject&>(global_object);
  1125. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  1126. NativeFunction::initialize(global_object);
  1127. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  1128. define_direct_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  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_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1136. )~~~");
  1137. }
  1138. // https://heycam.github.io/webidl/#es-operations
  1139. for (auto& function : interface.static_functions) {
  1140. auto function_generator = generator.fork();
  1141. function_generator.set("function.name", function.name);
  1142. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1143. function_generator.set("function.length", String::number(function.length()));
  1144. function_generator.append(R"~~~(
  1145. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1146. )~~~");
  1147. }
  1148. generator.append(R"~~~(
  1149. }
  1150. )~~~");
  1151. // Implementation: Static Functions
  1152. for (auto& function : interface.static_functions) {
  1153. generate_function(generator, function, StaticFunction::Yes, interface.constructor_class, interface.fully_qualified_name);
  1154. }
  1155. generator.append(R"~~~(
  1156. } // namespace Web::Bindings
  1157. )~~~");
  1158. outln("{}", generator.as_string_view());
  1159. }
  1160. static void generate_prototype_header(IDL::Interface const& interface)
  1161. {
  1162. StringBuilder builder;
  1163. SourceGenerator generator { builder };
  1164. generator.set("name", interface.name);
  1165. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1166. generator.set("prototype_class", interface.prototype_class);
  1167. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1168. generator.append(R"~~~(
  1169. #pragma once
  1170. #include <LibJS/Runtime/Object.h>
  1171. namespace Web::Bindings {
  1172. class @prototype_class@ : public JS::Object {
  1173. JS_OBJECT(@prototype_class@, JS::Object);
  1174. public:
  1175. explicit @prototype_class@(JS::GlobalObject&);
  1176. virtual void initialize(JS::GlobalObject&) override;
  1177. virtual ~@prototype_class@() override;
  1178. private:
  1179. )~~~");
  1180. for (auto& function : interface.functions) {
  1181. auto function_generator = generator.fork();
  1182. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1183. function_generator.append(R"~~~(
  1184. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1185. )~~~");
  1186. }
  1187. for (auto& attribute : interface.attributes) {
  1188. auto attribute_generator = generator.fork();
  1189. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1190. attribute_generator.append(R"~~~(
  1191. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_getter);
  1192. )~~~");
  1193. if (!attribute.readonly) {
  1194. attribute_generator.append(R"~~~(
  1195. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_setter);
  1196. )~~~");
  1197. }
  1198. }
  1199. generator.append(R"~~~(
  1200. };
  1201. } // namespace Web::Bindings
  1202. )~~~");
  1203. outln("{}", generator.as_string_view());
  1204. }
  1205. void generate_prototype_implementation(IDL::Interface const& interface)
  1206. {
  1207. StringBuilder builder;
  1208. SourceGenerator generator { builder };
  1209. generator.set("name", interface.name);
  1210. generator.set("parent_name", interface.parent_name);
  1211. generator.set("prototype_class", interface.prototype_class);
  1212. generator.set("prototype_base_class", interface.prototype_base_class);
  1213. generator.set("wrapper_class", interface.wrapper_class);
  1214. generator.set("constructor_class", interface.constructor_class);
  1215. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1216. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1217. generator.append(R"~~~(
  1218. #include <AK/Function.h>
  1219. #include <LibJS/Runtime/Array.h>
  1220. #include <LibJS/Runtime/Error.h>
  1221. #include <LibJS/Runtime/FunctionObject.h>
  1222. #include <LibJS/Runtime/GlobalObject.h>
  1223. #include <LibJS/Runtime/TypedArray.h>
  1224. #include <LibWeb/Bindings/@prototype_class@.h>
  1225. #include <LibWeb/Bindings/@wrapper_class@.h>
  1226. #include <LibWeb/Bindings/AbortSignalWrapper.h>
  1227. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  1228. #include <LibWeb/Bindings/CSSStyleSheetWrapper.h>
  1229. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  1230. #include <LibWeb/Bindings/CommentWrapper.h>
  1231. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  1232. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  1233. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  1234. #include <LibWeb/Bindings/DocumentWrapper.h>
  1235. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  1236. #include <LibWeb/Bindings/EventWrapper.h>
  1237. #include <LibWeb/Bindings/EventWrapperFactory.h>
  1238. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1239. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  1240. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  1241. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  1242. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  1243. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  1244. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  1245. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  1246. #include <LibWeb/Bindings/ImageDataWrapper.h>
  1247. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  1248. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  1249. #include <LibWeb/Bindings/RangeWrapper.h>
  1250. #include <LibWeb/Bindings/StyleSheetListWrapper.h>
  1251. #include <LibWeb/Bindings/TextWrapper.h>
  1252. #include <LibWeb/Bindings/WindowObject.h>
  1253. #include <LibWeb/DOM/Element.h>
  1254. #include <LibWeb/DOM/EventListener.h>
  1255. #include <LibWeb/DOM/Range.h>
  1256. #include <LibWeb/DOM/Window.h>
  1257. #include <LibWeb/HTML/EventHandler.h>
  1258. #include <LibWeb/HTML/HTMLElement.h>
  1259. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  1260. #include <LibWeb/Origin.h>
  1261. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  1262. # include <LibWeb/Bindings/@prototype_base_class@.h>
  1263. #endif
  1264. #if __has_include(<LibWeb/CSS/@name@.h>)
  1265. # include <LibWeb/CSS/@name@.h>
  1266. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1267. # include <LibWeb/DOM/@name@.h>
  1268. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1269. # include <LibWeb/HTML/@name@.h>
  1270. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1271. # include <LibWeb/UIEvents/@name@.h>
  1272. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1273. # include <LibWeb/HighResolutionTime/@name@.h>
  1274. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1275. # include <LibWeb/NavigationTiming/@name@.h>
  1276. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1277. # include <LibWeb/SVG/@name@.h>
  1278. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1279. # include <LibWeb/XHR/@name@.h>
  1280. #endif
  1281. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1282. using namespace Web::CSS;
  1283. using namespace Web::DOM;
  1284. using namespace Web::HTML;
  1285. using namespace Web::NavigationTiming;
  1286. using namespace Web::XHR;
  1287. namespace Web::Bindings {
  1288. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  1289. : Object(*global_object.object_prototype())
  1290. {
  1291. )~~~");
  1292. if (interface.name == "DOMException") {
  1293. // https://heycam.github.io/webidl/#es-DOMException-specialness
  1294. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  1295. generator.append(R"~~~(
  1296. auto success = internal_set_prototype_of(global_object.error_prototype());
  1297. VERIFY(success);
  1298. )~~~");
  1299. } else if (!interface.parent_name.is_empty()) {
  1300. generator.append(R"~~~(
  1301. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  1302. VERIFY(success);
  1303. )~~~");
  1304. }
  1305. // FIXME: Currently almost everything gets default_attributes but it should be configurable per attribute.
  1306. // See the spec links for details
  1307. generator.append(R"~~~(
  1308. }
  1309. @prototype_class@::~@prototype_class@()
  1310. {
  1311. }
  1312. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  1313. {
  1314. [[maybe_unused]] auto& vm = this->vm();
  1315. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;
  1316. )~~~");
  1317. // https://heycam.github.io/webidl/#es-attributes
  1318. for (auto& attribute : interface.attributes) {
  1319. auto attribute_generator = generator.fork();
  1320. attribute_generator.set("attribute.name", attribute.name);
  1321. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1322. if (attribute.readonly)
  1323. attribute_generator.set("attribute.setter_callback", "nullptr");
  1324. else
  1325. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1326. attribute_generator.append(R"~~~(
  1327. define_native_accessor("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  1328. )~~~");
  1329. }
  1330. // https://heycam.github.io/webidl/#es-constants
  1331. for (auto& constant : interface.constants) {
  1332. auto constant_generator = generator.fork();
  1333. constant_generator.set("constant.name", constant.name);
  1334. constant_generator.set("constant.value", constant.value);
  1335. constant_generator.append(R"~~~(
  1336. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1337. )~~~");
  1338. }
  1339. // https://heycam.github.io/webidl/#es-operations
  1340. for (auto& function : interface.functions) {
  1341. auto function_generator = generator.fork();
  1342. function_generator.set("function.name", function.name);
  1343. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1344. function_generator.set("function.length", String::number(function.length()));
  1345. function_generator.append(R"~~~(
  1346. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1347. )~~~");
  1348. }
  1349. generator.append(R"~~~(
  1350. Object::initialize(global_object);
  1351. }
  1352. )~~~");
  1353. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  1354. generator.append(R"~~~(
  1355. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  1356. {
  1357. auto* this_object = vm.this_value(global_object).to_object(global_object);
  1358. if (!this_object)
  1359. return {};
  1360. )~~~");
  1361. if (interface.name == "EventTarget") {
  1362. generator.append(R"~~~(
  1363. if (is<WindowObject>(this_object)) {
  1364. return &static_cast<WindowObject*>(this_object)->impl();
  1365. }
  1366. )~~~");
  1367. }
  1368. generator.append(R"~~~(
  1369. if (!is<@wrapper_class@>(this_object)) {
  1370. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@fully_qualified_name@");
  1371. return nullptr;
  1372. }
  1373. return &static_cast<@wrapper_class@*>(this_object)->impl();
  1374. }
  1375. )~~~");
  1376. }
  1377. for (auto& attribute : interface.attributes) {
  1378. auto attribute_generator = generator.fork();
  1379. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1380. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1381. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1382. if (attribute.extended_attributes.contains("ImplementedAs")) {
  1383. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  1384. attribute_generator.set("attribute.cpp_getter_name", implemented_as);
  1385. } else {
  1386. attribute_generator.set("attribute.cpp_getter_name", attribute.name.to_snakecase());
  1387. }
  1388. if (attribute.extended_attributes.contains("Reflect")) {
  1389. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1390. if (attribute_name.is_null())
  1391. attribute_name = attribute.name;
  1392. attribute_name = make_input_acceptable_cpp(attribute_name);
  1393. attribute_generator.set("attribute.reflect_name", attribute_name);
  1394. } else {
  1395. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  1396. }
  1397. attribute_generator.append(R"~~~(
  1398. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.getter_callback@)
  1399. {
  1400. auto* impl = impl_from(vm, global_object);
  1401. if (!impl)
  1402. return {};
  1403. )~~~");
  1404. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1405. attribute_generator.append(R"~~~(
  1406. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1407. return JS::js_null();
  1408. )~~~");
  1409. }
  1410. if (attribute.extended_attributes.contains("Reflect")) {
  1411. if (attribute.type.name != "boolean") {
  1412. attribute_generator.append(R"~~~(
  1413. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1414. )~~~");
  1415. } else {
  1416. attribute_generator.append(R"~~~(
  1417. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1418. )~~~");
  1419. }
  1420. } else {
  1421. attribute_generator.append(R"~~~(
  1422. auto retval = impl->@attribute.cpp_getter_name@();
  1423. )~~~");
  1424. }
  1425. generate_return_statement(generator, attribute.type);
  1426. attribute_generator.append(R"~~~(
  1427. }
  1428. )~~~");
  1429. if (!attribute.readonly) {
  1430. attribute_generator.append(R"~~~(
  1431. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.setter_callback@)
  1432. {
  1433. auto* impl = impl_from(vm, global_object);
  1434. if (!impl)
  1435. return {};
  1436. auto value = vm.argument(0);
  1437. )~~~");
  1438. generate_to_cpp(generator, attribute, "value", "", "cpp_value", false, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1439. if (attribute.extended_attributes.contains("Reflect")) {
  1440. if (attribute.type.name != "boolean") {
  1441. attribute_generator.append(R"~~~(
  1442. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1443. )~~~");
  1444. } else {
  1445. attribute_generator.append(R"~~~(
  1446. if (!cpp_value)
  1447. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1448. else
  1449. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1450. )~~~");
  1451. }
  1452. } else {
  1453. attribute_generator.append(R"~~~(
  1454. impl->set_@attribute.name:snakecase@(cpp_value);
  1455. )~~~");
  1456. }
  1457. attribute_generator.append(R"~~~(
  1458. return {};
  1459. }
  1460. )~~~");
  1461. }
  1462. }
  1463. // Implementation: Functions
  1464. for (auto& function : interface.functions) {
  1465. generate_function(generator, function, StaticFunction::No, interface.prototype_class, interface.fully_qualified_name);
  1466. }
  1467. generator.append(R"~~~(
  1468. } // namespace Web::Bindings
  1469. )~~~");
  1470. outln("{}", generator.as_string_view());
  1471. }