WrapperGenerator.cpp 53 KB

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