WrapperGenerator.cpp 57 KB

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