WrapperGenerator.cpp 50 KB

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