WrapperGenerator.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  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 if (return_type.name == "Location") {
  749. // Location is special cased as it is already a JS::Object.
  750. scoped_generator.append(R"~~~(
  751. return JS::Value(retval);
  752. )~~~");
  753. } else {
  754. scoped_generator.append(R"~~~(
  755. return wrap(global_object, const_cast<@return_type@&>(*retval));
  756. )~~~");
  757. }
  758. }
  759. enum class StaticFunction {
  760. No,
  761. Yes,
  762. };
  763. static void generate_function(SourceGenerator& generator, IDL::Function const& function, StaticFunction is_static_function, String const& class_name, String const& interface_fully_qualified_name)
  764. {
  765. auto function_generator = generator.fork();
  766. function_generator.set("class_name", class_name);
  767. function_generator.set("interface_fully_qualified_name", interface_fully_qualified_name);
  768. function_generator.set("function.name", function.name);
  769. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  770. if (function.extended_attributes.contains("ImplementedAs")) {
  771. auto implemented_as = function.extended_attributes.get("ImplementedAs").value();
  772. function_generator.set("function.cpp_name", implemented_as);
  773. } else {
  774. function_generator.set("function.cpp_name", function.name.to_snakecase());
  775. }
  776. function_generator.append(R"~~~(
  777. JS_DEFINE_NATIVE_FUNCTION(@class_name@::@function.name:snakecase@)
  778. {
  779. )~~~");
  780. if (is_static_function == StaticFunction::No) {
  781. function_generator.append(R"~~~(
  782. auto* impl = impl_from(vm, global_object);
  783. if (!impl)
  784. return {};
  785. )~~~");
  786. }
  787. generate_argument_count_check(generator, function);
  788. StringBuilder arguments_builder;
  789. generate_arguments(generator, function.parameters, arguments_builder);
  790. function_generator.set(".arguments", arguments_builder.string_view());
  791. if (is_static_function == StaticFunction::No) {
  792. function_generator.append(R"~~~(
  793. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->@function.cpp_name@(@.arguments@); });
  794. )~~~");
  795. } else {
  796. function_generator.append(R"~~~(
  797. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return @interface_fully_qualified_name@::@function.cpp_name@(@.arguments@); });
  798. )~~~");
  799. }
  800. function_generator.append(R"~~~(
  801. if (should_return_empty(result))
  802. return JS::Value();
  803. [[maybe_unused]] auto retval = result.release_value();
  804. )~~~");
  805. generate_return_statement(generator, function.return_type);
  806. function_generator.append(R"~~~(
  807. }
  808. )~~~");
  809. }
  810. static void generate_header(IDL::Interface const& interface)
  811. {
  812. StringBuilder builder;
  813. SourceGenerator generator { builder };
  814. generator.set("name", interface.name);
  815. generator.set("fully_qualified_name", interface.fully_qualified_name);
  816. generator.set("wrapper_base_class", interface.wrapper_base_class);
  817. generator.set("wrapper_class", interface.wrapper_class);
  818. generator.set("wrapper_class:snakecase", interface.wrapper_class.to_snakecase());
  819. generator.append(R"~~~(
  820. #pragma once
  821. #include <LibWeb/Bindings/Wrapper.h>
  822. // FIXME: This is very strange.
  823. #if __has_include(<LibWeb/CSS/@name@.h>)
  824. # include <LibWeb/CSS/@name@.h>
  825. #elif __has_include(<LibWeb/DOM/@name@.h>)
  826. # include <LibWeb/DOM/@name@.h>
  827. #elif __has_include(<LibWeb/HTML/@name@.h>)
  828. # include <LibWeb/HTML/@name@.h>
  829. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  830. # include <LibWeb/UIEvents/@name@.h>
  831. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  832. # include <LibWeb/HighResolutionTime/@name@.h>
  833. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  834. # include <LibWeb/NavigationTiming/@name@.h>
  835. #elif __has_include(<LibWeb/SVG/@name@.h>)
  836. # include <LibWeb/SVG/@name@.h>
  837. #elif __has_include(<LibWeb/XHR/@name@.h>)
  838. # include <LibWeb/XHR/@name@.h>
  839. #endif
  840. )~~~");
  841. if (interface.wrapper_base_class != "Wrapper") {
  842. generator.append(R"~~~(
  843. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  844. )~~~");
  845. }
  846. generator.append(R"~~~(
  847. namespace Web::Bindings {
  848. class @wrapper_class@ : public @wrapper_base_class@ {
  849. JS_OBJECT(@name@, @wrapper_base_class@);
  850. public:
  851. static @wrapper_class@* create(JS::GlobalObject&, @fully_qualified_name@&);
  852. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  853. virtual void initialize(JS::GlobalObject&) override;
  854. virtual ~@wrapper_class@() override;
  855. )~~~");
  856. if (interface.extended_attributes.contains("CustomGet")) {
  857. generator.append(R"~~~(
  858. virtual JS::Value internal_get(JS::PropertyName const&, JS::Value receiver) const override;
  859. )~~~");
  860. }
  861. if (interface.extended_attributes.contains("CustomSet")) {
  862. generator.append(R"~~~(
  863. virtual bool internal_set(JS::PropertyName const&, JS::Value, JS::Value receiver) override;
  864. )~~~");
  865. }
  866. if (interface.extended_attributes.contains("CustomHasProperty")) {
  867. generator.append(R"~~~(
  868. virtual bool internal_has_property(JS::PropertyName const&) const override;
  869. )~~~");
  870. }
  871. if (interface.wrapper_base_class == "Wrapper") {
  872. generator.append(R"~~~(
  873. @fully_qualified_name@& impl() { return *m_impl; }
  874. @fully_qualified_name@ const& impl() const { return *m_impl; }
  875. )~~~");
  876. } else {
  877. generator.append(R"~~~(
  878. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  879. @fully_qualified_name@ const& impl() const { return static_cast<@fully_qualified_name@ const&>(@wrapper_base_class@::impl()); }
  880. )~~~");
  881. }
  882. generator.append(R"~~~(
  883. private:
  884. )~~~");
  885. if (interface.wrapper_base_class == "Wrapper") {
  886. generator.append(R"~~~(
  887. NonnullRefPtr<@fully_qualified_name@> m_impl;
  888. )~~~");
  889. }
  890. generator.append(R"~~~(
  891. };
  892. )~~~");
  893. if (should_emit_wrapper_factory(interface)) {
  894. generator.append(R"~~~(
  895. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  896. )~~~");
  897. }
  898. generator.append(R"~~~(
  899. } // namespace Web::Bindings
  900. )~~~");
  901. outln("{}", generator.as_string_view());
  902. }
  903. void generate_implementation(IDL::Interface const& interface)
  904. {
  905. StringBuilder builder;
  906. SourceGenerator generator { builder };
  907. generator.set("name", interface.name);
  908. generator.set("wrapper_class", interface.wrapper_class);
  909. generator.set("wrapper_base_class", interface.wrapper_base_class);
  910. generator.set("prototype_class", interface.prototype_class);
  911. generator.set("fully_qualified_name", interface.fully_qualified_name);
  912. generator.append(R"~~~(
  913. #include <AK/FlyString.h>
  914. #include <LibJS/Runtime/Array.h>
  915. #include <LibJS/Runtime/Error.h>
  916. #include <LibJS/Runtime/FunctionObject.h>
  917. #include <LibJS/Runtime/GlobalObject.h>
  918. #include <LibJS/Runtime/TypedArray.h>
  919. #include <LibJS/Runtime/Value.h>
  920. #include <LibWeb/Bindings/@prototype_class@.h>
  921. #include <LibWeb/Bindings/@wrapper_class@.h>
  922. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  923. #include <LibWeb/Bindings/CommentWrapper.h>
  924. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  925. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  926. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  927. #include <LibWeb/Bindings/DocumentWrapper.h>
  928. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  929. #include <LibWeb/Bindings/EventWrapperFactory.h>
  930. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  931. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  932. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  933. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  934. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  935. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  936. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  937. #include <LibWeb/Bindings/ImageDataWrapper.h>
  938. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  939. #include <LibWeb/Bindings/TextWrapper.h>
  940. #include <LibWeb/Bindings/WindowObject.h>
  941. #include <LibWeb/DOM/Element.h>
  942. #include <LibWeb/DOM/EventListener.h>
  943. #include <LibWeb/HTML/HTMLElement.h>
  944. #include <LibWeb/Origin.h>
  945. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  946. using namespace Web::CSS;
  947. using namespace Web::DOM;
  948. using namespace Web::HTML;
  949. namespace Web::Bindings {
  950. @wrapper_class@* @wrapper_class@::create(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  951. {
  952. return global_object.heap().allocate<@wrapper_class@>(global_object, global_object, impl);
  953. }
  954. )~~~");
  955. if (interface.wrapper_base_class == "Wrapper") {
  956. generator.append(R"~~~(
  957. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  958. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  959. , m_impl(impl)
  960. {
  961. }
  962. )~~~");
  963. } else {
  964. generator.append(R"~~~(
  965. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  966. : @wrapper_base_class@(global_object, impl)
  967. {
  968. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  969. VERIFY(success);
  970. }
  971. )~~~");
  972. }
  973. generator.append(R"~~~(
  974. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  975. {
  976. @wrapper_base_class@::initialize(global_object);
  977. }
  978. @wrapper_class@::~@wrapper_class@()
  979. {
  980. }
  981. )~~~");
  982. if (should_emit_wrapper_factory(interface)) {
  983. generator.append(R"~~~(
  984. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  985. {
  986. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  987. }
  988. )~~~");
  989. }
  990. generator.append(R"~~~(
  991. } // namespace Web::Bindings
  992. )~~~");
  993. outln("{}", generator.as_string_view());
  994. }
  995. static void generate_constructor_header(IDL::Interface const& interface)
  996. {
  997. StringBuilder builder;
  998. SourceGenerator generator { builder };
  999. generator.set("name", interface.name);
  1000. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1001. generator.set("constructor_class", interface.constructor_class);
  1002. generator.set("constructor_class:snakecase", interface.constructor_class.to_snakecase());
  1003. generator.append(R"~~~(
  1004. #pragma once
  1005. #include <LibJS/Runtime/NativeFunction.h>
  1006. namespace Web::Bindings {
  1007. class @constructor_class@ : public JS::NativeFunction {
  1008. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  1009. public:
  1010. explicit @constructor_class@(JS::GlobalObject&);
  1011. virtual void initialize(JS::GlobalObject&) override;
  1012. virtual ~@constructor_class@() override;
  1013. virtual JS::Value call() override;
  1014. virtual JS::Value construct(JS::FunctionObject& new_target) override;
  1015. private:
  1016. virtual bool has_constructor() const override { return true; }
  1017. )~~~");
  1018. for (auto& function : interface.static_functions) {
  1019. auto function_generator = generator.fork();
  1020. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1021. function_generator.append(R"~~~(
  1022. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1023. )~~~");
  1024. }
  1025. generator.append(R"~~~(
  1026. };
  1027. } // namespace Web::Bindings
  1028. )~~~");
  1029. outln("{}", generator.as_string_view());
  1030. }
  1031. void generate_constructor_implementation(IDL::Interface const& interface)
  1032. {
  1033. StringBuilder builder;
  1034. SourceGenerator generator { builder };
  1035. generator.set("name", interface.name);
  1036. generator.set("prototype_class", interface.prototype_class);
  1037. generator.set("wrapper_class", interface.wrapper_class);
  1038. generator.set("constructor_class", interface.constructor_class);
  1039. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1040. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1041. generator.append(R"~~~(
  1042. #include <LibJS/Heap/Heap.h>
  1043. #include <LibJS/Runtime/GlobalObject.h>
  1044. #include <LibWeb/Bindings/@constructor_class@.h>
  1045. #include <LibWeb/Bindings/@prototype_class@.h>
  1046. #include <LibWeb/Bindings/@wrapper_class@.h>
  1047. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1048. #include <LibWeb/Bindings/WindowObject.h>
  1049. #if __has_include(<LibWeb/CSS/@name@.h>)
  1050. # include <LibWeb/CSS/@name@.h>
  1051. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1052. # include <LibWeb/DOM/@name@.h>
  1053. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1054. # include <LibWeb/HTML/@name@.h>
  1055. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1056. # include <LibWeb/UIEvents/@name@.h>
  1057. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1058. # include <LibWeb/HighResolutionTime/@name@.h>
  1059. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1060. # include <LibWeb/NavigationTiming/@name@.h>
  1061. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1062. # include <LibWeb/SVG/@name@.h>
  1063. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1064. # include <LibWeb/XHR/@name@.h>
  1065. #endif
  1066. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1067. using namespace Web::CSS;
  1068. using namespace Web::DOM;
  1069. using namespace Web::HTML;
  1070. namespace Web::Bindings {
  1071. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  1072. : NativeFunction(*global_object.function_prototype())
  1073. {
  1074. }
  1075. @constructor_class@::~@constructor_class@()
  1076. {
  1077. }
  1078. JS::Value @constructor_class@::call()
  1079. {
  1080. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  1081. return {};
  1082. }
  1083. JS::Value @constructor_class@::construct(FunctionObject&)
  1084. {
  1085. )~~~");
  1086. if (interface.constructors.is_empty()) {
  1087. // No constructor
  1088. generator.set("constructor.length", "0");
  1089. generator.append(R"~~~(
  1090. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::NotAConstructor, "@name@");
  1091. return {};
  1092. )~~~");
  1093. } else if (interface.constructors.size() == 1) {
  1094. // Single constructor
  1095. auto& constructor = interface.constructors[0];
  1096. generator.set("constructor.length", String::number(constructor.length()));
  1097. generator.append(R"~~~(
  1098. [[maybe_unused]] auto& vm = this->vm();
  1099. auto& global_object = this->global_object();
  1100. auto& window = static_cast<WindowObject&>(global_object);
  1101. )~~~");
  1102. if (!constructor.parameters.is_empty()) {
  1103. generate_argument_count_check(generator, constructor);
  1104. StringBuilder arguments_builder;
  1105. generate_arguments(generator, constructor.parameters, arguments_builder);
  1106. generator.set(".constructor_arguments", arguments_builder.string_view());
  1107. generator.append(R"~~~(
  1108. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window, @.constructor_arguments@); });
  1109. )~~~");
  1110. } else {
  1111. generator.append(R"~~~(
  1112. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window); });
  1113. )~~~");
  1114. }
  1115. generator.append(R"~~~(
  1116. if (should_return_empty(impl))
  1117. return JS::Value();
  1118. return @wrapper_class@::create(global_object, impl.release_value());
  1119. )~~~");
  1120. } else {
  1121. // Multiple constructor overloads - can't do that yet.
  1122. TODO();
  1123. }
  1124. generator.append(R"~~~(
  1125. }
  1126. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  1127. {
  1128. auto& vm = this->vm();
  1129. auto& window = static_cast<WindowObject&>(global_object);
  1130. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  1131. NativeFunction::initialize(global_object);
  1132. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  1133. define_direct_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  1134. )~~~");
  1135. for (auto& constant : interface.constants) {
  1136. auto constant_generator = generator.fork();
  1137. constant_generator.set("constant.name", constant.name);
  1138. constant_generator.set("constant.value", constant.value);
  1139. constant_generator.append(R"~~~(
  1140. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1141. )~~~");
  1142. }
  1143. // https://heycam.github.io/webidl/#es-operations
  1144. for (auto& function : interface.static_functions) {
  1145. auto function_generator = generator.fork();
  1146. function_generator.set("function.name", function.name);
  1147. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1148. function_generator.set("function.length", String::number(function.length()));
  1149. function_generator.append(R"~~~(
  1150. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1151. )~~~");
  1152. }
  1153. generator.append(R"~~~(
  1154. }
  1155. )~~~");
  1156. // Implementation: Static Functions
  1157. for (auto& function : interface.static_functions) {
  1158. generate_function(generator, function, StaticFunction::Yes, interface.constructor_class, interface.fully_qualified_name);
  1159. }
  1160. generator.append(R"~~~(
  1161. } // namespace Web::Bindings
  1162. )~~~");
  1163. outln("{}", generator.as_string_view());
  1164. }
  1165. static void generate_prototype_header(IDL::Interface const& interface)
  1166. {
  1167. StringBuilder builder;
  1168. SourceGenerator generator { builder };
  1169. generator.set("name", interface.name);
  1170. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1171. generator.set("prototype_class", interface.prototype_class);
  1172. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1173. generator.append(R"~~~(
  1174. #pragma once
  1175. #include <LibJS/Runtime/Object.h>
  1176. namespace Web::Bindings {
  1177. class @prototype_class@ : public JS::Object {
  1178. JS_OBJECT(@prototype_class@, JS::Object);
  1179. public:
  1180. explicit @prototype_class@(JS::GlobalObject&);
  1181. virtual void initialize(JS::GlobalObject&) override;
  1182. virtual ~@prototype_class@() override;
  1183. private:
  1184. )~~~");
  1185. for (auto& function : interface.functions) {
  1186. auto function_generator = generator.fork();
  1187. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1188. function_generator.append(R"~~~(
  1189. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1190. )~~~");
  1191. }
  1192. for (auto& attribute : interface.attributes) {
  1193. auto attribute_generator = generator.fork();
  1194. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1195. attribute_generator.append(R"~~~(
  1196. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_getter);
  1197. )~~~");
  1198. if (!attribute.readonly) {
  1199. attribute_generator.append(R"~~~(
  1200. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_setter);
  1201. )~~~");
  1202. }
  1203. }
  1204. generator.append(R"~~~(
  1205. };
  1206. } // namespace Web::Bindings
  1207. )~~~");
  1208. outln("{}", generator.as_string_view());
  1209. }
  1210. void generate_prototype_implementation(IDL::Interface const& interface)
  1211. {
  1212. StringBuilder builder;
  1213. SourceGenerator generator { builder };
  1214. generator.set("name", interface.name);
  1215. generator.set("parent_name", interface.parent_name);
  1216. generator.set("prototype_class", interface.prototype_class);
  1217. generator.set("prototype_base_class", interface.prototype_base_class);
  1218. generator.set("wrapper_class", interface.wrapper_class);
  1219. generator.set("constructor_class", interface.constructor_class);
  1220. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1221. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1222. generator.append(R"~~~(
  1223. #include <AK/Function.h>
  1224. #include <LibJS/Runtime/Array.h>
  1225. #include <LibJS/Runtime/Error.h>
  1226. #include <LibJS/Runtime/FunctionObject.h>
  1227. #include <LibJS/Runtime/GlobalObject.h>
  1228. #include <LibJS/Runtime/TypedArray.h>
  1229. #include <LibWeb/Bindings/@prototype_class@.h>
  1230. #include <LibWeb/Bindings/@wrapper_class@.h>
  1231. #include <LibWeb/Bindings/AbortSignalWrapper.h>
  1232. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  1233. #include <LibWeb/Bindings/CSSStyleSheetWrapper.h>
  1234. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  1235. #include <LibWeb/Bindings/CommentWrapper.h>
  1236. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  1237. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  1238. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  1239. #include <LibWeb/Bindings/DocumentWrapper.h>
  1240. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  1241. #include <LibWeb/Bindings/EventWrapper.h>
  1242. #include <LibWeb/Bindings/EventWrapperFactory.h>
  1243. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1244. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  1245. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  1246. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  1247. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  1248. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  1249. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  1250. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  1251. #include <LibWeb/Bindings/ImageDataWrapper.h>
  1252. #include <LibWeb/Bindings/LocationObject.h>
  1253. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  1254. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  1255. #include <LibWeb/Bindings/RangeWrapper.h>
  1256. #include <LibWeb/Bindings/StyleSheetListWrapper.h>
  1257. #include <LibWeb/Bindings/TextWrapper.h>
  1258. #include <LibWeb/Bindings/WindowObject.h>
  1259. #include <LibWeb/DOM/Element.h>
  1260. #include <LibWeb/DOM/EventListener.h>
  1261. #include <LibWeb/DOM/Range.h>
  1262. #include <LibWeb/DOM/Window.h>
  1263. #include <LibWeb/HTML/EventHandler.h>
  1264. #include <LibWeb/HTML/HTMLElement.h>
  1265. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  1266. #include <LibWeb/Origin.h>
  1267. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  1268. # include <LibWeb/Bindings/@prototype_base_class@.h>
  1269. #endif
  1270. #if __has_include(<LibWeb/CSS/@name@.h>)
  1271. # include <LibWeb/CSS/@name@.h>
  1272. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1273. # include <LibWeb/DOM/@name@.h>
  1274. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1275. # include <LibWeb/HTML/@name@.h>
  1276. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1277. # include <LibWeb/UIEvents/@name@.h>
  1278. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1279. # include <LibWeb/HighResolutionTime/@name@.h>
  1280. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1281. # include <LibWeb/NavigationTiming/@name@.h>
  1282. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1283. # include <LibWeb/SVG/@name@.h>
  1284. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1285. # include <LibWeb/XHR/@name@.h>
  1286. #endif
  1287. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1288. using namespace Web::CSS;
  1289. using namespace Web::DOM;
  1290. using namespace Web::HTML;
  1291. using namespace Web::NavigationTiming;
  1292. using namespace Web::XHR;
  1293. namespace Web::Bindings {
  1294. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  1295. : Object(*global_object.object_prototype())
  1296. {
  1297. )~~~");
  1298. if (interface.name == "DOMException") {
  1299. // https://heycam.github.io/webidl/#es-DOMException-specialness
  1300. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  1301. generator.append(R"~~~(
  1302. auto success = internal_set_prototype_of(global_object.error_prototype());
  1303. VERIFY(success);
  1304. )~~~");
  1305. } else if (!interface.parent_name.is_empty()) {
  1306. generator.append(R"~~~(
  1307. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  1308. VERIFY(success);
  1309. )~~~");
  1310. }
  1311. // FIXME: Currently almost everything gets default_attributes but it should be configurable per attribute.
  1312. // See the spec links for details
  1313. generator.append(R"~~~(
  1314. }
  1315. @prototype_class@::~@prototype_class@()
  1316. {
  1317. }
  1318. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  1319. {
  1320. [[maybe_unused]] auto& vm = this->vm();
  1321. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;
  1322. )~~~");
  1323. // https://heycam.github.io/webidl/#es-attributes
  1324. for (auto& attribute : interface.attributes) {
  1325. auto attribute_generator = generator.fork();
  1326. attribute_generator.set("attribute.name", attribute.name);
  1327. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1328. if (attribute.readonly)
  1329. attribute_generator.set("attribute.setter_callback", "nullptr");
  1330. else
  1331. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1332. attribute_generator.append(R"~~~(
  1333. define_native_accessor("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  1334. )~~~");
  1335. }
  1336. // https://heycam.github.io/webidl/#es-constants
  1337. for (auto& constant : interface.constants) {
  1338. auto constant_generator = generator.fork();
  1339. constant_generator.set("constant.name", constant.name);
  1340. constant_generator.set("constant.value", constant.value);
  1341. constant_generator.append(R"~~~(
  1342. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1343. )~~~");
  1344. }
  1345. // https://heycam.github.io/webidl/#es-operations
  1346. for (auto& function : interface.functions) {
  1347. auto function_generator = generator.fork();
  1348. function_generator.set("function.name", function.name);
  1349. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1350. function_generator.set("function.length", String::number(function.length()));
  1351. function_generator.append(R"~~~(
  1352. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1353. )~~~");
  1354. }
  1355. generator.append(R"~~~(
  1356. Object::initialize(global_object);
  1357. }
  1358. )~~~");
  1359. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  1360. generator.append(R"~~~(
  1361. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  1362. {
  1363. auto* this_object = vm.this_value(global_object).to_object(global_object);
  1364. if (!this_object)
  1365. return {};
  1366. )~~~");
  1367. if (interface.name == "EventTarget") {
  1368. generator.append(R"~~~(
  1369. if (is<WindowObject>(this_object)) {
  1370. return &static_cast<WindowObject*>(this_object)->impl();
  1371. }
  1372. )~~~");
  1373. }
  1374. generator.append(R"~~~(
  1375. if (!is<@wrapper_class@>(this_object)) {
  1376. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@fully_qualified_name@");
  1377. return nullptr;
  1378. }
  1379. return &static_cast<@wrapper_class@*>(this_object)->impl();
  1380. }
  1381. )~~~");
  1382. }
  1383. for (auto& attribute : interface.attributes) {
  1384. auto attribute_generator = generator.fork();
  1385. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1386. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1387. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1388. if (attribute.extended_attributes.contains("ImplementedAs")) {
  1389. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  1390. attribute_generator.set("attribute.cpp_getter_name", implemented_as);
  1391. } else {
  1392. attribute_generator.set("attribute.cpp_getter_name", attribute.name.to_snakecase());
  1393. }
  1394. if (attribute.extended_attributes.contains("Reflect")) {
  1395. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1396. if (attribute_name.is_null())
  1397. attribute_name = attribute.name;
  1398. attribute_name = make_input_acceptable_cpp(attribute_name);
  1399. attribute_generator.set("attribute.reflect_name", attribute_name);
  1400. } else {
  1401. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  1402. }
  1403. attribute_generator.append(R"~~~(
  1404. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.getter_callback@)
  1405. {
  1406. auto* impl = impl_from(vm, global_object);
  1407. if (!impl)
  1408. return {};
  1409. )~~~");
  1410. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1411. attribute_generator.append(R"~~~(
  1412. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1413. return JS::js_null();
  1414. )~~~");
  1415. }
  1416. if (attribute.extended_attributes.contains("Reflect")) {
  1417. if (attribute.type.name != "boolean") {
  1418. attribute_generator.append(R"~~~(
  1419. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1420. )~~~");
  1421. } else {
  1422. attribute_generator.append(R"~~~(
  1423. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1424. )~~~");
  1425. }
  1426. } else {
  1427. attribute_generator.append(R"~~~(
  1428. auto retval = impl->@attribute.cpp_getter_name@();
  1429. )~~~");
  1430. }
  1431. generate_return_statement(generator, attribute.type);
  1432. attribute_generator.append(R"~~~(
  1433. }
  1434. )~~~");
  1435. if (!attribute.readonly) {
  1436. attribute_generator.append(R"~~~(
  1437. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.setter_callback@)
  1438. {
  1439. auto* impl = impl_from(vm, global_object);
  1440. if (!impl)
  1441. return {};
  1442. auto value = vm.argument(0);
  1443. )~~~");
  1444. generate_to_cpp(generator, attribute, "value", "", "cpp_value", false, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1445. if (attribute.extended_attributes.contains("Reflect")) {
  1446. if (attribute.type.name != "boolean") {
  1447. attribute_generator.append(R"~~~(
  1448. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1449. )~~~");
  1450. } else {
  1451. attribute_generator.append(R"~~~(
  1452. if (!cpp_value)
  1453. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1454. else
  1455. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1456. )~~~");
  1457. }
  1458. } else {
  1459. attribute_generator.append(R"~~~(
  1460. impl->set_@attribute.name:snakecase@(cpp_value);
  1461. )~~~");
  1462. }
  1463. attribute_generator.append(R"~~~(
  1464. return {};
  1465. }
  1466. )~~~");
  1467. }
  1468. }
  1469. // Implementation: Functions
  1470. for (auto& function : interface.functions) {
  1471. generate_function(generator, function, StaticFunction::No, interface.prototype_class, interface.fully_qualified_name);
  1472. }
  1473. generator.append(R"~~~(
  1474. } // namespace Web::Bindings
  1475. )~~~");
  1476. outln("{}", generator.as_string_view());
  1477. }