WrapperGenerator.cpp 61 KB

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