WrapperGenerator.cpp 52 KB

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