WrapperGenerator.cpp 57 KB

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