WrapperGenerator.cpp 61 KB

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