WrapperGenerator.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/ByteBuffer.h>
  27. #include <AK/GenericLexer.h>
  28. #include <AK/HashMap.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/SourceGenerator.h>
  31. #include <AK/StringBuilder.h>
  32. #include <LibCore/ArgsParser.h>
  33. #include <LibCore/File.h>
  34. #include <ctype.h>
  35. static String snake_name(const StringView& title_name)
  36. {
  37. StringBuilder builder;
  38. bool first = true;
  39. bool last_was_uppercase = false;
  40. for (auto ch : title_name) {
  41. if (isupper(ch)) {
  42. if (!first && !last_was_uppercase)
  43. builder.append('_');
  44. builder.append(tolower(ch));
  45. } else {
  46. builder.append(ch);
  47. }
  48. first = false;
  49. last_was_uppercase = isupper(ch);
  50. }
  51. return builder.to_string();
  52. }
  53. static String make_input_acceptable_cpp(const String& input)
  54. {
  55. if (input.is_one_of("class", "template", "for", "default", "char")) {
  56. StringBuilder builder;
  57. builder.append(input);
  58. builder.append('_');
  59. return builder.to_string();
  60. }
  61. String input_without_dashes = input;
  62. input_without_dashes.replace("-", "_");
  63. return input_without_dashes;
  64. }
  65. static void report_parsing_error(StringView message, StringView filename, StringView input, size_t offset)
  66. {
  67. // FIXME: Spaghetti code ahead.
  68. size_t lineno = 1;
  69. size_t colno = 1;
  70. size_t start_line = 0;
  71. size_t line_length = 0;
  72. for (size_t index = 0; index < input.length(); ++index) {
  73. if (offset == index)
  74. colno = index - start_line + 1;
  75. if (input[index] == '\n') {
  76. if (index >= offset)
  77. break;
  78. start_line = index + 1;
  79. line_length = 0;
  80. ++lineno;
  81. } else {
  82. ++line_length;
  83. }
  84. }
  85. StringBuilder error_message;
  86. error_message.appendff("{}\n", input.substring_view(start_line, line_length));
  87. for (size_t i = 0; i < colno - 1; ++i)
  88. error_message.append(' ');
  89. error_message.append("\033[1;31m^\n");
  90. error_message.appendff("{}:{}: error: {}\033[0m\n", filename, lineno, message);
  91. warnln("{}", error_message.string_view());
  92. exit(EXIT_FAILURE);
  93. }
  94. namespace IDL {
  95. struct Type {
  96. String name;
  97. bool nullable { false };
  98. };
  99. struct Parameter {
  100. Type type;
  101. String name;
  102. bool optional { false };
  103. };
  104. struct Function {
  105. Type return_type;
  106. String name;
  107. Vector<Parameter> parameters;
  108. HashMap<String, String> extended_attributes;
  109. size_t length() const
  110. {
  111. // FIXME: This seems to produce a length that is way over what it's supposed to be.
  112. // For example, getElementsByTagName has its length set to 20 when it should be 1.
  113. size_t length = 0;
  114. for (auto& parameter : parameters) {
  115. if (!parameter.optional)
  116. length++;
  117. }
  118. return length;
  119. }
  120. };
  121. struct Attribute {
  122. bool readonly { false };
  123. bool unsigned_ { false };
  124. Type type;
  125. String name;
  126. HashMap<String, String> extended_attributes;
  127. // Added for convenience after parsing
  128. String getter_callback_name;
  129. String setter_callback_name;
  130. };
  131. struct Interface {
  132. String name;
  133. String parent_name;
  134. Vector<Attribute> attributes;
  135. Vector<Function> functions;
  136. // Added for convenience after parsing
  137. String wrapper_class;
  138. String wrapper_base_class;
  139. String fully_qualified_name;
  140. String constructor_class;
  141. String prototype_class;
  142. };
  143. static OwnPtr<Interface> parse_interface(StringView filename, const StringView& input)
  144. {
  145. auto interface = make<Interface>();
  146. GenericLexer lexer(input);
  147. auto assert_specific = [&](char ch) {
  148. if (!lexer.consume_specific(ch))
  149. report_parsing_error(String::formatted("expected '{}'", ch), filename, input, lexer.tell());
  150. };
  151. auto consume_whitespace = [&] {
  152. bool consumed = true;
  153. while (consumed) {
  154. consumed = lexer.consume_while([](char ch) { return isspace(ch); }).length() > 0;
  155. if (lexer.consume_specific("//")) {
  156. lexer.consume_until('\n');
  157. consumed = true;
  158. }
  159. }
  160. };
  161. auto assert_string = [&](const StringView& expected) {
  162. if (!lexer.consume_specific(expected))
  163. report_parsing_error(String::formatted("expected '{}'", expected), filename, input, lexer.tell());
  164. };
  165. assert_string("interface");
  166. consume_whitespace();
  167. interface->name = lexer.consume_until([](auto ch) { return isspace(ch); });
  168. consume_whitespace();
  169. if (lexer.consume_specific(':')) {
  170. consume_whitespace();
  171. interface->parent_name = lexer.consume_until([](auto ch) { return isspace(ch); });
  172. consume_whitespace();
  173. }
  174. assert_specific('{');
  175. auto parse_type = [&] {
  176. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '?'; });
  177. auto nullable = lexer.consume_specific('?');
  178. return Type { name, nullable };
  179. };
  180. auto parse_attribute = [&](HashMap<String, String>& extended_attributes) {
  181. bool readonly = lexer.consume_specific("readonly");
  182. if (readonly)
  183. consume_whitespace();
  184. if (lexer.consume_specific("attribute"))
  185. consume_whitespace();
  186. bool unsigned_ = lexer.consume_specific("unsigned");
  187. if (unsigned_)
  188. consume_whitespace();
  189. auto type = parse_type();
  190. consume_whitespace();
  191. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ';'; });
  192. consume_whitespace();
  193. assert_specific(';');
  194. Attribute attribute;
  195. attribute.readonly = readonly;
  196. attribute.unsigned_ = unsigned_;
  197. attribute.type = type;
  198. attribute.name = name;
  199. attribute.getter_callback_name = String::formatted("{}_getter", snake_name(attribute.name));
  200. attribute.setter_callback_name = String::formatted("{}_setter", snake_name(attribute.name));
  201. attribute.extended_attributes = move(extended_attributes);
  202. interface->attributes.append(move(attribute));
  203. };
  204. auto parse_function = [&](HashMap<String, String>& extended_attributes) {
  205. auto return_type = parse_type();
  206. consume_whitespace();
  207. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == '('; });
  208. consume_whitespace();
  209. assert_specific('(');
  210. Vector<Parameter> parameters;
  211. for (;;) {
  212. if (lexer.consume_specific(')'))
  213. break;
  214. bool optional = lexer.consume_specific("optional");
  215. if (optional)
  216. consume_whitespace();
  217. auto type = parse_type();
  218. consume_whitespace();
  219. auto name = lexer.consume_until([](auto ch) { return isspace(ch) || ch == ',' || ch == ')'; });
  220. parameters.append({ move(type), move(name), optional });
  221. if (lexer.consume_specific(')'))
  222. break;
  223. assert_specific(',');
  224. consume_whitespace();
  225. }
  226. consume_whitespace();
  227. assert_specific(';');
  228. interface->functions.append(Function { return_type, name, move(parameters), move(extended_attributes) });
  229. };
  230. auto parse_extended_attributes = [&] {
  231. HashMap<String, String> extended_attributes;
  232. for (;;) {
  233. consume_whitespace();
  234. if (lexer.consume_specific(']'))
  235. break;
  236. auto name = lexer.consume_until([](auto ch) { return ch == ']' || ch == '=' || ch == ','; });
  237. if (lexer.consume_specific('=')) {
  238. auto value = lexer.consume_until([](auto ch) { return ch == ']' || ch == ','; });
  239. extended_attributes.set(name, value);
  240. } else {
  241. extended_attributes.set(name, {});
  242. }
  243. lexer.consume_specific(',');
  244. }
  245. consume_whitespace();
  246. return extended_attributes;
  247. };
  248. for (;;) {
  249. HashMap<String, String> extended_attributes;
  250. consume_whitespace();
  251. if (lexer.consume_specific('}')) {
  252. consume_whitespace();
  253. assert_specific(';');
  254. break;
  255. }
  256. if (lexer.consume_specific('[')) {
  257. extended_attributes = parse_extended_attributes();
  258. }
  259. if (lexer.next_is("readonly") || lexer.next_is("attribute")) {
  260. parse_attribute(extended_attributes);
  261. continue;
  262. }
  263. parse_function(extended_attributes);
  264. }
  265. interface->wrapper_class = String::formatted("{}Wrapper", interface->name);
  266. interface->wrapper_base_class = String::formatted("{}Wrapper", interface->parent_name.is_empty() ? String::empty() : interface->parent_name);
  267. interface->constructor_class = String::formatted("{}Constructor", interface->name);
  268. interface->prototype_class = String::formatted("{}Prototype", interface->name);
  269. return interface;
  270. }
  271. }
  272. static void generate_constructor_header(const IDL::Interface&);
  273. static void generate_constructor_implementation(const IDL::Interface&);
  274. static void generate_prototype_header(const IDL::Interface&);
  275. static void generate_prototype_implementation(const IDL::Interface&);
  276. static void generate_header(const IDL::Interface&);
  277. static void generate_implementation(const IDL::Interface&);
  278. int main(int argc, char** argv)
  279. {
  280. Core::ArgsParser args_parser;
  281. const char* path = nullptr;
  282. bool header_mode = false;
  283. bool implementation_mode = false;
  284. bool constructor_header_mode = false;
  285. bool constructor_implementation_mode = false;
  286. bool prototype_header_mode = false;
  287. bool prototype_implementation_mode = false;
  288. args_parser.add_option(header_mode, "Generate the wrapper .h file", "header", 'H');
  289. args_parser.add_option(implementation_mode, "Generate the wrapper .cpp file", "implementation", 'I');
  290. args_parser.add_option(constructor_header_mode, "Generate the constructor .h file", "constructor-header", 'C');
  291. args_parser.add_option(constructor_implementation_mode, "Generate the constructor .cpp file", "constructor-implementation", 'O');
  292. args_parser.add_option(prototype_header_mode, "Generate the prototype .h file", "prototype-header", 'P');
  293. args_parser.add_option(prototype_implementation_mode, "Generate the prototype .cpp file", "prototype-implementation", 'R');
  294. args_parser.add_positional_argument(path, "IDL file", "idl-file");
  295. args_parser.parse(argc, argv);
  296. auto file_or_error = Core::File::open(path, Core::IODevice::ReadOnly);
  297. if (file_or_error.is_error()) {
  298. fprintf(stderr, "Cannot open %s\n", path);
  299. return 1;
  300. }
  301. LexicalPath lexical_path(path);
  302. auto namespace_ = lexical_path.parts().at(lexical_path.parts().size() - 2);
  303. auto data = file_or_error.value()->read_all();
  304. auto interface = IDL::parse_interface(path, data);
  305. if (!interface) {
  306. warnln("Cannot parse {}", path);
  307. return 1;
  308. }
  309. if (namespace_.is_one_of("DOM", "HTML", "UIEvents", "HighResolutionTime", "SVG")) {
  310. StringBuilder builder;
  311. builder.append(namespace_);
  312. builder.append("::");
  313. builder.append(interface->name);
  314. interface->fully_qualified_name = builder.to_string();
  315. } else {
  316. interface->fully_qualified_name = interface->name;
  317. }
  318. #if 0
  319. dbgln("Attributes:");
  320. for (auto& attribute : interface->attributes) {
  321. dbg() << " " << (attribute.readonly ? "Readonly " : "")
  322. << attribute.type.name << (attribute.type.nullable ? "?" : "")
  323. << " " << attribute.name;
  324. }
  325. dbgln("Functions:");
  326. for (auto& function : interface->functions) {
  327. dbg() << " " << function.return_type.name << (function.return_type.nullable ? "?" : "")
  328. << " " << function.name;
  329. for (auto& parameter : function.parameters) {
  330. dbg() << " " << parameter.type.name << (parameter.type.nullable ? "?" : "") << " " << parameter.name;
  331. }
  332. }
  333. #endif
  334. if (header_mode)
  335. generate_header(*interface);
  336. if (implementation_mode)
  337. generate_implementation(*interface);
  338. if (constructor_header_mode)
  339. generate_constructor_header(*interface);
  340. if (constructor_implementation_mode)
  341. generate_constructor_implementation(*interface);
  342. if (prototype_header_mode)
  343. generate_prototype_header(*interface);
  344. if (prototype_implementation_mode)
  345. generate_prototype_implementation(*interface);
  346. return 0;
  347. }
  348. static bool should_emit_wrapper_factory(const IDL::Interface& interface)
  349. {
  350. // FIXME: This is very hackish.
  351. if (interface.name == "Event")
  352. return false;
  353. if (interface.name == "EventTarget")
  354. return false;
  355. if (interface.name == "Node")
  356. return false;
  357. if (interface.name == "Text")
  358. return false;
  359. if (interface.name == "Document")
  360. return false;
  361. if (interface.name == "DocumentType")
  362. return false;
  363. if (interface.name.ends_with("Element"))
  364. return false;
  365. return true;
  366. }
  367. static bool is_wrappable_type(const IDL::Type& type)
  368. {
  369. if (type.name == "Node")
  370. return true;
  371. if (type.name == "Document")
  372. return true;
  373. if (type.name == "Text")
  374. return true;
  375. if (type.name == "DocumentType")
  376. return true;
  377. if (type.name.ends_with("Element"))
  378. return true;
  379. if (type.name == "ImageData")
  380. return true;
  381. return false;
  382. }
  383. static void generate_header(const IDL::Interface& interface)
  384. {
  385. StringBuilder builder;
  386. SourceGenerator generator { builder };
  387. generator.set("name", interface.name);
  388. generator.set("fully_qualified_name", interface.fully_qualified_name);
  389. generator.set("wrapper_base_class", interface.wrapper_base_class);
  390. generator.set("wrapper_class", interface.wrapper_class);
  391. generator.set("wrapper_class:snakecase", snake_name(interface.wrapper_class));
  392. generator.append(R"~~~(
  393. #pragma once
  394. #include <LibWeb/Bindings/Wrapper.h>
  395. // FIXME: This is very strange.
  396. #if __has_include(<LibWeb/DOM/@name@.h>)
  397. # include <LibWeb/DOM/@name@.h>
  398. #elif __has_include(<LibWeb/HTML/@name@.h>)
  399. # include <LibWeb/HTML/@name@.h>
  400. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  401. # include <LibWeb/UIEvents/@name@.h>
  402. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  403. # include <LibWeb/HighResolutionTime/@name@.h>
  404. #elif __has_include(<LibWeb/SVG/@name@.h>)
  405. # include <LibWeb/SVG/@name@.h>
  406. #endif
  407. )~~~");
  408. if (interface.wrapper_base_class != "Wrapper") {
  409. generator.append(R"~~~(
  410. #include <LibWeb/Bindings/@wrapper_base_class@.h>
  411. )~~~");
  412. }
  413. generator.append(R"~~~(
  414. namespace Web::Bindings {
  415. class @wrapper_class@ : public @wrapper_base_class@ {
  416. JS_OBJECT(@wrapper_class@, @wrapper_base_class@);
  417. public:
  418. @wrapper_class@(JS::GlobalObject&, @fully_qualified_name@&);
  419. virtual void initialize(JS::GlobalObject&) override;
  420. virtual ~@wrapper_class@() override;
  421. )~~~");
  422. if (interface.wrapper_base_class == "Wrapper") {
  423. generator.append(R"~~~(
  424. @fully_qualified_name@& impl() { return *m_impl; }
  425. const @fully_qualified_name@& impl() const { return *m_impl; }
  426. )~~~");
  427. } else {
  428. generator.append(R"~~~(
  429. @fully_qualified_name@& impl() { return static_cast<@fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  430. const @fully_qualified_name@& impl() const { return static_cast<const @fully_qualified_name@&>(@wrapper_base_class@::impl()); }
  431. )~~~");
  432. }
  433. generator.append(R"~~~(
  434. private:
  435. )~~~");
  436. for (auto& function : interface.functions) {
  437. auto function_generator = generator.fork();
  438. function_generator.set("function.name:snakecase", snake_name(function.name));
  439. function_generator.append(R"~~~(
  440. JS_DECLARE_NATIVE_FUNCTION(@function.name:snakecase@);
  441. )~~~");
  442. }
  443. for (auto& attribute : interface.attributes) {
  444. auto attribute_generator = generator.fork();
  445. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  446. attribute_generator.append(R"~~~(
  447. JS_DECLARE_NATIVE_GETTER(@attribute.name:snakecase@_getter);
  448. )~~~");
  449. if (!attribute.readonly) {
  450. attribute_generator.append(R"~~~(
  451. JS_DECLARE_NATIVE_SETTER(@attribute.name:snakecase@_setter);
  452. )~~~");
  453. }
  454. }
  455. if (interface.wrapper_base_class == "Wrapper") {
  456. generator.append(R"~~~(
  457. NonnullRefPtr<@fully_qualified_name@> m_impl;
  458. )~~~");
  459. }
  460. generator.append(R"~~~(
  461. };
  462. )~~~");
  463. if (should_emit_wrapper_factory(interface)) {
  464. generator.append(R"~~~(
  465. @wrapper_class@* wrap(JS::GlobalObject&, @fully_qualified_name@&);
  466. )~~~");
  467. }
  468. generator.append(R"~~~(
  469. } // namespace Web::Bindings
  470. )~~~");
  471. outln("{}", generator.as_string_view());
  472. }
  473. void generate_implementation(const IDL::Interface& interface)
  474. {
  475. StringBuilder builder;
  476. SourceGenerator generator { builder };
  477. generator.set("name", interface.name);
  478. generator.set("wrapper_class", interface.wrapper_class);
  479. generator.set("wrapper_base_class", interface.wrapper_base_class);
  480. generator.set("fully_qualified_name", interface.fully_qualified_name);
  481. generator.append(R"~~~(
  482. #include <AK/FlyString.h>
  483. #include <LibJS/Runtime/Array.h>
  484. #include <LibJS/Runtime/Error.h>
  485. #include <LibJS/Runtime/Function.h>
  486. #include <LibJS/Runtime/GlobalObject.h>
  487. #include <LibJS/Runtime/Uint8ClampedArray.h>
  488. #include <LibJS/Runtime/Value.h>
  489. #include <LibWeb/Bindings/@wrapper_class@.h>
  490. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  491. #include <LibWeb/Bindings/CommentWrapper.h>
  492. #include <LibWeb/Bindings/DOMImplementationWrapper.h>
  493. #include <LibWeb/Bindings/DocumentFragmentWrapper.h>
  494. #include <LibWeb/Bindings/DocumentTypeWrapper.h>
  495. #include <LibWeb/Bindings/DocumentWrapper.h>
  496. #include <LibWeb/Bindings/EventTargetWrapperFactory.h>
  497. #include <LibWeb/Bindings/HTMLCanvasElementWrapper.h>
  498. #include <LibWeb/Bindings/HTMLHeadElementWrapper.h>
  499. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  500. #include <LibWeb/Bindings/ImageDataWrapper.h>
  501. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  502. #include <LibWeb/Bindings/TextWrapper.h>
  503. #include <LibWeb/Bindings/WindowObject.h>
  504. #include <LibWeb/DOM/Element.h>
  505. #include <LibWeb/DOM/EventListener.h>
  506. #include <LibWeb/HTML/HTMLElement.h>
  507. #include <LibWeb/Origin.h>
  508. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  509. using namespace Web::DOM;
  510. using namespace Web::HTML;
  511. namespace Web::Bindings {
  512. )~~~");
  513. if (interface.wrapper_base_class == "Wrapper") {
  514. generator.append(R"~~~(
  515. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  516. : Wrapper(*global_object.object_prototype())
  517. , m_impl(impl)
  518. {
  519. }
  520. )~~~");
  521. } else {
  522. generator.append(R"~~~(
  523. @wrapper_class@::@wrapper_class@(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  524. : @wrapper_base_class@(global_object, impl)
  525. {
  526. set_prototype(static_cast<WindowObject&>(global_object).web_prototype("@name@"));
  527. }
  528. )~~~");
  529. }
  530. generator.append(R"~~~(
  531. void @wrapper_class@::initialize(JS::GlobalObject& global_object)
  532. {
  533. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable;
  534. @wrapper_base_class@::initialize(global_object);
  535. )~~~");
  536. for (auto& attribute : interface.attributes) {
  537. auto attribute_generator = generator.fork();
  538. attribute_generator.set("attribute.name", attribute.name);
  539. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  540. if (attribute.readonly)
  541. attribute_generator.set("attribute.setter_callback", "nullptr");
  542. else
  543. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  544. attribute_generator.append(R"~~~(
  545. define_native_property("@attribute.name@", @attribute.getter_callback@, @attribute.setter_callback@, default_attributes);
  546. )~~~");
  547. }
  548. for (auto& function : interface.functions) {
  549. auto function_generator = generator.fork();
  550. function_generator.set("function.name", function.name);
  551. function_generator.set("function.name:snakecase", snake_name(function.name));
  552. function_generator.set("function.name:length", String::number(function.name.length()));
  553. function_generator.append(R"~~~(
  554. define_native_function("@function.name@", @function.name:snakecase@, @function.name:length@, default_attributes);
  555. )~~~");
  556. }
  557. generator.append(R"~~~(
  558. }
  559. @wrapper_class@::~@wrapper_class@()
  560. {
  561. }
  562. )~~~");
  563. if (!interface.attributes.is_empty() || !interface.functions.is_empty()) {
  564. generator.append(R"~~~(
  565. static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  566. {
  567. auto* this_object = vm.this_value(global_object).to_object(global_object);
  568. if (!this_object)
  569. return {};
  570. if (!is<@wrapper_class@>(this_object)) {
  571. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@fully_qualified_name@");
  572. return nullptr;
  573. }
  574. return &static_cast<@wrapper_class@*>(this_object)->impl();
  575. }
  576. )~~~");
  577. }
  578. auto generate_to_cpp = [&](auto& parameter, auto& js_name, const auto& js_suffix, auto cpp_name, bool return_void = false, bool legacy_null_to_empty_string = false, bool optional = false) {
  579. auto scoped_generator = generator.fork();
  580. scoped_generator.set("cpp_name", cpp_name);
  581. scoped_generator.set("js_name", js_name);
  582. scoped_generator.set("js_suffix", js_suffix);
  583. scoped_generator.set("legacy_null_to_empty_string", legacy_null_to_empty_string ? "true" : "false");
  584. scoped_generator.set("parameter.type.name", parameter.type.name);
  585. if (return_void)
  586. scoped_generator.set("return_statement", "return;");
  587. else
  588. scoped_generator.set("return_statement", "return {};");
  589. // FIXME: Add support for optional to all types
  590. if (parameter.type.name == "DOMString") {
  591. if (!optional) {
  592. scoped_generator.append(R"~~~(
  593. auto @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  594. if (vm.exception())
  595. @return_statement@
  596. )~~~");
  597. } else {
  598. scoped_generator.append(R"~~~(
  599. String @cpp_name@;
  600. if (!@js_name@@js_suffix@.is_undefined()) {
  601. @cpp_name@ = @js_name@@js_suffix@.to_string(global_object, @legacy_null_to_empty_string@);
  602. if (vm.exception())
  603. @return_statement@
  604. }
  605. )~~~");
  606. }
  607. } else if (parameter.type.name == "EventListener") {
  608. scoped_generator.append(R"~~~(
  609. if (!@js_name@@js_suffix@.is_function()) {
  610. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "Function");
  611. @return_statement@
  612. }
  613. auto @cpp_name@ = adopt(*new EventListener(JS::make_handle(&@js_name@@js_suffix@.as_function())));
  614. )~~~");
  615. } else if (is_wrappable_type(parameter.type)) {
  616. scoped_generator.append(R"~~~(
  617. auto @cpp_name@_object = @js_name@@js_suffix@.to_object(global_object);
  618. if (vm.exception())
  619. @return_statement@
  620. if (!is<@parameter.type.name@Wrapper>(@cpp_name@_object)) {
  621. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotA, "@parameter.type.name@");
  622. @return_statement@
  623. }
  624. auto& @cpp_name@ = static_cast<@parameter.type.name@Wrapper*>(@cpp_name@_object)->impl();
  625. )~~~");
  626. } else if (parameter.type.name == "double") {
  627. scoped_generator.append(R"~~~(
  628. auto @cpp_name@ = @js_name@@js_suffix@.to_double(global_object);
  629. if (vm.exception())
  630. @return_statement@
  631. )~~~");
  632. } else if (parameter.type.name == "boolean") {
  633. scoped_generator.append(R"~~~(
  634. auto @cpp_name@ = @js_name@@js_suffix@.to_boolean();
  635. )~~~");
  636. } else {
  637. dbgln("Unimplemented JS-to-C++ conversion: {}", parameter.type.name);
  638. ASSERT_NOT_REACHED();
  639. }
  640. };
  641. auto generate_arguments = [&](auto& parameters, auto& arguments_builder, bool return_void = false) {
  642. auto arguments_generator = generator.fork();
  643. Vector<String> parameter_names;
  644. size_t argument_index = 0;
  645. for (auto& parameter : parameters) {
  646. parameter_names.append(snake_name(parameter.name));
  647. arguments_generator.set("argument.index", String::number(argument_index));
  648. arguments_generator.append(R"~~~(
  649. auto arg@argument.index@ = vm.argument(@argument.index@);
  650. )~~~");
  651. // FIXME: Parameters can have [LegacyNullToEmptyString] attached.
  652. generate_to_cpp(parameter, "arg", String::number(argument_index), snake_name(parameter.name), return_void, false, parameter.optional);
  653. ++argument_index;
  654. }
  655. arguments_builder.join(", ", parameter_names);
  656. };
  657. auto generate_return_statement = [&](auto& return_type) {
  658. auto scoped_generator = generator.fork();
  659. scoped_generator.set("return_type", return_type.name);
  660. if (return_type.name == "undefined") {
  661. scoped_generator.append(R"~~~(
  662. return JS::js_undefined();
  663. )~~~");
  664. return;
  665. }
  666. if (return_type.nullable) {
  667. if (return_type.name == "DOMString") {
  668. scoped_generator.append(R"~~~(
  669. if (retval.is_null())
  670. return JS::js_null();
  671. )~~~");
  672. } else {
  673. scoped_generator.append(R"~~~(
  674. if (!retval)
  675. return JS::js_null();
  676. )~~~");
  677. }
  678. }
  679. if (return_type.name == "DOMString") {
  680. scoped_generator.append(R"~~~(
  681. return JS::js_string(vm, retval);
  682. )~~~");
  683. } else if (return_type.name == "ArrayFromVector") {
  684. // FIXME: Remove this fake type hack once it's no longer needed.
  685. // Basically once we have NodeList we can throw this out.
  686. scoped_generator.append(R"~~~(
  687. auto* new_array = JS::Array::create(global_object);
  688. for (auto& element : retval)
  689. new_array->indexed_properties().append(wrap(global_object, element));
  690. return new_array;
  691. )~~~");
  692. } else if (return_type.name == "long" || return_type.name == "double" || return_type.name == "boolean" || return_type.name == "short") {
  693. scoped_generator.append(R"~~~(
  694. return JS::Value(retval);
  695. )~~~");
  696. } else if (return_type.name == "Uint8ClampedArray") {
  697. scoped_generator.append(R"~~~(
  698. return retval;
  699. )~~~");
  700. } else {
  701. scoped_generator.append(R"~~~(
  702. return wrap(global_object, const_cast<@return_type@&>(*retval));
  703. )~~~");
  704. }
  705. };
  706. for (auto& attribute : interface.attributes) {
  707. auto attribute_generator = generator.fork();
  708. attribute_generator.set("attribute.getter_callback", attribute.getter_callback_name);
  709. attribute_generator.set("attribute.setter_callback", attribute.setter_callback_name);
  710. attribute_generator.set("attribute.name:snakecase", snake_name(attribute.name));
  711. if (attribute.extended_attributes.contains("Reflect")) {
  712. auto attribute_name = attribute.extended_attributes.get("Reflect").value();
  713. if (attribute_name.is_null())
  714. attribute_name = attribute.name;
  715. attribute_name = make_input_acceptable_cpp(attribute_name);
  716. attribute_generator.set("attribute.reflect_name", attribute_name);
  717. } else {
  718. attribute_generator.set("attribute.reflect_name", snake_name(attribute.name));
  719. }
  720. attribute_generator.append(R"~~~(
  721. JS_DEFINE_NATIVE_GETTER(@wrapper_class@::@attribute.getter_callback@)
  722. {
  723. auto* impl = impl_from(vm, global_object);
  724. if (!impl)
  725. return {};
  726. )~~~");
  727. if (attribute.extended_attributes.contains("ReturnNullIfCrossOrigin")) {
  728. attribute_generator.append(R"~~~(
  729. if (!impl->may_access_from_origin(static_cast<WindowObject&>(global_object).origin()))
  730. return JS::js_null();
  731. )~~~");
  732. }
  733. if (attribute.extended_attributes.contains("Reflect")) {
  734. if (attribute.type.name != "boolean") {
  735. attribute_generator.append(R"~~~(
  736. auto retval = impl->attribute(HTML::AttributeNames::@attribute.reflect_name@);
  737. )~~~");
  738. } else {
  739. attribute_generator.append(R"~~~(
  740. auto retval = impl->has_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  741. )~~~");
  742. }
  743. } else {
  744. attribute_generator.append(R"~~~(
  745. auto retval = impl->@attribute.name:snakecase@();
  746. )~~~");
  747. }
  748. generate_return_statement(attribute.type);
  749. attribute_generator.append(R"~~~(
  750. }
  751. )~~~");
  752. if (!attribute.readonly) {
  753. attribute_generator.append(R"~~~(
  754. JS_DEFINE_NATIVE_SETTER(@wrapper_class@::@attribute.setter_callback@)
  755. {
  756. auto* impl = impl_from(vm, global_object);
  757. if (!impl)
  758. return;
  759. )~~~");
  760. generate_to_cpp(attribute, "value", "", "cpp_value", true, attribute.extended_attributes.contains("LegacyNullToEmptyString"));
  761. if (attribute.extended_attributes.contains("Reflect")) {
  762. if (attribute.type.name != "boolean") {
  763. attribute_generator.append(R"~~~(
  764. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, cpp_value);
  765. )~~~");
  766. } else {
  767. attribute_generator.append(R"~~~(
  768. if (!cpp_value)
  769. impl->remove_attribute(HTML::AttributeNames::@attribute.reflect_name@);
  770. else
  771. impl->set_attribute(HTML::AttributeNames::@attribute.reflect_name@, String::empty());
  772. )~~~");
  773. }
  774. } else {
  775. attribute_generator.append(R"~~~(
  776. impl->set_@attribute.name:snakecase@(cpp_value);
  777. )~~~");
  778. }
  779. attribute_generator.append(R"~~~(
  780. }
  781. )~~~");
  782. }
  783. }
  784. // Implementation: Functions
  785. for (auto& function : interface.functions) {
  786. auto function_generator = generator.fork();
  787. function_generator.set("function.name", function.name);
  788. function_generator.set("function.name:snakecase", snake_name(function.name));
  789. function_generator.set("function.nargs", String::number(function.length()));
  790. function_generator.append(R"~~~(\
  791. JS_DEFINE_NATIVE_FUNCTION(@wrapper_class@::@function.name:snakecase@)
  792. {
  793. auto* impl = impl_from(vm, global_object);
  794. if (!impl)
  795. return {};
  796. )~~~");
  797. if (function.length() > 0) {
  798. if (function.length() == 1) {
  799. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountOne");
  800. function_generator.set(".arg_count_suffix", "");
  801. } else {
  802. function_generator.set(".bad_arg_count", "JS::ErrorType::BadArgCountMany");
  803. function_generator.set(".arg_count_suffix", String::formatted(", \"{}\"", function.length()));
  804. }
  805. function_generator.append(R"~~~(
  806. if (vm.argument_count() < @function.nargs@) {
  807. vm.throw_exception<JS::TypeError>(global_object, @.bad_arg_count@, "@function.name@"@.arg_count_suffix@);
  808. return {};
  809. }
  810. )~~~");
  811. }
  812. StringBuilder arguments_builder;
  813. generate_arguments(function.parameters, arguments_builder);
  814. function_generator.set(".arguments", arguments_builder.string_view());
  815. if (function.return_type.name != "undefined") {
  816. function_generator.append(R"~~~(
  817. auto retval = impl->@function.name:snakecase@(@.arguments@);
  818. )~~~");
  819. } else {
  820. function_generator.append(R"~~~(
  821. impl->@function.name:snakecase@(@.arguments@);
  822. )~~~");
  823. }
  824. generate_return_statement(function.return_type);
  825. function_generator.append(R"~~~(
  826. }
  827. )~~~");
  828. }
  829. if (should_emit_wrapper_factory(interface)) {
  830. generator.append(R"~~~(
  831. @wrapper_class@* wrap(JS::GlobalObject& global_object, @fully_qualified_name@& impl)
  832. {
  833. return static_cast<@wrapper_class@*>(wrap_impl(global_object, impl));
  834. }
  835. )~~~");
  836. }
  837. generator.append(R"~~~(
  838. } // namespace Web::Bindings
  839. )~~~");
  840. outln("{}", generator.as_string_view());
  841. }
  842. static void generate_constructor_header(const IDL::Interface& interface)
  843. {
  844. StringBuilder builder;
  845. SourceGenerator generator { builder };
  846. generator.set("name", interface.name);
  847. generator.set("fully_qualified_name", interface.fully_qualified_name);
  848. generator.set("constructor_class", interface.constructor_class);
  849. generator.set("constructor_class:snakecase", snake_name(interface.constructor_class));
  850. generator.append(R"~~~(
  851. #pragma once
  852. #include <LibJS/Runtime/NativeFunction.h>
  853. namespace Web::Bindings {
  854. class @constructor_class@ : public JS::NativeFunction {
  855. JS_OBJECT(@constructor_class@, JS::NativeFunction);
  856. public:
  857. explicit @constructor_class@(JS::GlobalObject&);
  858. virtual void initialize(JS::GlobalObject&) override;
  859. virtual ~@constructor_class@() override;
  860. virtual JS::Value call() override;
  861. virtual JS::Value construct(JS::Function& new_target) override;
  862. private:
  863. virtual bool has_constructor() const override { return true; }
  864. };
  865. } // namespace Web::Bindings
  866. )~~~");
  867. outln("{}", generator.as_string_view());
  868. }
  869. void generate_constructor_implementation(const IDL::Interface& interface)
  870. {
  871. StringBuilder builder;
  872. SourceGenerator generator { builder };
  873. generator.set("name", interface.name);
  874. generator.set("prototype_class", interface.prototype_class);
  875. generator.set("wrapper_class", interface.wrapper_class);
  876. generator.set("constructor_class", interface.constructor_class);
  877. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  878. generator.set("fully_qualified_name", interface.fully_qualified_name);
  879. generator.append(R"~~~(
  880. #include <LibJS/Heap/Heap.h>
  881. #include <LibJS/Runtime/GlobalObject.h>
  882. #include <LibWeb/Bindings/@constructor_class@.h>
  883. #include <LibWeb/Bindings/@prototype_class@.h>
  884. #include <LibWeb/Bindings/@wrapper_class@.h>
  885. #include <LibWeb/Bindings/WindowObject.h>
  886. #if __has_include(<LibWeb/DOM/@name@.h>)
  887. # include <LibWeb/DOM/@name@.h>
  888. #elif __has_include(<LibWeb/HTML/@name@.h>)
  889. # include <LibWeb/HTML/@name@.h>
  890. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  891. # include <LibWeb/UIEvents/@name@.h>
  892. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  893. # include <LibWeb/HighResolutionTime/@name@.h>
  894. #elif __has_include(<LibWeb/SVG/@name@.h>)
  895. # include <LibWeb/SVG/@name@.h>
  896. #endif
  897. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  898. using namespace Web::DOM;
  899. using namespace Web::HTML;
  900. namespace Web::Bindings {
  901. @constructor_class@::@constructor_class@(JS::GlobalObject& global_object)
  902. : NativeFunction(*global_object.function_prototype())
  903. {
  904. }
  905. @constructor_class@::~@constructor_class@()
  906. {
  907. }
  908. JS::Value @constructor_class@::call()
  909. {
  910. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "@name@");
  911. return {};
  912. }
  913. JS::Value @constructor_class@::construct(Function&)
  914. {
  915. return {};
  916. #if 0
  917. // FIXME: It would be cool to construct stuff!
  918. auto& window = static_cast<WindowObject&>(global_object());
  919. return heap().allocate<@wrapper_class@>(window, window, @fully_qualified_name@::create(window.impl()));
  920. #endif
  921. }
  922. void @constructor_class@::initialize(JS::GlobalObject& global_object)
  923. {
  924. auto& vm = this->vm();
  925. auto& window = static_cast<WindowObject&>(global_object);
  926. [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
  927. NativeFunction::initialize(global_object);
  928. define_property(vm.names.prototype, window.web_prototype("@prototype_class@"), 0);
  929. define_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
  930. }
  931. } // namespace Web::Bindings
  932. )~~~");
  933. outln("{}", generator.as_string_view());
  934. }
  935. static void generate_prototype_header(const IDL::Interface& interface)
  936. {
  937. StringBuilder builder;
  938. SourceGenerator generator { builder };
  939. generator.set("name", interface.name);
  940. generator.set("fully_qualified_name", interface.fully_qualified_name);
  941. generator.set("prototype_class", interface.prototype_class);
  942. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  943. generator.append(R"~~~(
  944. #pragma once
  945. #include <LibJS/Runtime/Object.h>
  946. namespace Web::Bindings {
  947. class @prototype_class@ : public JS::Object {
  948. JS_OBJECT(@prototype_class@, JS::Object);
  949. public:
  950. explicit @prototype_class@(JS::GlobalObject&);
  951. virtual void initialize(JS::GlobalObject&) override;
  952. virtual ~@prototype_class@() override;
  953. };
  954. } // namespace Web::Bindings
  955. )~~~");
  956. outln("{}", generator.as_string_view());
  957. }
  958. void generate_prototype_implementation(const IDL::Interface& interface)
  959. {
  960. StringBuilder builder;
  961. SourceGenerator generator { builder };
  962. generator.set("name", interface.name);
  963. generator.set("prototype_class", interface.prototype_class);
  964. generator.set("wrapper_class", interface.wrapper_class);
  965. generator.set("constructor_class", interface.constructor_class);
  966. generator.set("prototype_class:snakecase", snake_name(interface.prototype_class));
  967. generator.set("fully_qualified_name", interface.fully_qualified_name);
  968. generator.append(R"~~~(
  969. #include <AK/Function.h>
  970. #include <LibJS/Runtime/Error.h>
  971. #include <LibJS/Runtime/GlobalObject.h>
  972. #include <LibWeb/Bindings/@prototype_class@.h>
  973. #if __has_include(<LibWeb/DOM/@name@.h>)
  974. # include <LibWeb/DOM/@name@.h>
  975. #elif __has_include(<LibWeb/HTML/@name@.h>)
  976. # include <LibWeb/HTML/@name@.h>
  977. #elif __has_include(<LibWeb/UIEvents/@name@.h>)
  978. # include <LibWeb/UIEvents/@name@.h>
  979. #elif __has_include(<LibWeb/HighResolutionTime/@name@.h>)
  980. # include <LibWeb/HighResolutionTime/@name@.h>
  981. #elif __has_include(<LibWeb/SVG/@name@.h>)
  982. # include <LibWeb/SVG/@name@.h>
  983. #endif
  984. // FIXME: This is a total hack until we can figure out the namespace for a given type somehow.
  985. using namespace Web::DOM;
  986. using namespace Web::HTML;
  987. namespace Web::Bindings {
  988. @prototype_class@::@prototype_class@(JS::GlobalObject& global_object)
  989. : Object(*global_object.object_prototype())
  990. {
  991. }
  992. @prototype_class@::~@prototype_class@()
  993. {
  994. }
  995. void @prototype_class@::initialize(JS::GlobalObject& global_object)
  996. {
  997. [[maybe_unused]] auto& vm = this->vm();
  998. Object::initialize(global_object);
  999. }
  1000. } // namespace Web::Bindings
  1001. )~~~");
  1002. outln("{}", generator.as_string_view());
  1003. }