WrapperGenerator.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  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(String const& 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, 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. 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(IDL::Interface const&);
  314. static void generate_constructor_implementation(IDL::Interface const&);
  315. static void generate_prototype_header(IDL::Interface const&);
  316. static void generate_prototype_implementation(IDL::Interface const&);
  317. static void generate_header(IDL::Interface const&);
  318. static void generate_implementation(IDL::Interface const&);
  319. int main(int argc, char** argv)
  320. {
  321. Core::ArgsParser args_parser;
  322. char const* 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_view().at(lexical_path.parts_view().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(IDL::Interface const& 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(IDL::Type const& 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, 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 = {})
  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_nullish()) {
  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. if (!parameter.type.nullable) {
  497. scoped_generator.append(R"~~~(
  498. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  499. if (vm.exception())
  500. @return_statement@
  501. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  502. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  503. @return_statement@
  504. }
  505. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  506. )~~~");
  507. } else {
  508. scoped_generator.append(R"~~~(
  509. @parameter.type.name@* @cpp_name@ = nullptr;
  510. if (!@js_name@@js_suffix@.is_nullish()) {
  511. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  512. if (vm.exception())
  513. @return_statement@
  514. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  515. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  516. @return_statement@
  517. }
  518. @cpp_name@ = &static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  519. }
  520. )~~~");
  521. }
  522. } else if (parameter.type.name == "double") {
  523. if (!optional) {
  524. scoped_generator.append(R"~~~(
  525. double @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  526. if (vm.exception())
  527. @return_statement@
  528. )~~~");
  529. } else {
  530. if (optional_default_value.has_value()) {
  531. scoped_generator.append(R"~~~(
  532. double @cpp_name@;
  533. )~~~");
  534. } else {
  535. scoped_generator.append(R"~~~(
  536. Optional<double> @cpp_name@;
  537. )~~~");
  538. }
  539. scoped_generator.append(R"~~~(
  540. if (!@js_name@@js_suffix@.is_undefined()) {
  541. @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  542. if (vm.exception())
  543. @return_statement@
  544. }
  545. )~~~");
  546. if (optional_default_value.has_value()) {
  547. scoped_generator.append(R"~~~(
  548. else
  549. @cpp_name@ = @parameter.optional_default_value@;
  550. )~~~");
  551. } else {
  552. scoped_generator.append(R"~~~(
  553. )~~~");
  554. }
  555. }
  556. } else if (parameter.type.name == "boolean") {
  557. if (!optional) {
  558. scoped_generator.append(R"~~~(
  559. bool @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  560. )~~~");
  561. } else {
  562. if (optional_default_value.has_value()) {
  563. scoped_generator.append(R"~~~(
  564. bool @cpp_name@;
  565. )~~~");
  566. } else {
  567. scoped_generator.append(R"~~~(
  568. Optional<bool> @cpp_name@;
  569. )~~~");
  570. }
  571. scoped_generator.append(R"~~~(
  572. if (!@js_name@@js_suffix@.is_undefined())
  573. @cpp_name@ = @js_name@@js_suffix@.to_boolean();)~~~");
  574. if (optional_default_value.has_value()) {
  575. scoped_generator.append(R"~~~(
  576. else
  577. @cpp_name@ = @parameter.optional_default_value@;
  578. )~~~");
  579. } else {
  580. scoped_generator.append(R"~~~(
  581. )~~~");
  582. }
  583. }
  584. } else if (parameter.type.name == "unsigned long") {
  585. scoped_generator.append(R"~~~(
  586. auto @cpp_name@ = @js_name@@js_suffix@.to_u32(global_object);
  587. if (vm.exception())
  588. @return_statement@
  589. )~~~");
  590. } else if (parameter.type.name == "unsigned short") {
  591. scoped_generator.append(R"~~~(
  592. auto @cpp_name@ = (u16)@js_name@@js_suffix@.to_u32(global_object);
  593. if (vm.exception())
  594. @return_statement@
  595. )~~~");
  596. } else if (parameter.type.name == "long") {
  597. scoped_generator.append(R"~~~(
  598. auto @cpp_name@ = @js_name@@js_suffix@.to_i32(global_object);
  599. if (vm.exception())
  600. @return_statement@
  601. )~~~");
  602. } else if (parameter.type.name == "EventHandler") {
  603. // x.onfoo = function() { ... }
  604. scoped_generator.append(R"~~~(
  605. HTML::EventHandler @cpp_name@;
  606. if (@js_name@@js_suffix@.is_function()) {
  607. @cpp_name@.callback = JS::make_handle(&@js_name@@js_suffix@.as_function());
  608. } else if (@js_name@@js_suffix@.is_string()) {
  609. @cpp_name@.string = @js_name@@js_suffix@.as_string().string();
  610. } else {
  611. @return_statement@
  612. }
  613. )~~~");
  614. } else {
  615. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  616. VERIFY_NOT_REACHED();
  617. }
  618. }
  619. template<typename FunctionType>
  620. static void generate_argument_count_check(SourceGenerator& generator, FunctionType& function)
  621. {
  622. auto argument_count_check_generator = generator.fork();
  623. argument_count_check_generator.set("function.name", function.name);
  624. argument_count_check_generator.set("function.nargs", String::number(function.length()));
  625. if (function.length() == 0)
  626. return;
  627. if (function.length() == 1) {
  628. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  629. argument_count_check_generator.set(".arg_count_suffix", "");
  630. } else {
  631. argument_count_check_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  632. argument_count_check_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  633. }
  634. argument_count_check_generator.append(R"~~~(
  635. if (vm.argument_count() < @function.nargs@) {
  636. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  637. return {};
  638. }
  639. )~~~");
  640. }
  641. static void generate_arguments(SourceGenerator& generator, Vector<IDL::Parameter> const& parameters, StringBuilder& arguments_builder, bool return_void = false)
  642. {
  643. auto arguments_generator = generator.fork();
  644. Vector<String> parameter_names;
  645. size_t argument_index = 0;
  646. for (auto& parameter : parameters) {
  647. parameter_names.append(make_input_acceptable_cpp(parameter.name.to_snakecase()));
  648. arguments_generator.set("argument.index", String::number(argument_index));
  649. arguments_generator.append(R"~~~(
  650. auto arg@argument.index@ = vm.argument(@argument.index@);
  651. )~~~");
  652. bool legacy_null_to_empty_string = parameter.extended_attributes.contains("LegacyNullToEmptyString");
  653. 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);
  654. ++argument_index;
  655. }
  656. arguments_builder.join(", ", parameter_names);
  657. }
  658. static void generate_header(IDL::Interface const& interface)
  659. {
  660. StringBuilder builder;
  661. SourceGenerator generator { builder };
  662. generator.set("name", interface.name);
  663. generator.set("fully_qualified_name", interface.fully_qualified_name);
  664. generator.set("wrapper_base_class", interface.wrapper_base_class);
  665. generator.set("wrapper_class", interface.wrapper_class);
  666. generator.set("wrapper_class:snakecase", interface.wrapper_class.to_snakecase());
  667. generator.append(R"~~~(
  668. #pragma once
  669. #include <LibWeb/Bindings/Wrapper.h>
  670. // FIXME: This is very strange.
  671. #if __has_include(<LibWeb/CSS/@name@.h>)
  672. # include <LibWeb/CSS/@name@.h>
  673. #elif __has_include(<LibWeb/DOM/@name@.h>)
  674. # include <LibWeb/DOM/@name@.h>
  675. #elif __has_include(<LibWeb/HTML/@name@.h>)
  676. # include <LibWeb/HTML/@name@.h>
  677. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  678. # include <LibWeb/UIEvents/@name@.h>
  679. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  680. # include <LibWeb/HighResolutionTime/@name@.h>
  681. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  682. # include <LibWeb/NavigationTiming/@name@.h>
  683. #elif __has_include(<LibWeb/SVG/@name@.h>)
  684. # include <LibWeb/SVG/@name@.h>
  685. #elif __has_include(<LibWeb/XHR/@name@.h>)
  686. # include <LibWeb/XHR/@name@.h>
  687. #endif
  688. )~~~");
  689. if (interface.wrapper_base_class != "Wrapper") {
  690. generator.append(R"~~~(
  691. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  692. )~~~");
  693. }
  694. generator.append(R"~~~(
  695. namespace Web::Bindings {
  696. class @wrapper_class@ : public @wrapper_base_class@ {
  697. JS_OBJECT(@name@, @wrapper_base_class@);
  698. public:
  699. static @wrapper_class@* create(JS::GlobalObject&, @fully_qualified_name@&);
  700. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  701. virtual void initialize(JS::GlobalObject&) override;
  702. virtual ~@wrapper_class@() override;
  703. )~~~");
  704. if (interface.extended_attributes.contains("CustomGet")) {
  705. generator.append(R"~~~(
  706. virtual JS::Value internal_get(JS::PropertyName const&, JS::Value receiver) const override;
  707. )~~~");
  708. }
  709. if (interface.extended_attributes.contains("CustomSet")) {
  710. generator.append(R"~~~(
  711. virtual bool internal_set(JS::PropertyName const&, JS::Value, JS::Value receiver) override;
  712. )~~~");
  713. }
  714. if (interface.extended_attributes.contains("CustomHasProperty")) {
  715. generator.append(R"~~~(
  716. virtual bool internal_has_property(JS::PropertyName const&) const override;
  717. )~~~");
  718. }
  719. if (interface.wrapper_base_class == "Wrapper") {
  720. generator.append(R"~~~(
  721. @fully_qualified_name@& impl() { return *m_impl; }
  722. @fully_qualified_name@ const& impl() const { return *m_impl; }
  723. )~~~");
  724. } else {
  725. generator.append(R"~~~(
  726. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  727. @fully_qualified_name@ const& impl() const { return static_cast<@fully_qualified_name@ const&>(@wrapper_base_class@::impl()); }
  728. )~~~");
  729. }
  730. generator.append(R"~~~(
  731. private:
  732. )~~~");
  733. if (interface.wrapper_base_class == "Wrapper") {
  734. generator.append(R"~~~(
  735. NonnullRefPtr<@fully_qualified_name@> m_impl;
  736. )~~~");
  737. }
  738. generator.append(R"~~~(
  739. };
  740. )~~~");
  741. if (should_emit_wrapper_factory(interface)) {
  742. generator.append(R"~~~(
  743. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  744. )~~~");
  745. }
  746. generator.append(R"~~~(
  747. } // namespace Web::Bindings
  748. )~~~");
  749. outln("{}", generator.as_string_view());
  750. }
  751. void generate_implementation(IDL::Interface const& interface)
  752. {
  753. StringBuilder builder;
  754. SourceGenerator generator { builder };
  755. generator.set("name", interface.name);
  756. generator.set("wrapper_class", interface.wrapper_class);
  757. generator.set("wrapper_base_class", interface.wrapper_base_class);
  758. generator.set("prototype_class", interface.prototype_class);
  759. generator.set("fully_qualified_name", interface.fully_qualified_name);
  760. generator.append(R"~~~(
  761. #include <AK/FlyString.h>
  762. #include <LibJS/Runtime/Array.h>
  763. #include <LibJS/Runtime/Error.h>
  764. #include <LibJS/Runtime/FunctionObject.h>
  765. #include <LibJS/Runtime/GlobalObject.h>
  766. #include <LibJS/Runtime/TypedArray.h>
  767. #include <LibJS/Runtime/Value.h>
  768. #include <LibWeb/Bindings/@prototype_class@.h>
  769. #include <LibWeb/Bindings/@wrapper_class@.h>
  770. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  771. #include <LibWeb/Bindings/CommentWrapper.h>
  772. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  773. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  774. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  775. #include <LibWeb/Bindings/DocumentWrapper.h>
  776. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  777. #include <LibWeb/Bindings/EventWrapperFactory.h>
  778. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  779. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  780. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  781. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  782. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  783. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  784. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  785. #include <LibWeb/Bindings/ImageDataWrapper.h>
  786. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  787. #include <LibWeb/Bindings/TextWrapper.h>
  788. #include <LibWeb/Bindings/WindowObject.h>
  789. #include <LibWeb/DOM/Element.h>
  790. #include <LibWeb/DOM/EventListener.h>
  791. #include <LibWeb/HTML/HTMLElement.h>
  792. #include <LibWeb/Origin.h>
  793. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  794. using namespace Web::CSS;
  795. using namespace Web::DOM;
  796. using namespace Web::HTML;
  797. namespace Web::Bindings {
  798. @wrapper_class@* @wrapper_class@::create(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  799. {
  800. return global_object.heap().allocate<@wrapper_class@>(global_object, global_object, impl);
  801. }
  802. )~~~");
  803. if (interface.wrapper_base_class == "Wrapper") {
  804. generator.append(R"~~~(
  805. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  806. : Wrapper(static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"))
  807. , m_impl(impl)
  808. {
  809. }
  810. )~~~");
  811. } else {
  812. generator.append(R"~~~(
  813. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  814. : @wrapper_base_class@(global_object, impl)
  815. {
  816. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_class@>("@name@"));
  817. VERIFY(success);
  818. }
  819. )~~~");
  820. }
  821. generator.append(R"~~~(
  822. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  823. {
  824. @wrapper_base_class@::initialize(global_object);
  825. }
  826. @wrapper_class@::~@wrapper_class@()
  827. {
  828. }
  829. )~~~");
  830. if (should_emit_wrapper_factory(interface)) {
  831. generator.append(R"~~~(
  832. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  833. {
  834. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  835. }
  836. )~~~");
  837. }
  838. generator.append(R"~~~(
  839. } // namespace Web::Bindings
  840. )~~~");
  841. outln("{}", generator.as_string_view());
  842. }
  843. static void generate_constructor_header(IDL::Interface const& interface)
  844. {
  845. StringBuilder builder;
  846. SourceGenerator generator { builder };
  847. generator.set("name", interface.name);
  848. generator.set("fully_qualified_name", interface.fully_qualified_name);
  849. generator.set("constructor_class", interface.constructor_class);
  850. generator.set("constructor_class:snakecase", interface.constructor_class.to_snakecase());
  851. generator.append(R"~~~(
  852. #pragma once
  853. #include <LibJS/Runtime/NativeFunction.h>
  854. namespace Web::Bindings {
  855. class @constructor_class@ : public JS::NativeFunction {
  856. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  857. public:
  858. explicit @constructor_class@(JS::GlobalObject&);
  859. virtual void initialize(JS::GlobalObject&) override;
  860. virtual ~@constructor_class@() override;
  861. virtual JS::Value call() override;
  862. virtual JS::Value construct(JS::FunctionObject& new_target) override;
  863. private:
  864. virtual bool has_constructor() const override { return true; }
  865. };
  866. } // namespace Web::Bindings
  867. )~~~");
  868. outln("{}", generator.as_string_view());
  869. }
  870. void generate_constructor_implementation(IDL::Interface const& interface)
  871. {
  872. StringBuilder builder;
  873. SourceGenerator generator { builder };
  874. generator.set("name", interface.name);
  875. generator.set("prototype_class", interface.prototype_class);
  876. generator.set("wrapper_class", interface.wrapper_class);
  877. generator.set("constructor_class", interface.constructor_class);
  878. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  879. generator.set("fully_qualified_name", interface.fully_qualified_name);
  880. generator.append(R"~~~(
  881. #include <LibJS/Heap/Heap.h>
  882. #include <LibJS/Runtime/GlobalObject.h>
  883. #include <LibWeb/Bindings/@constructor_class@.h>
  884. #include <LibWeb/Bindings/@prototype_class@.h>
  885. #include <LibWeb/Bindings/@wrapper_class@.h>
  886. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  887. #include <LibWeb/Bindings/WindowObject.h>
  888. #if __has_include(<LibWeb/CSS/@name@.h>)
  889. # include <LibWeb/CSS/@name@.h>
  890. #elif __has_include(<LibWeb/DOM/@name@.h>)
  891. # include <LibWeb/DOM/@name@.h>
  892. #elif __has_include(<LibWeb/HTML/@name@.h>)
  893. # include <LibWeb/HTML/@name@.h>
  894. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  895. # include <LibWeb/UIEvents/@name@.h>
  896. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  897. # include <LibWeb/HighResolutionTime/@name@.h>
  898. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  899. # include <LibWeb/NavigationTiming/@name@.h>
  900. #elif __has_include(<LibWeb/SVG/@name@.h>)
  901. # include <LibWeb/SVG/@name@.h>
  902. #elif __has_include(<LibWeb/XHR/@name@.h>)
  903. # include <LibWeb/XHR/@name@.h>
  904. #endif
  905. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  906. using namespace Web::CSS;
  907. using namespace Web::DOM;
  908. using namespace Web::HTML;
  909. namespace Web::Bindings {
  910. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  911. : NativeFunction(*global_object.function_prototype())
  912. {
  913. }
  914. @constructor_class@::~@constructor_class@()
  915. {
  916. }
  917. JS::Value @constructor_class@::call()
  918. {
  919. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  920. return {};
  921. }
  922. JS::Value @constructor_class@::construct(FunctionObject&)
  923. {
  924. )~~~");
  925. if (interface.constructors.is_empty()) {
  926. // No constructor
  927. generator.set("constructor.length", "0");
  928. generator.append(R"~~~(
  929. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::NotAConstructor, "@name@");
  930. return {};
  931. )~~~");
  932. } else if (interface.constructors.size() == 1) {
  933. // Single constructor
  934. auto& constructor = interface.constructors[0];
  935. generator.set("constructor.length", String::number(constructor.length()));
  936. generator.append(R"~~~(
  937. [[maybe_unused]] auto& vm = this->vm();
  938. auto& global_object = this->global_object();
  939. auto& window = static_cast<WindowObject&>(global_object);
  940. )~~~");
  941. if (!constructor.parameters.is_empty()) {
  942. generate_argument_count_check(generator, constructor);
  943. StringBuilder arguments_builder;
  944. generate_arguments(generator, constructor.parameters, arguments_builder);
  945. generator.set(".constructor_arguments", arguments_builder.string_view());
  946. generator.append(R"~~~(
  947. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window, @.constructor_arguments@); });
  948. )~~~");
  949. } else {
  950. generator.append(R"~~~(
  951. auto impl = throw_dom_exception_if_needed(vm, global_object, [&] { return @fully_qualified_name@::create_with_global_object(window); });
  952. )~~~");
  953. }
  954. generator.append(R"~~~(
  955. if (should_return_empty(impl))
  956. return JS::Value();
  957. return @wrapper_class@::create(global_object, impl.release_value());
  958. )~~~");
  959. } else {
  960. // Multiple constructor overloads - can't do that yet.
  961. TODO();
  962. }
  963. generator.append(R"~~~(
  964. }
  965. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  966. {
  967. auto& vm = this->vm();
  968. auto& window = static_cast<WindowObject&>(global_object);
  969. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  970. NativeFunction::initialize(global_object);
  971. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<@prototype_class@>("@name@"), 0);
  972. define_direct_property(vm.names.length, JS::Value(@constructor.length@), JS::Attribute::Configurable);
  973. )~~~");
  974. for (auto& constant : interface.constants) {
  975. auto constant_generator = generator.fork();
  976. constant_generator.set("constant.name", constant.name);
  977. constant_generator.set("constant.value", constant.value);
  978. constant_generator.append(R"~~~(
  979. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  980. )~~~");
  981. }
  982. generator.append(R"~~~(
  983. }
  984. } // namespace Web::Bindings
  985. )~~~");
  986. outln("{}", generator.as_string_view());
  987. }
  988. static void generate_prototype_header(IDL::Interface const& interface)
  989. {
  990. StringBuilder builder;
  991. SourceGenerator generator { builder };
  992. generator.set("name", interface.name);
  993. generator.set("fully_qualified_name", interface.fully_qualified_name);
  994. generator.set("prototype_class", interface.prototype_class);
  995. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  996. generator.append(R"~~~(
  997. #pragma once
  998. #include <LibJS/Runtime/Object.h>
  999. namespace Web::Bindings {
  1000. class @prototype_class@ : public JS::Object {
  1001. JS_OBJECT(@prototype_class@, JS::Object);
  1002. public:
  1003. explicit @prototype_class@(JS::GlobalObject&);
  1004. virtual void initialize(JS::GlobalObject&) override;
  1005. virtual ~@prototype_class@() override;
  1006. private:
  1007. )~~~");
  1008. for (auto& function : interface.functions) {
  1009. auto function_generator = generator.fork();
  1010. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1011. function_generator.append(R"~~~(
  1012. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  1013. )~~~");
  1014. }
  1015. for (auto& attribute : interface.attributes) {
  1016. auto attribute_generator = generator.fork();
  1017. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1018. attribute_generator.append(R"~~~(
  1019. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_getter);
  1020. )~~~");
  1021. if (!attribute.readonly) {
  1022. attribute_generator.append(R"~~~(
  1023. JS_DECLARE_NATIVE_FUNCTION(@attribute.name:snakecase@_setter);
  1024. )~~~");
  1025. }
  1026. }
  1027. generator.append(R"~~~(
  1028. };
  1029. } // namespace Web::Bindings
  1030. )~~~");
  1031. outln("{}", generator.as_string_view());
  1032. }
  1033. void generate_prototype_implementation(IDL::Interface const& interface)
  1034. {
  1035. StringBuilder builder;
  1036. SourceGenerator generator { builder };
  1037. generator.set("name", interface.name);
  1038. generator.set("parent_name", interface.parent_name);
  1039. generator.set("prototype_class", interface.prototype_class);
  1040. generator.set("prototype_base_class", interface.prototype_base_class);
  1041. generator.set("wrapper_class", interface.wrapper_class);
  1042. generator.set("constructor_class", interface.constructor_class);
  1043. generator.set("prototype_class:snakecase", interface.prototype_class.to_snakecase());
  1044. generator.set("fully_qualified_name", interface.fully_qualified_name);
  1045. generator.append(R"~~~(
  1046. #include <AK/Function.h>
  1047. #include <LibJS/Runtime/Array.h>
  1048. #include <LibJS/Runtime/Error.h>
  1049. #include <LibJS/Runtime/FunctionObject.h>
  1050. #include <LibJS/Runtime/GlobalObject.h>
  1051. #include <LibJS/Runtime/TypedArray.h>
  1052. #include <LibWeb/Bindings/@prototype_class@.h>
  1053. #include <LibWeb/Bindings/@wrapper_class@.h>
  1054. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  1055. #include <LibWeb/Bindings/CSSStyleSheetWrapper.h>
  1056. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  1057. #include <LibWeb/Bindings/CommentWrapper.h>
  1058. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  1059. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  1060. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  1061. #include <LibWeb/Bindings/DocumentWrapper.h>
  1062. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  1063. #include <LibWeb/Bindings/EventWrapper.h>
  1064. #include <LibWeb/Bindings/EventWrapperFactory.h>
  1065. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  1066. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  1067. #include <LibWeb/Bindings/HTMLCollectionWrapper.h>
  1068. #include <LibWeb/Bindings/HTMLFormElementWrapper.h>
  1069. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  1070. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  1071. #include <LibWeb/Bindings/HTMLTableCaptionElementWrapper.h>
  1072. #include <LibWeb/Bindings/HTMLTableSectionElementWrapper.h>
  1073. #include <LibWeb/Bindings/ImageDataWrapper.h>
  1074. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  1075. #include <LibWeb/Bindings/PerformanceTimingWrapper.h>
  1076. #include <LibWeb/Bindings/RangeWrapper.h>
  1077. #include <LibWeb/Bindings/StyleSheetListWrapper.h>
  1078. #include <LibWeb/Bindings/TextWrapper.h>
  1079. #include <LibWeb/Bindings/WindowObject.h>
  1080. #include <LibWeb/DOM/Element.h>
  1081. #include <LibWeb/DOM/EventListener.h>
  1082. #include <LibWeb/DOM/Range.h>
  1083. #include <LibWeb/DOM/Window.h>
  1084. #include <LibWeb/HTML/EventHandler.h>
  1085. #include <LibWeb/HTML/HTMLElement.h>
  1086. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  1087. #include <LibWeb/Origin.h>
  1088. #if __has_include(<LibWeb/Bindings/@prototype_base_class@.h>)
  1089. # include <LibWeb/Bindings/@prototype_base_class@.h>
  1090. #endif
  1091. #if __has_include(<LibWeb/CSS/@name@.h>)
  1092. # include <LibWeb/CSS/@name@.h>
  1093. #elif __has_include(<LibWeb/DOM/@name@.h>)
  1094. # include <LibWeb/DOM/@name@.h>
  1095. #elif __has_include(<LibWeb/HTML/@name@.h>)
  1096. # include <LibWeb/HTML/@name@.h>
  1097. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  1098. # include <LibWeb/UIEvents/@name@.h>
  1099. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  1100. # include <LibWeb/HighResolutionTime/@name@.h>
  1101. #elif __has_include(<LibWeb/NavigationTiming/@name@.h>)
  1102. # include <LibWeb/NavigationTiming/@name@.h>
  1103. #elif __has_include(<LibWeb/SVG/@name@.h>)
  1104. # include <LibWeb/SVG/@name@.h>
  1105. #elif __has_include(<LibWeb/XHR/@name@.h>)
  1106. # include <LibWeb/XHR/@name@.h>
  1107. #endif
  1108. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  1109. using namespace Web::CSS;
  1110. using namespace Web::DOM;
  1111. using namespace Web::HTML;
  1112. using namespace Web::NavigationTiming;
  1113. using namespace Web::XHR;
  1114. namespace Web::Bindings {
  1115. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  1116. : Object(*global_object.object_prototype())
  1117. {
  1118. )~~~");
  1119. if (interface.name == "DOMException") {
  1120. // https://heycam.github.io/webidl/#es-DOMException-specialness
  1121. // Object.getPrototypeOf(DOMException.prototype) === Error.prototype
  1122. generator.append(R"~~~(
  1123. auto success = internal_set_prototype_of(global_object.error_prototype());
  1124. VERIFY(success);
  1125. )~~~");
  1126. } else if (!interface.parent_name.is_empty()) {
  1127. generator.append(R"~~~(
  1128. auto success = internal_set_prototype_of(&static_cast<WindowObject&>(global_object).ensure_web_prototype<@prototype_base_class@>("@parent_name@"));
  1129. VERIFY(success);
  1130. )~~~");
  1131. }
  1132. // FIXME: Currently almost everything gets default_attributes but it should be configurable per attribute.
  1133. // See the spec links for details
  1134. generator.append(R"~~~(
  1135. }
  1136. @prototype_class@::~@prototype_class@()
  1137. {
  1138. }
  1139. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  1140. {
  1141. [[maybe_unused]] auto& vm = this->vm();
  1142. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;
  1143. )~~~");
  1144. // https://heycam.github.io/webidl/#es-attributes
  1145. for (auto& attribute : interface.attributes) {
  1146. auto attribute_generator = generator.fork();
  1147. attribute_generator.set("attribute.name", attribute.name);
  1148. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1149. if (attribute.readonly)
  1150. attribute_generator.set("attribute.setter_callback", "nullptr");
  1151. else
  1152. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1153. attribute_generator.append(R"~~~(
  1154. define_native_accessor("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  1155. )~~~");
  1156. }
  1157. // https://heycam.github.io/webidl/#es-constants
  1158. for (auto& constant : interface.constants) {
  1159. auto constant_generator = generator.fork();
  1160. constant_generator.set("constant.name", constant.name);
  1161. constant_generator.set("constant.value", constant.value);
  1162. constant_generator.append(R"~~~(
  1163. define_direct_property("@constant.name@", JS::Value((i32)@constant.value@), JS::Attribute::Enumerable);
  1164. )~~~");
  1165. }
  1166. // https://heycam.github.io/webidl/#es-operations
  1167. for (auto& function : interface.functions) {
  1168. auto function_generator = generator.fork();
  1169. function_generator.set("function.name", function.name);
  1170. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1171. function_generator.set("function.length", String::number(function.length()));
  1172. function_generator.append(R"~~~(
  1173. define_native_function("@function.name@", @function.name:snakecase@, @function.length@, default_attributes);
  1174. )~~~");
  1175. }
  1176. generator.append(R"~~~(
  1177. Object::initialize(global_object);
  1178. }
  1179. )~~~");
  1180. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  1181. generator.append(R"~~~(
  1182. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  1183. {
  1184. auto* this_object = vm.this_value(global_object).to_object(global_object);
  1185. if (!this_object)
  1186. return {};
  1187. )~~~");
  1188. if (interface.name == "EventTarget") {
  1189. generator.append(R"~~~(
  1190. if (is<WindowObject>(this_object)) {
  1191. return &static_cast<WindowObject*>(this_object)->impl();
  1192. }
  1193. )~~~");
  1194. }
  1195. generator.append(R"~~~(
  1196. if (!is<@wrapper_class@>(this_object)) {
  1197. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  1198. return nullptr;
  1199. }
  1200. return &static_cast<@wrapper_class@*>(this_object)->impl();
  1201. }
  1202. )~~~");
  1203. }
  1204. auto generate_return_statement = [&](auto& return_type) {
  1205. auto scoped_generator = generator.fork();
  1206. scoped_generator.set("return_type", return_type.name);
  1207. if (return_type.name == "undefined") {
  1208. scoped_generator.append(R"~~~(
  1209. return JS::js_undefined();
  1210. )~~~");
  1211. return;
  1212. }
  1213. if (return_type.nullable) {
  1214. if (return_type.is_string()) {
  1215. scoped_generator.append(R"~~~(
  1216. if (retval.is_null())
  1217. return JS::js_null();
  1218. )~~~");
  1219. } else {
  1220. scoped_generator.append(R"~~~(
  1221. if (!retval)
  1222. return JS::js_null();
  1223. )~~~");
  1224. }
  1225. }
  1226. if (return_type.is_string()) {
  1227. scoped_generator.append(R"~~~(
  1228. return JS::js_string(vm, retval);
  1229. )~~~");
  1230. } else if (return_type.name == "ArrayFromVector") {
  1231. // FIXME: Remove this fake type hack once it's no longer needed.
  1232. // Basically once we have NodeList we can throw this out.
  1233. scoped_generator.append(R"~~~(
  1234. auto* new_array = JS::Array::create(global_object, 0);
  1235. for (auto& element : retval)
  1236. new_array->indexed_properties().append(wrap(global_object, element));
  1237. return new_array;
  1238. )~~~");
  1239. } else if (return_type.name == "boolean" || return_type.name == "double") {
  1240. scoped_generator.append(R"~~~(
  1241. return JS::Value(retval);
  1242. )~~~");
  1243. } else if (return_type.name == "short" || return_type.name == "unsigned short" || return_type.name == "long" || return_type.name == "unsigned long") {
  1244. scoped_generator.append(R"~~~(
  1245. return JS::Value((i32)retval);
  1246. )~~~");
  1247. } else if (return_type.name == "Uint8ClampedArray") {
  1248. scoped_generator.append(R"~~~(
  1249. return retval;
  1250. )~~~");
  1251. } else if (return_type.name == "EventHandler") {
  1252. scoped_generator.append(R"~~~(
  1253. if (retval.callback.is_null())
  1254. return JS::js_null();
  1255. return retval.callback.cell();
  1256. )~~~");
  1257. } else {
  1258. scoped_generator.append(R"~~~(
  1259. return wrap(global_object, const_cast<@return_type@&>(*retval));
  1260. )~~~");
  1261. }
  1262. };
  1263. for (auto& attribute : interface.attributes) {
  1264. auto attribute_generator = generator.fork();
  1265. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  1266. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  1267. attribute_generator.set("attribute.name:snakecase", attribute.name.to_snakecase());
  1268. if (attribute.extended_attributes.contains("ImplementedAs")) {
  1269. auto implemented_as = attribute.extended_attributes.get("ImplementedAs").value();
  1270. attribute_generator.set("attribute.cpp_getter_name", implemented_as);
  1271. } else {
  1272. attribute_generator.set("attribute.cpp_getter_name", attribute.name.to_snakecase());
  1273. }
  1274. if (attribute.extended_attributes.contains("Reflect")) {
  1275. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  1276. if (attribute_name.is_null())
  1277. attribute_name = attribute.name;
  1278. attribute_name = make_input_acceptable_cpp(attribute_name);
  1279. attribute_generator.set("attribute.reflect_name", attribute_name);
  1280. } else {
  1281. attribute_generator.set("attribute.reflect_name", attribute.name.to_snakecase());
  1282. }
  1283. attribute_generator.append(R"~~~(
  1284. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.getter_callback@)
  1285. {
  1286. auto* impl = impl_from(vm, global_object);
  1287. if (!impl)
  1288. return {};
  1289. )~~~");
  1290. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  1291. attribute_generator.append(R"~~~(
  1292. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  1293. return JS::js_null();
  1294. )~~~");
  1295. }
  1296. if (attribute.extended_attributes.contains("Reflect")) {
  1297. if (attribute.type.name != "boolean") {
  1298. attribute_generator.append(R"~~~(
  1299. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1300. )~~~");
  1301. } else {
  1302. attribute_generator.append(R"~~~(
  1303. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1304. )~~~");
  1305. }
  1306. } else {
  1307. attribute_generator.append(R"~~~(
  1308. auto retval = impl->@attribute.cpp_getter_name@();
  1309. )~~~");
  1310. }
  1311. generate_return_statement(attribute.type);
  1312. attribute_generator.append(R"~~~(
  1313. }
  1314. )~~~");
  1315. if (!attribute.readonly) {
  1316. attribute_generator.append(R"~~~(
  1317. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@attribute.setter_callback@)
  1318. {
  1319. auto* impl = impl_from(vm, global_object);
  1320. if (!impl)
  1321. return {};
  1322. auto value = vm.argument(0);
  1323. )~~~");
  1324. generate_to_cpp(generator, attribute, "value", "", "cpp_value", false, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  1325. if (attribute.extended_attributes.contains("Reflect")) {
  1326. if (attribute.type.name != "boolean") {
  1327. attribute_generator.append(R"~~~(
  1328. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  1329. )~~~");
  1330. } else {
  1331. attribute_generator.append(R"~~~(
  1332. if (!cpp_value)
  1333. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  1334. else
  1335. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  1336. )~~~");
  1337. }
  1338. } else {
  1339. attribute_generator.append(R"~~~(
  1340. impl->set_@attribute.name:snakecase@(cpp_value);
  1341. )~~~");
  1342. }
  1343. attribute_generator.append(R"~~~(
  1344. return {};
  1345. }
  1346. )~~~");
  1347. }
  1348. }
  1349. // Implementation: Functions
  1350. for (auto& function : interface.functions) {
  1351. auto function_generator = generator.fork();
  1352. function_generator.set("function.name", function.name);
  1353. function_generator.set("function.name:snakecase", function.name.to_snakecase());
  1354. if (function.extended_attributes.contains("ImplementedAs")) {
  1355. auto implemented_as = function.extended_attributes.get("ImplementedAs").value();
  1356. function_generator.set("function.cpp_name", implemented_as);
  1357. } else {
  1358. function_generator.set("function.cpp_name", function.name.to_snakecase());
  1359. }
  1360. function_generator.append(R"~~~(
  1361. JS_DEFINE_NATIVE_FUNCTION(@prototype_class@::@function.name:snakecase@)
  1362. {
  1363. auto* impl = impl_from(vm, global_object);
  1364. if (!impl)
  1365. return {};
  1366. )~~~");
  1367. generate_argument_count_check(generator, function);
  1368. StringBuilder arguments_builder;
  1369. generate_arguments(generator, function.parameters, arguments_builder);
  1370. function_generator.set(".arguments", arguments_builder.string_view());
  1371. function_generator.append(R"~~~(
  1372. auto result = throw_dom_exception_if_needed(vm, global_object, [&] { return impl->@function.cpp_name@(@.arguments@); });
  1373. if (should_return_empty(result))
  1374. return JS::Value();
  1375. [[maybe_unused]] auto retval = result.release_value();
  1376. )~~~");
  1377. generate_return_statement(function.return_type);
  1378. function_generator.append(R"~~~(
  1379. }
  1380. )~~~");
  1381. }
  1382. generator.append(R"~~~(
  1383. } // namespace Web::Bindings
  1384. )~~~");
  1385. outln("{}", generator.as_string_view());
  1386. }