GenerateWindowOrWorkerInterfaces.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DeprecatedString.h>
  7. #include <AK/LexicalPath.h>
  8. #include <AK/SourceGenerator.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/File.h>
  12. #include <LibIDL/IDLParser.h>
  13. #include <LibIDL/Types.h>
  14. #include <LibMain/Main.h>
  15. static ErrorOr<void> add_to_interface_sets(IDL::Interface&, Vector<IDL::Interface&>& intrinsics, Vector<IDL::Interface&>& window_exposed, Vector<IDL::Interface&>& dedicated_worker_exposed, Vector<IDL::Interface&>& shared_worker_exposed);
  16. static DeprecatedString s_error_string;
  17. struct LegacyConstructor {
  18. DeprecatedString name;
  19. DeprecatedString constructor_class;
  20. };
  21. static void consume_whitespace(GenericLexer& lexer)
  22. {
  23. bool consumed = true;
  24. while (consumed) {
  25. consumed = lexer.consume_while(is_ascii_space).length() > 0;
  26. if (lexer.consume_specific("//")) {
  27. lexer.consume_until('\n');
  28. lexer.ignore();
  29. consumed = true;
  30. }
  31. }
  32. }
  33. static Optional<LegacyConstructor> const& lookup_legacy_constructor(IDL::Interface& interface)
  34. {
  35. static HashMap<StringView, Optional<LegacyConstructor>> s_legacy_constructors;
  36. if (auto cache = s_legacy_constructors.get(interface.name); cache.has_value())
  37. return cache.value();
  38. auto attribute = interface.extended_attributes.get("LegacyFactoryFunction"sv);
  39. if (!attribute.has_value()) {
  40. s_legacy_constructors.set(interface.name, {});
  41. return s_legacy_constructors.get(interface.name).value();
  42. }
  43. GenericLexer function_lexer(attribute.value());
  44. consume_whitespace(function_lexer);
  45. auto name = function_lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == '('; });
  46. auto constructor_class = DeprecatedString::formatted("{}Constructor", name);
  47. s_legacy_constructors.set(interface.name, LegacyConstructor { name, move(constructor_class) });
  48. return s_legacy_constructors.get(interface.name).value();
  49. }
  50. static ErrorOr<void> generate_forwarding_header(StringView output_path, Vector<IDL::Interface&>& exposed_interfaces)
  51. {
  52. StringBuilder builder;
  53. SourceGenerator generator(builder);
  54. generator.append(R"~~~(
  55. #pragma once
  56. namespace Web::Bindings {
  57. )~~~");
  58. auto add_interface = [](SourceGenerator& gen, StringView prototype_class, StringView constructor_class, Optional<LegacyConstructor> const& legacy_constructor) {
  59. gen.set("prototype_class", prototype_class);
  60. gen.set("constructor_class", constructor_class);
  61. gen.append(R"~~~(
  62. class @prototype_class@;
  63. class @constructor_class@;)~~~");
  64. if (legacy_constructor.has_value()) {
  65. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  66. gen.append(R"~~~(
  67. class @legacy_constructor_class@;)~~~");
  68. }
  69. };
  70. for (auto& interface : exposed_interfaces) {
  71. auto gen = generator.fork();
  72. add_interface(gen, interface.prototype_class, interface.constructor_class, lookup_legacy_constructor(interface));
  73. }
  74. // FIXME: Special case WebAssembly. We should convert WASM to use IDL.
  75. {
  76. auto gen = generator.fork();
  77. add_interface(gen, "WebAssemblyMemoryPrototype"sv, "WebAssemblyMemoryConstructor"sv, {});
  78. add_interface(gen, "WebAssemblyInstancePrototype"sv, "WebAssemblyInstanceConstructor"sv, {});
  79. add_interface(gen, "WebAssemblyModulePrototype"sv, "WebAssemblyModuleConstructor"sv, {});
  80. add_interface(gen, "WebAssemblyTablePrototype"sv, "WebAssemblyTableConstructor"sv, {});
  81. }
  82. generator.append(R"~~~(
  83. }
  84. )~~~");
  85. auto generated_forward_path = LexicalPath(output_path).append("Forward.h"sv).string();
  86. auto generated_forward_file = TRY(Core::File::open(generated_forward_path, Core::File::OpenMode::Write));
  87. // FIXME: This should write the entire span.
  88. TRY(generated_forward_file->write_some(generator.as_string_view().bytes()));
  89. return {};
  90. }
  91. static ErrorOr<void> generate_intrinsic_definitions(StringView output_path, Vector<IDL::Interface&>& exposed_interfaces)
  92. {
  93. StringBuilder builder;
  94. SourceGenerator generator(builder);
  95. generator.append(R"~~~(
  96. #include <LibJS/Heap/DeferGC.h>
  97. #include <LibJS/Runtime/Object.h>
  98. #include <LibWeb/Bindings/Intrinsics.h>)~~~");
  99. for (auto& interface : exposed_interfaces) {
  100. auto gen = generator.fork();
  101. gen.set("prototype_class", interface.prototype_class);
  102. gen.set("constructor_class", interface.constructor_class);
  103. gen.append(R"~~~(
  104. #include <LibWeb/Bindings/@constructor_class@.h>
  105. #include <LibWeb/Bindings/@prototype_class@.h>)~~~");
  106. if (auto const& legacy_constructor = lookup_legacy_constructor(interface); legacy_constructor.has_value()) {
  107. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  108. gen.append(R"~~~(
  109. #include <LibWeb/Bindings/@legacy_constructor_class@.h>)~~~");
  110. }
  111. }
  112. // FIXME: Special case WebAssembly. We should convert WASM to use IDL.
  113. generator.append(R"~~~(
  114. #include <LibWeb/WebAssembly/WebAssemblyMemoryConstructor.h>
  115. #include <LibWeb/WebAssembly/WebAssemblyMemoryPrototype.h>
  116. #include <LibWeb/WebAssembly/WebAssemblyInstanceConstructor.h>
  117. #include <LibWeb/WebAssembly/WebAssemblyInstanceObjectPrototype.h>
  118. #include <LibWeb/WebAssembly/WebAssemblyModuleConstructor.h>
  119. #include <LibWeb/WebAssembly/WebAssemblyModulePrototype.h>
  120. #include <LibWeb/WebAssembly/WebAssemblyTableConstructor.h>
  121. #include <LibWeb/WebAssembly/WebAssemblyTablePrototype.h>)~~~");
  122. generator.append(R"~~~(
  123. namespace Web::Bindings {
  124. )~~~");
  125. auto add_interface = [&](SourceGenerator& gen, StringView name, StringView prototype_class, StringView constructor_class, Optional<LegacyConstructor> const& legacy_constructor) {
  126. gen.set("interface_name", name);
  127. gen.set("prototype_class", prototype_class);
  128. gen.set("constructor_class", constructor_class);
  129. gen.append(R"~~~(
  130. template<>
  131. void Intrinsics::create_web_prototype_and_constructor<@prototype_class@>(JS::Realm& realm)
  132. {
  133. auto& vm = realm.vm();
  134. auto prototype = heap().allocate<@prototype_class@>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors();
  135. m_prototypes.set("@interface_name@"sv, prototype);
  136. auto constructor = heap().allocate<@constructor_class@>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors();
  137. m_constructors.set("@interface_name@"sv, constructor);
  138. prototype->define_direct_property(vm.names.constructor, constructor.ptr(), JS::Attribute::Writable | JS::Attribute::Configurable);
  139. constructor->define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "@interface_name@"sv).release_allocated_value_but_fixme_should_propagate_errors(), JS::Attribute::Configurable);
  140. )~~~");
  141. if (legacy_constructor.has_value()) {
  142. gen.set("legacy_interface_name", legacy_constructor->name);
  143. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  144. gen.append(R"~~~(
  145. auto legacy_constructor = heap().allocate<@legacy_constructor_class@>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors();
  146. m_constructors.set("@legacy_interface_name@"sv, legacy_constructor);
  147. legacy_constructor->define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "@legacy_interface_name@"sv).release_allocated_value_but_fixme_should_propagate_errors(), JS::Attribute::Configurable);)~~~");
  148. }
  149. gen.append(R"~~~(
  150. }
  151. )~~~");
  152. };
  153. for (auto& interface : exposed_interfaces) {
  154. auto gen = generator.fork();
  155. add_interface(gen, interface.name, interface.prototype_class, interface.constructor_class, lookup_legacy_constructor(interface));
  156. }
  157. // FIXME: Special case WebAssembly. We should convert WASM to use IDL.
  158. {
  159. auto gen = generator.fork();
  160. add_interface(gen, "WebAssembly.Memory"sv, "WebAssemblyMemoryPrototype"sv, "WebAssemblyMemoryConstructor"sv, {});
  161. add_interface(gen, "WebAssembly.Instance"sv, "WebAssemblyInstancePrototype"sv, "WebAssemblyInstanceConstructor"sv, {});
  162. add_interface(gen, "WebAssembly.Module"sv, "WebAssemblyModulePrototype"sv, "WebAssemblyModuleConstructor"sv, {});
  163. add_interface(gen, "WebAssembly.Table"sv, "WebAssemblyTablePrototype"sv, "WebAssemblyTableConstructor"sv, {});
  164. }
  165. generator.append(R"~~~(
  166. }
  167. )~~~");
  168. auto generated_intrinsics_path = LexicalPath(output_path).append("IntrinsicDefinitions.cpp"sv).string();
  169. auto generated_intrinsics_file = TRY(Core::File::open(generated_intrinsics_path, Core::File::OpenMode::Write));
  170. // FIXME: This should write the entire span.
  171. TRY(generated_intrinsics_file->write_some(generator.as_string_view().bytes()));
  172. return {};
  173. }
  174. static ErrorOr<void> generate_exposed_interface_header(StringView class_name, StringView output_path)
  175. {
  176. StringBuilder builder;
  177. SourceGenerator generator(builder);
  178. generator.set("global_object_snake_name", DeprecatedString(class_name).to_snakecase());
  179. generator.append(R"~~~(
  180. #pragma once
  181. #include <LibJS/Forward.h>
  182. namespace Web::Bindings {
  183. void add_@global_object_snake_name@_exposed_interfaces(JS::Object&);
  184. }
  185. )~~~");
  186. auto generated_header_path = LexicalPath(output_path).append(DeprecatedString::formatted("{}ExposedInterfaces.h", class_name)).string();
  187. auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
  188. // FIXME: This should write the entire span.
  189. TRY(generated_header_file->write_some(generator.as_string_view().bytes()));
  190. return {};
  191. }
  192. static ErrorOr<void> generate_exposed_interface_implementation(StringView class_name, StringView output_path, Vector<IDL::Interface&>& exposed_interfaces)
  193. {
  194. StringBuilder builder;
  195. SourceGenerator generator(builder);
  196. generator.set("global_object_name", class_name);
  197. generator.set("global_object_snake_name", DeprecatedString(class_name).to_snakecase());
  198. generator.append(R"~~~(
  199. #include <LibJS/Runtime/Object.h>
  200. #include <LibWeb/Bindings/Intrinsics.h>
  201. #include <LibWeb/Bindings/@global_object_name@ExposedInterfaces.h>
  202. )~~~");
  203. for (auto& interface : exposed_interfaces) {
  204. auto gen = generator.fork();
  205. gen.set("prototype_class", interface.prototype_class);
  206. gen.set("constructor_class", interface.constructor_class);
  207. gen.append(R"~~~(#include <LibWeb/Bindings/@constructor_class@.h>
  208. #include <LibWeb/Bindings/@prototype_class@.h>
  209. )~~~");
  210. if (auto const& legacy_constructor = lookup_legacy_constructor(interface); legacy_constructor.has_value()) {
  211. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  212. gen.append(R"~~~(#include <LibWeb/Bindings/@legacy_constructor_class@.h>
  213. )~~~");
  214. }
  215. }
  216. generator.append(R"~~~(
  217. namespace Web::Bindings {
  218. void add_@global_object_snake_name@_exposed_interfaces(JS::Object& global)
  219. {
  220. static constexpr u8 attr = JS::Attribute::Writable | JS::Attribute::Configurable;
  221. )~~~");
  222. auto add_interface = [](SourceGenerator& gen, StringView name, StringView prototype_class, Optional<LegacyConstructor> const& legacy_constructor) {
  223. gen.set("interface_name", name);
  224. gen.set("prototype_class", prototype_class);
  225. gen.append(R"~~~(
  226. global.define_intrinsic_accessor("@interface_name@", attr, [](auto& realm) -> JS::Value { return &ensure_web_constructor<@prototype_class@>(realm, "@interface_name@"sv); });)~~~");
  227. if (legacy_constructor.has_value()) {
  228. gen.set("legacy_interface_name", legacy_constructor->name);
  229. gen.append(R"~~~(
  230. global.define_intrinsic_accessor("@legacy_interface_name@", attr, [](auto& realm) -> JS::Value { return &ensure_web_constructor<@prototype_class@>(realm, "@legacy_interface_name@"sv); });)~~~");
  231. }
  232. };
  233. for (auto& interface : exposed_interfaces) {
  234. auto gen = generator.fork();
  235. add_interface(gen, interface.name, interface.prototype_class, lookup_legacy_constructor(interface));
  236. }
  237. generator.append(R"~~~(
  238. }
  239. }
  240. )~~~");
  241. auto generated_implementation_path = LexicalPath(output_path).append(DeprecatedString::formatted("{}ExposedInterfaces.cpp", class_name)).string();
  242. auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
  243. // FIXME: This should write the entire span.
  244. TRY(generated_implementation_file->write_some(generator.as_string_view().bytes()));
  245. return {};
  246. }
  247. ErrorOr<int> serenity_main(Main::Arguments arguments)
  248. {
  249. Core::ArgsParser args_parser;
  250. StringView output_path;
  251. StringView base_path;
  252. Vector<DeprecatedString> paths;
  253. args_parser.add_option(output_path, "Path to output generated files into", "output-path", 'o', "output-path");
  254. args_parser.add_option(base_path, "Path to root of IDL file tree", "base-path", 'b', "base-path");
  255. args_parser.add_positional_argument(paths, "Paths of every IDL file that could be Exposed", "paths");
  256. args_parser.parse(arguments);
  257. VERIFY(!paths.is_empty());
  258. VERIFY(!base_path.is_empty());
  259. const LexicalPath lexical_base(base_path);
  260. // Read in all IDL files, we must own the storage for all of these for the lifetime of the program
  261. Vector<DeprecatedString> file_contents;
  262. for (DeprecatedString const& path : paths) {
  263. auto file_or_error = Core::File::open(path, Core::File::OpenMode::Read);
  264. if (file_or_error.is_error()) {
  265. s_error_string = DeprecatedString::formatted("Unable to open file {}", path);
  266. return Error::from_string_view(s_error_string);
  267. }
  268. auto file = file_or_error.release_value();
  269. auto string = MUST(file->read_until_eof());
  270. file_contents.append(DeprecatedString(ReadonlyBytes(string)));
  271. }
  272. VERIFY(paths.size() == file_contents.size());
  273. Vector<IDL::Parser> parsers;
  274. Vector<IDL::Interface&> intrinsics;
  275. Vector<IDL::Interface&> window_exposed;
  276. Vector<IDL::Interface&> dedicated_worker_exposed;
  277. Vector<IDL::Interface&> shared_worker_exposed;
  278. // TODO: service_worker_exposed
  279. for (size_t i = 0; i < paths.size(); ++i) {
  280. IDL::Parser parser(paths[i], file_contents[i], lexical_base.string());
  281. TRY(add_to_interface_sets(parser.parse(), intrinsics, window_exposed, dedicated_worker_exposed, shared_worker_exposed));
  282. parsers.append(move(parser));
  283. }
  284. TRY(generate_forwarding_header(output_path, intrinsics));
  285. TRY(generate_intrinsic_definitions(output_path, intrinsics));
  286. TRY(generate_exposed_interface_header("Window"sv, output_path));
  287. TRY(generate_exposed_interface_header("DedicatedWorker"sv, output_path));
  288. TRY(generate_exposed_interface_header("SharedWorker"sv, output_path));
  289. // TODO: ServiceWorkerExposed.h
  290. TRY(generate_exposed_interface_implementation("Window"sv, output_path, window_exposed));
  291. TRY(generate_exposed_interface_implementation("DedicatedWorker"sv, output_path, dedicated_worker_exposed));
  292. TRY(generate_exposed_interface_implementation("SharedWorker"sv, output_path, shared_worker_exposed));
  293. // TODO: ServiceWorkerExposed.cpp
  294. return 0;
  295. }
  296. enum ExposedTo {
  297. Nobody = 0x0,
  298. DedicatedWorker = 0x1,
  299. SharedWorker = 0x2,
  300. ServiceWorker = 0x4,
  301. AudioWorklet = 0x8,
  302. Window = 0x10,
  303. AllWorkers = 0xF, // FIXME: Is "AudioWorklet" a Worker? We'll assume it is for now
  304. All = 0x1F,
  305. };
  306. AK_ENUM_BITWISE_OPERATORS(ExposedTo);
  307. static ErrorOr<ExposedTo> parse_exposure_set(IDL::Interface& interface)
  308. {
  309. // NOTE: This roughly follows the definitions of https://webidl.spec.whatwg.org/#Exposed
  310. // It does not remotely interpret all the abstract operations therein though.
  311. auto maybe_exposed = interface.extended_attributes.get("Exposed");
  312. if (!maybe_exposed.has_value()) {
  313. s_error_string = DeprecatedString::formatted("Interface {} is missing extended attribute Exposed", interface.name);
  314. return Error::from_string_view(s_error_string);
  315. }
  316. auto exposed = maybe_exposed.value().trim_whitespace();
  317. if (exposed == "*"sv)
  318. return ExposedTo::All;
  319. if (exposed == "Window"sv)
  320. return ExposedTo::Window;
  321. if (exposed == "Worker"sv)
  322. return ExposedTo::AllWorkers;
  323. if (exposed == "AudioWorklet"sv)
  324. return ExposedTo::AudioWorklet;
  325. if (exposed[0] == '(') {
  326. ExposedTo whom = Nobody;
  327. for (StringView candidate : exposed.substring_view(1, exposed.length() - 1).split_view(',')) {
  328. candidate = candidate.trim_whitespace();
  329. if (candidate == "Window"sv) {
  330. whom |= ExposedTo::Window;
  331. } else if (candidate == "Worker"sv) {
  332. whom |= ExposedTo::AllWorkers;
  333. } else if (candidate == "DedicatedWorker"sv) {
  334. whom |= ExposedTo::DedicatedWorker;
  335. } else if (candidate == "SharedWorker"sv) {
  336. whom |= ExposedTo::SharedWorker;
  337. } else if (candidate == "ServiceWorker"sv) {
  338. whom |= ExposedTo::ServiceWorker;
  339. } else if (candidate == "AudioWorklet"sv) {
  340. whom |= ExposedTo::AudioWorklet;
  341. } else {
  342. s_error_string = DeprecatedString::formatted("Unknown Exposed attribute candidate {} in {} in {}", candidate, exposed, interface.name);
  343. return Error::from_string_view(s_error_string);
  344. }
  345. }
  346. if (whom == ExposedTo::Nobody) {
  347. s_error_string = DeprecatedString::formatted("Unknown Exposed attribute {} in {}", exposed, interface.name);
  348. return Error::from_string_view(s_error_string);
  349. }
  350. return whom;
  351. }
  352. s_error_string = DeprecatedString::formatted("Unknown Exposed attribute {} in {}", exposed, interface.name);
  353. return Error::from_string_view(s_error_string);
  354. }
  355. ErrorOr<void> add_to_interface_sets(IDL::Interface& interface, Vector<IDL::Interface&>& intrinsics, Vector<IDL::Interface&>& window_exposed, Vector<IDL::Interface&>& dedicated_worker_exposed, Vector<IDL::Interface&>& shared_worker_exposed)
  356. {
  357. // TODO: Add service worker exposed and audio worklet exposed
  358. auto whom = TRY(parse_exposure_set(interface));
  359. VERIFY(whom != ExposedTo::Nobody);
  360. if ((whom & ExposedTo::Window) || (whom & ExposedTo::DedicatedWorker) || (whom & ExposedTo::SharedWorker))
  361. intrinsics.append(interface);
  362. if (whom & ExposedTo::Window)
  363. window_exposed.append(interface);
  364. if (whom & ExposedTo::DedicatedWorker)
  365. dedicated_worker_exposed.append(interface);
  366. if (whom & ExposedTo::SharedWorker)
  367. shared_worker_exposed.append(interface);
  368. return {};
  369. }