WrapperGenerator.cpp 48 KB

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