WrapperGenerator.cpp 53 KB

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