WrapperGenerator.cpp 53 KB

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