WrapperGenerator.cpp 53 KB

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