WrapperGenerator.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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", "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_statement@
  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/SVG/@name@.h>)
  853. # include <LibWeb/SVG/@name@.h>
  854. #elif __has_include(<LibWeb/XHR/@name@.h>)
  855. # include <LibWeb/XHR/@name@.h>
  856. #elif __has_include(<LibWeb/URL/@name@.h>)
  857. # include <LibWeb/URL/@name@.h>
  858. #endif
  859. )~~~");
  860. if (interface.wrapper_base_class != "Wrapper") {
  861. generator.append(R"~~~(
  862. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  863. )~~~");
  864. }
  865. generator.append(R"~~~(
  866. namespace Web::Bindings {
  867. class @wrapper_class@ : public @wrapper_base_class@ {
  868. JS_OBJECT(@name@, @wrapper_base_class@);
  869. public:
  870. static @wrapper_class@* create(JS::GlobalObject&, @fully_qualified_name@&);
  871. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  872. virtual void initialize(JS::GlobalObject&) override;
  873. virtual ~@wrapper_class@() override;
  874. )~~~");
  875. if (interface.extended_attributes.contains("CustomGet")) {
  876. generator.append(R"~~~(
  877. virtual JS::Value internal_get(JS::PropertyName const&, JS::Value receiver) const override;
  878. )~~~");
  879. }
  880. if (interface.extended_attributes.contains("CustomSet")) {
  881. generator.append(R"~~~(
  882. virtual bool internal_set(JS::PropertyName const&, JS::Value, JS::Value receiver) override;
  883. )~~~");
  884. }
  885. if (interface.extended_attributes.contains("CustomHasProperty")) {
  886. generator.append(R"~~~(
  887. virtual bool internal_has_property(JS::PropertyName const&) const override;
  888. )~~~");
  889. }
  890. if (interface.wrapper_base_class == "Wrapper") {
  891. generator.append(R"~~~(
  892. @fully_qualified_name@& impl() { return *m_impl; }
  893. @fully_qualified_name@ const& impl() const { return *m_impl; }
  894. )~~~");
  895. } else {
  896. generator.append(R"~~~(
  897. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  898. @fully_qualified_name@ const& impl() const { return static_cast<@fully_qualified_name@ const&>(@wrapper_base_class@::impl()); }
  899. )~~~");
  900. }
  901. generator.append(R"~~~(
  902. private:
  903. )~~~");
  904. if (interface.wrapper_base_class == "Wrapper") {
  905. generator.append(R"~~~(
  906. NonnullRefPtr<@fully_qualified_name@> m_impl;
  907. )~~~");
  908. }
  909. generator.append(R"~~~(
  910. };
  911. )~~~");
  912. if (should_emit_wrapper_factory(interface)) {
  913. generator.append(R"~~~(
  914. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  915. )~~~");
  916. }
  917. generator.append(R"~~~(
  918. } // namespace Web::Bindings
  919. )~~~");
  920. outln("{}", generator.as_string_view());
  921. }
  922. void generate_implementation(IDL::Interface const& interface)
  923. {
  924. StringBuilder builder;
  925. SourceGenerator generator { builder };
  926. generator.set("name", interface.name);
  927. generator.set("wrapper_class", interface.wrapper_class);
  928. generator.set("wrapper_base_class", interface.wrapper_base_class);
  929. generator.set("prototype_class", interface.prototype_class);
  930. generator.set("fully_qualified_name", interface.fully_qualified_name);
  931. generator.append(R"~~~(
  932. #include <AK/FlyString.h>
  933. #include <LibJS/Runtime/Array.h>
  934. #include <LibJS/Runtime/Error.h>
  935. #include <LibJS/Runtime/FunctionObject.h>
  936. #include <LibJS/Runtime/GlobalObject.h>
  937. #include <LibJS/Runtime/TypedArray.h>
  938. #include <LibJS/Runtime/Value.h>
  939. #include <LibWeb/Bindings/@prototype_class@.h>
  940. #include <LibWeb/Bindings/@wrapper_class@.h>
  941. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  942. #include <LibWeb/Bindings/CommentWrapper.h>
  943. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  944. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  945. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  946. #include <LibWeb/Bindings/DocumentWrapper.h>
  947. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  948. #include <LibWeb/Bindings/EventWrapperFactory.h>
  949. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  950. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  951. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  952. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  953. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  954. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  955. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  956. #include <LibWeb/Bindings/ImageDataWrapper.h>
  957. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  958. #include <LibWeb/Bindings/TextWrapper.h>
  959. #include <LibWeb/Bindings/WindowObject.h>
  960. #include <LibWeb/DOM/Element.h>
  961. #include <LibWeb/DOM/EventListener.h>
  962. #include <LibWeb/HTML/HTMLElement.h>
  963. #include <LibWeb/Origin.h>
  964. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  965. using namespace Web::CSS;
  966. using namespace Web::DOM;
  967. using namespace Web::HTML;
  968. namespace Web::Bindings {
  969. @wrapper_class@* @wrapper_class@::create(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  970. {
  971. return global_object.heap().allocate<@wrapper_class@>(global_object, global_object, impl);
  972. }
  973. )~~~");
  974. if (interface.wrapper_base_class == "Wrapper") {
  975. generator.append(R"~~~(
  976. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  977. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  978. , m_impl(impl)
  979. {
  980. }
  981. )~~~");
  982. } else {
  983. generator.append(R"~~~(
  984. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  985. : @wrapper_base_class@(global_object, impl)
  986. {
  987. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  988. VERIFY(success);
  989. }
  990. )~~~");
  991. }
  992. generator.append(R"~~~(
  993. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  994. {
  995. @wrapper_base_class@::initialize(global_object);
  996. }
  997. @wrapper_class@::~@wrapper_class@()
  998. {
  999. }
  1000. )~~~");
  1001. if (should_emit_wrapper_factory(interface)) {
  1002. generator.append(R"~~~(
  1003. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  1004. {
  1005. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  1006. }
  1007. )~~~");
  1008. }
  1009. generator.append(R"~~~(
  1010. } // namespace Web::Bindings
  1011. )~~~");
  1012. outln("{}", generator.as_string_view());
  1013. }
  1014. static void generate_constructor_header(IDL::Interface const& interface)
  1015. {
  1016. StringBuilder builder;
  1017. SourceGenerator generator { builder };
  1018. generator.set("name", interface.name);
  1019. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1020. generator.set("constructor_class", interface.constructor_class);
  1021. generator.set("constructor_class:snakecase", interface.constructor_class.to_snakecase());
  1022. generator.append(R"~~~(
  1023. #pragma once
  1024. #include <LibJS/Runtime/NativeFunction.h>
  1025. namespace Web::Bindings {
  1026. class @constructor_class@ : public JS::NativeFunction {
  1027. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  1028. public:
  1029. explicit @constructor_class@(JS::GlobalObject&);
  1030. virtual void initialize(JS::GlobalObject&) override;
  1031. virtual ~@constructor_class@() override;
  1032. virtual JS::Value call() override;
  1033. virtual JS::Value construct(JS::FunctionObject& new_target) override;
  1034. private:
  1035. virtual bool has_constructor() const override { return true; }
  1036. )~~~");
  1037. for (auto& function : interface.static_functions) {
  1038. auto function_generator = generator.fork();
  1039. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1040. function_generator.append(R"~~~(
  1041. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1042. )~~~");
  1043. }
  1044. generator.append(R"~~~(
  1045. };
  1046. } // namespace Web::Bindings
  1047. )~~~");
  1048. outln("{}", generator.as_string_view());
  1049. }
  1050. void generate_constructor_implementation(IDL::Interface const& interface)
  1051. {
  1052. StringBuilder builder;
  1053. SourceGenerator generator { builder };
  1054. generator.set("name", interface.name);
  1055. generator.set("prototype_class", interface.prototype_class);
  1056. generator.set("wrapper_class", interface.wrapper_class);
  1057. generator.set("constructor_class", interface.constructor_class);
  1058. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1059. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1060. generator.append(R"~~~(
  1061. #include <LibJS/Heap/Heap.h>
  1062. #include <LibJS/Runtime/GlobalObject.h>
  1063. #include <LibWeb/Bindings/@constructor_class@.h>
  1064. #include <LibWeb/Bindings/@prototype_class@.h>
  1065. #include <LibWeb/Bindings/@wrapper_class@.h>
  1066. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1067. #include <LibWeb/Bindings/WindowObject.h>
  1068. #if __has_include(<LibWeb/CSS/@name@.h>)
  1069. # include <LibWeb/CSS/@name@.h>
  1070. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1071. # include <LibWeb/DOM/@name@.h>
  1072. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1073. # include <LibWeb/HTML/@name@.h>
  1074. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1075. # include <LibWeb/UIEvents/@name@.h>
  1076. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1077. # include <LibWeb/HighResolutionTime/@name@.h>
  1078. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1079. # include <LibWeb/NavigationTiming/@name@.h>
  1080. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1081. # include <LibWeb/SVG/@name@.h>
  1082. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1083. # include <LibWeb/XHR/@name@.h>
  1084. #elif __has_include(<LibWeb/URL/@name@.h>)
  1085. # include <LibWeb/URL/@name@.h>
  1086. #endif
  1087. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1088. using namespace Web::CSS;
  1089. using namespace Web::DOM;
  1090. using namespace Web::HTML;
  1091. namespace Web::Bindings {
  1092. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  1093. : NativeFunction(*global_object.function_prototype())
  1094. {
  1095. }
  1096. @constructor_class@::~@constructor_class@()
  1097. {
  1098. }
  1099. JS::Value @constructor_class@::call()
  1100. {
  1101. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  1102. return {};
  1103. }
  1104. JS::Value @constructor_class@::construct(FunctionObject&)
  1105. {
  1106. )~~~");
  1107. if (interface.constructors.is_empty()) {
  1108. // No constructor
  1109. generator.set("constructor.length", "0");
  1110. generator.append(R"~~~(
  1111. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::NotAConstructor, "@name@");
  1112. return {};
  1113. )~~~");
  1114. } else if (interface.constructors.size() == 1) {
  1115. // Single constructor
  1116. auto& constructor = interface.constructors[0];
  1117. generator.set("constructor.length", String::number(constructor.length()));
  1118. generator.append(R"~~~(
  1119. [[maybe_unused]] auto& vm = this->vm();
  1120. auto& global_object = this->global_object();
  1121. auto& window = static_cast<WindowObject&>(global_object);
  1122. )~~~");
  1123. if (!constructor.parameters.is_empty()) {
  1124. generate_argument_count_check(generator, constructor);
  1125. StringBuilder arguments_builder;
  1126. generate_arguments(generator, constructor.parameters, arguments_builder);
  1127. generator.set(".constructor_arguments", arguments_builder.string_view());
  1128. generator.append(R"~~~(
  1129. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window, @.constructor_arguments@); });
  1130. )~~~");
  1131. } else {
  1132. generator.append(R"~~~(
  1133. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window); });
  1134. )~~~");
  1135. }
  1136. generator.append(R"~~~(
  1137. if (should_return_empty(impl))
  1138. return JS::Value();
  1139. return @wrapper_class@::create(global_object, impl.release_value());
  1140. )~~~");
  1141. } else {
  1142. // Multiple constructor overloads - can't do that yet.
  1143. TODO();
  1144. }
  1145. generator.append(R"~~~(
  1146. }
  1147. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  1148. {
  1149. auto& vm = this->vm();
  1150. auto& window = static_cast<WindowObject&>(global_object);
  1151. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  1152. NativeFunction::initialize(global_object);
  1153. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  1154. define_direct_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  1155. )~~~");
  1156. for (auto& constant : interface.constants) {
  1157. auto constant_generator = generator.fork();
  1158. constant_generator.set("constant.name", constant.name);
  1159. constant_generator.set("constant.value", constant.value);
  1160. constant_generator.append(R"~~~(
  1161. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1162. )~~~");
  1163. }
  1164. // https://heycam.github.io/webidl/#es-operations
  1165. for (auto& function : interface.static_functions) {
  1166. auto function_generator = generator.fork();
  1167. function_generator.set("function.name", function.name);
  1168. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1169. function_generator.set("function.length", String::number(function.length()));
  1170. function_generator.append(R"~~~(
  1171. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1172. )~~~");
  1173. }
  1174. generator.append(R"~~~(
  1175. }
  1176. )~~~");
  1177. // Implementation: Static Functions
  1178. for (auto& function : interface.static_functions) {
  1179. generate_function(generator, function, StaticFunction::Yes, interface.constructor_class, interface.fully_qualified_name);
  1180. }
  1181. generator.append(R"~~~(
  1182. } // namespace Web::Bindings
  1183. )~~~");
  1184. outln("{}", generator.as_string_view());
  1185. }
  1186. static void generate_prototype_header(IDL::Interface const& interface)
  1187. {
  1188. StringBuilder builder;
  1189. SourceGenerator generator { builder };
  1190. generator.set("name", interface.name);
  1191. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1192. generator.set("prototype_class", interface.prototype_class);
  1193. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1194. generator.append(R"~~~(
  1195. #pragma once
  1196. #include <LibJS/Runtime/Object.h>
  1197. namespace Web::Bindings {
  1198. class @prototype_class@ : public JS::Object {
  1199. JS_OBJECT(@prototype_class@, JS::Object);
  1200. public:
  1201. explicit @prototype_class@(JS::GlobalObject&);
  1202. virtual void initialize(JS::GlobalObject&) override;
  1203. virtual ~@prototype_class@() override;
  1204. private:
  1205. )~~~");
  1206. for (auto& function : interface.functions) {
  1207. auto function_generator = generator.fork();
  1208. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1209. function_generator.append(R"~~~(
  1210. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1211. )~~~");
  1212. }
  1213. if (interface.has_stringifier) {
  1214. auto stringifier_generator = generator.fork();
  1215. stringifier_generator.append(R"~~~(
  1216. JS_DECLARE_NATIVE_FUNCTION(to_string);
  1217. )~~~");
  1218. }
  1219. for (auto& attribute : interface.attributes) {
  1220. auto attribute_generator = generator.fork();
  1221. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1222. attribute_generator.append(R"~~~(
  1223. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_getter);
  1224. )~~~");
  1225. if (!attribute.readonly) {
  1226. attribute_generator.append(R"~~~(
  1227. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_setter);
  1228. )~~~");
  1229. }
  1230. }
  1231. generator.append(R"~~~(
  1232. };
  1233. } // namespace Web::Bindings
  1234. )~~~");
  1235. outln("{}", generator.as_string_view());
  1236. }
  1237. void generate_prototype_implementation(IDL::Interface const& interface)
  1238. {
  1239. StringBuilder builder;
  1240. SourceGenerator generator { builder };
  1241. generator.set("name", interface.name);
  1242. generator.set("parent_name", interface.parent_name);
  1243. generator.set("prototype_class", interface.prototype_class);
  1244. generator.set("prototype_base_class", interface.prototype_base_class);
  1245. generator.set("wrapper_class", interface.wrapper_class);
  1246. generator.set("constructor_class", interface.constructor_class);
  1247. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1248. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1249. generator.append(R"~~~(
  1250. #include <AK/Function.h>
  1251. #include <LibJS/Runtime/Array.h>
  1252. #include <LibJS/Runtime/Error.h>
  1253. #include <LibJS/Runtime/FunctionObject.h>
  1254. #include <LibJS/Runtime/GlobalObject.h>
  1255. #include <LibJS/Runtime/TypedArray.h>
  1256. #include <LibWeb/Bindings/@prototype_class@.h>
  1257. #include <LibWeb/Bindings/@wrapper_class@.h>
  1258. #include <LibWeb/Bindings/AbortSignalWrapper.h>
  1259. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  1260. #include <LibWeb/Bindings/CSSStyleSheetWrapper.h>
  1261. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  1262. #include <LibWeb/Bindings/CommentWrapper.h>
  1263. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  1264. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  1265. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  1266. #include <LibWeb/Bindings/DocumentWrapper.h>
  1267. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  1268. #include <LibWeb/Bindings/EventWrapper.h>
  1269. #include <LibWeb/Bindings/EventWrapperFactory.h>
  1270. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1271. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  1272. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  1273. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  1274. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  1275. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  1276. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  1277. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  1278. #include <LibWeb/Bindings/ImageDataWrapper.h>
  1279. #include <LibWeb/Bindings/LocationObject.h>
  1280. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  1281. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  1282. #include <LibWeb/Bindings/RangeWrapper.h>
  1283. #include <LibWeb/Bindings/StyleSheetListWrapper.h>
  1284. #include <LibWeb/Bindings/TextWrapper.h>
  1285. #include <LibWeb/Bindings/URLSearchParamsWrapper.h>
  1286. #include <LibWeb/Bindings/WindowObject.h>
  1287. #include <LibWeb/DOM/Element.h>
  1288. #include <LibWeb/DOM/EventListener.h>
  1289. #include <LibWeb/DOM/Range.h>
  1290. #include <LibWeb/DOM/Window.h>
  1291. #include <LibWeb/HTML/EventHandler.h>
  1292. #include <LibWeb/HTML/HTMLElement.h>
  1293. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  1294. #include <LibWeb/Origin.h>
  1295. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  1296. # include <LibWeb/Bindings/@prototype_base_class@.h>
  1297. #endif
  1298. #if __has_include(<LibWeb/CSS/@name@.h>)
  1299. # include <LibWeb/CSS/@name@.h>
  1300. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1301. # include <LibWeb/DOM/@name@.h>
  1302. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1303. # include <LibWeb/HTML/@name@.h>
  1304. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1305. # include <LibWeb/UIEvents/@name@.h>
  1306. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1307. # include <LibWeb/HighResolutionTime/@name@.h>
  1308. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1309. # include <LibWeb/NavigationTiming/@name@.h>
  1310. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1311. # include <LibWeb/SVG/@name@.h>
  1312. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1313. # include <LibWeb/XHR/@name@.h>
  1314. #elif __has_include(<LibWeb/URL/@name@.h>)
  1315. # include <LibWeb/URL/@name@.h>
  1316. #endif
  1317. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1318. using namespace Web::CSS;
  1319. using namespace Web::DOM;
  1320. using namespace Web::HTML;
  1321. using namespace Web::NavigationTiming;
  1322. using namespace Web::XHR;
  1323. using namespace Web::URL;
  1324. namespace Web::Bindings {
  1325. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  1326. : Object(*global_object.object_prototype())
  1327. {
  1328. )~~~");
  1329. if (interface.name == "DOMException") {
  1330. // https://heycam.github.io/webidl/#es-DOMException-specialness
  1331. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  1332. generator.append(R"~~~(
  1333. auto success = internal_set_prototype_of(global_object.error_prototype());
  1334. VERIFY(success);
  1335. )~~~");
  1336. } else if (!interface.parent_name.is_empty()) {
  1337. generator.append(R"~~~(
  1338. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  1339. VERIFY(success);
  1340. )~~~");
  1341. }
  1342. // FIXME: Currently almost everything gets default_attributes but it should be configurable per attribute.
  1343. // See the spec links for details
  1344. generator.append(R"~~~(
  1345. }
  1346. @prototype_class@::~@prototype_class@()
  1347. {
  1348. }
  1349. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  1350. {
  1351. [[maybe_unused]] auto& vm = this->vm();
  1352. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;
  1353. )~~~");
  1354. // https://heycam.github.io/webidl/#es-attributes
  1355. for (auto& attribute : interface.attributes) {
  1356. auto attribute_generator = generator.fork();
  1357. attribute_generator.set("attribute.name", attribute.name);
  1358. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1359. if (attribute.readonly)
  1360. attribute_generator.set("attribute.setter_callback", "nullptr");
  1361. else
  1362. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1363. attribute_generator.append(R"~~~(
  1364. define_native_accessor("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  1365. )~~~");
  1366. }
  1367. // https://heycam.github.io/webidl/#es-constants
  1368. for (auto& constant : interface.constants) {
  1369. auto constant_generator = generator.fork();
  1370. constant_generator.set("constant.name", constant.name);
  1371. constant_generator.set("constant.value", constant.value);
  1372. constant_generator.append(R"~~~(
  1373. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1374. )~~~");
  1375. }
  1376. // https://heycam.github.io/webidl/#es-operations
  1377. for (auto& function : interface.functions) {
  1378. auto function_generator = generator.fork();
  1379. function_generator.set("function.name", function.name);
  1380. function_generator.set("function.name:snakecase", make_input_acceptable_cpp(function.name.to_snakecase()));
  1381. function_generator.set("function.length", String::number(function.length()));
  1382. function_generator.append(R"~~~(
  1383. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1384. )~~~");
  1385. }
  1386. if (interface.has_stringifier) {
  1387. auto stringifier_generator = generator.fork();
  1388. stringifier_generator.append(R"~~~(
  1389. define_native_function("toString", to_string, 0, default_attributes);
  1390. )~~~");
  1391. }
  1392. generator.append(R"~~~(
  1393. Object::initialize(global_object);
  1394. }
  1395. )~~~");
  1396. if (!interface.attributes.is_empty() || !interface.functions.is_empty() || interface.has_stringifier) {
  1397. generator.append(R"~~~(
  1398. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  1399. {
  1400. auto* this_object = vm.this_value(global_object).to_object(global_object);
  1401. if (!this_object)
  1402. return {};
  1403. )~~~");
  1404. if (interface.name == "EventTarget") {
  1405. generator.append(R"~~~(
  1406. if (is<WindowObject>(this_object)) {
  1407. return &static_cast<WindowObject*>(this_object)->impl();
  1408. }
  1409. )~~~");
  1410. }
  1411. generator.append(R"~~~(
  1412. if (!is<@wrapper_class@>(this_object)) {
  1413. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "@fully_qualified_name@");
  1414. return nullptr;
  1415. }
  1416. return &static_cast<@wrapper_class@*>(this_object)->impl();
  1417. }
  1418. )~~~");
  1419. }
  1420. for (auto& attribute : interface.attributes) {
  1421. auto attribute_generator = generator.fork();
  1422. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1423. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1424. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1425. if (attribute.extended_attributes.contains("ImplementedAs")) {
  1426. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  1427. attribute_generator.set("attribute.cpp_getter_name", implemented_as);
  1428. } else {
  1429. attribute_generator.set("attribute.cpp_getter_name", attribute.name.to_snakecase());
  1430. }
  1431. if (attribute.extended_attributes.contains("Reflect")) {
  1432. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1433. if (attribute_name.is_null())
  1434. attribute_name = attribute.name;
  1435. attribute_name = make_input_acceptable_cpp(attribute_name);
  1436. attribute_generator.set("attribute.reflect_name", attribute_name);
  1437. } else {
  1438. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  1439. }
  1440. attribute_generator.append(R"~~~(
  1441. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.getter_callback@)
  1442. {
  1443. auto* impl = impl_from(vm, global_object);
  1444. if (!impl)
  1445. return {};
  1446. )~~~");
  1447. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1448. attribute_generator.append(R"~~~(
  1449. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1450. return JS::js_null();
  1451. )~~~");
  1452. }
  1453. if (attribute.extended_attributes.contains("Reflect")) {
  1454. if (attribute.type.name != "boolean") {
  1455. attribute_generator.append(R"~~~(
  1456. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1457. )~~~");
  1458. } else {
  1459. attribute_generator.append(R"~~~(
  1460. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1461. )~~~");
  1462. }
  1463. } else {
  1464. attribute_generator.append(R"~~~(
  1465. auto retval = impl->@attribute.cpp_getter_name@();
  1466. )~~~");
  1467. }
  1468. generate_return_statement(generator, attribute.type);
  1469. attribute_generator.append(R"~~~(
  1470. }
  1471. )~~~");
  1472. if (!attribute.readonly) {
  1473. attribute_generator.append(R"~~~(
  1474. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.setter_callback@)
  1475. {
  1476. auto* impl = impl_from(vm, global_object);
  1477. if (!impl)
  1478. return {};
  1479. auto value = vm.argument(0);
  1480. )~~~");
  1481. generate_to_cpp(generator, attribute, "value", "", "cpp_value", false, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1482. if (attribute.extended_attributes.contains("Reflect")) {
  1483. if (attribute.type.name != "boolean") {
  1484. attribute_generator.append(R"~~~(
  1485. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1486. )~~~");
  1487. } else {
  1488. attribute_generator.append(R"~~~(
  1489. if (!cpp_value)
  1490. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1491. else
  1492. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1493. )~~~");
  1494. }
  1495. } else {
  1496. attribute_generator.append(R"~~~(
  1497. [[maybe_unused]] auto retval = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->set_@attribute.name:snakecase@(cpp_value); });
  1498. )~~~");
  1499. }
  1500. attribute_generator.append(R"~~~(
  1501. return {};
  1502. }
  1503. )~~~");
  1504. }
  1505. }
  1506. // Implementation: Functions
  1507. for (auto& function : interface.functions) {
  1508. generate_function(generator, function, StaticFunction::No, interface.prototype_class, interface.fully_qualified_name);
  1509. }
  1510. if (interface.has_stringifier) {
  1511. auto stringifier_generator = generator.fork();
  1512. stringifier_generator.set("class_name", interface.prototype_class);
  1513. if (interface.stringifier_attribute.has_value())
  1514. stringifier_generator.set("attribute.cpp_getter_name", interface.stringifier_attribute->to_snakecase());
  1515. stringifier_generator.append(R"~~~(
  1516. JS_DEFINE_NATIVE_FUNCTION(@class_name@::to_string)
  1517. {
  1518. auto* impl = impl_from(vm, global_object);
  1519. if (!impl)
  1520. return {};
  1521. )~~~");
  1522. if (interface.stringifier_attribute.has_value()) {
  1523. stringifier_generator.append(R"~~~(
  1524. auto retval = impl->@attribute.cpp_getter_name@();
  1525. )~~~");
  1526. } else {
  1527. stringifier_generator.append(R"~~~(
  1528. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->to_string(); });
  1529. if (should_return_empty(result))
  1530. return JS::Value();
  1531. auto retval = result.release_value();
  1532. )~~~");
  1533. }
  1534. stringifier_generator.append(R"~~~(
  1535. return JS::js_string(vm, move(retval));
  1536. }
  1537. )~~~");
  1538. }
  1539. generator.append(R"~~~(
  1540. } // namespace Web::Bindings
  1541. )~~~");
  1542. outln("{}", generator.as_string_view());
  1543. }