GenerateWindowOrWorkerInterfaces.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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_namespace = [](SourceGenerator& gen, StringView namespace_class) {
  59. gen.set("namespace_class", namespace_class);
  60. gen.append(R"~~~(
  61. class @namespace_class@;)~~~");
  62. };
  63. auto add_interface = [](SourceGenerator& gen, StringView prototype_class, StringView constructor_class, Optional<LegacyConstructor> const& legacy_constructor, StringView named_properties_class) {
  64. gen.set("prototype_class", prototype_class);
  65. gen.set("constructor_class", constructor_class);
  66. gen.append(R"~~~(
  67. class @prototype_class@;
  68. class @constructor_class@;)~~~");
  69. if (legacy_constructor.has_value()) {
  70. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  71. gen.append(R"~~~(
  72. class @legacy_constructor_class@;)~~~");
  73. }
  74. if (!named_properties_class.is_empty()) {
  75. gen.set("named_properties_class", named_properties_class);
  76. gen.append(R"~~~(
  77. class @named_properties_class@;)~~~");
  78. }
  79. };
  80. for (auto& interface : exposed_interfaces) {
  81. auto gen = generator.fork();
  82. String named_properties_class;
  83. if (interface.extended_attributes.contains("Global") && interface.supports_named_properties()) {
  84. named_properties_class = MUST(String::formatted("{}Properties", interface.name));
  85. }
  86. if (interface.is_namespace)
  87. add_namespace(gen, interface.namespace_class);
  88. else
  89. add_interface(gen, interface.prototype_class, interface.constructor_class, lookup_legacy_constructor(interface), named_properties_class);
  90. }
  91. generator.append(R"~~~(
  92. }
  93. )~~~");
  94. auto generated_forward_path = LexicalPath(output_path).append("Forward.h"sv).string();
  95. auto generated_forward_file = TRY(Core::File::open(generated_forward_path, Core::File::OpenMode::Write));
  96. TRY(generated_forward_file->write_until_depleted(generator.as_string_view().bytes()));
  97. return {};
  98. }
  99. static ErrorOr<void> generate_intrinsic_definitions(StringView output_path, Vector<IDL::Interface&>& exposed_interfaces)
  100. {
  101. StringBuilder builder;
  102. SourceGenerator generator(builder);
  103. generator.append(R"~~~(
  104. #include <LibJS/Heap/DeferGC.h>
  105. #include <LibJS/Runtime/Object.h>
  106. #include <LibWeb/Bindings/Intrinsics.h>)~~~");
  107. for (auto& interface : exposed_interfaces) {
  108. auto gen = generator.fork();
  109. gen.set("namespace_class", interface.namespace_class);
  110. gen.set("prototype_class", interface.prototype_class);
  111. gen.set("constructor_class", interface.constructor_class);
  112. if (interface.is_namespace) {
  113. gen.append(R"~~~(
  114. #include <LibWeb/Bindings/@namespace_class@.h>)~~~");
  115. } else {
  116. gen.append(R"~~~(
  117. #include <LibWeb/Bindings/@constructor_class@.h>
  118. #include <LibWeb/Bindings/@prototype_class@.h>)~~~");
  119. if (auto const& legacy_constructor = lookup_legacy_constructor(interface); legacy_constructor.has_value()) {
  120. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  121. gen.append(R"~~~(
  122. #include <LibWeb/Bindings/@legacy_constructor_class@.h>)~~~");
  123. }
  124. }
  125. }
  126. generator.append(R"~~~(
  127. namespace Web::Bindings {
  128. )~~~");
  129. auto add_namespace = [&](SourceGenerator& gen, StringView name, StringView namespace_class) {
  130. gen.set("interface_name", name);
  131. gen.set("namespace_class", namespace_class);
  132. gen.append(R"~~~(
  133. template<>
  134. void Intrinsics::create_web_namespace<@namespace_class@>(JS::Realm& realm)
  135. {
  136. auto namespace_object = heap().allocate<@namespace_class@>(realm, realm);
  137. m_namespaces.set("@interface_name@"sv, namespace_object);
  138. [[maybe_unused]] static constexpr u8 attr = JS::Attribute::Writable | JS::Attribute::Configurable;)~~~");
  139. for (auto& interface : exposed_interfaces) {
  140. if (interface.extended_attributes.get("LegacyNamespace"sv) != name)
  141. continue;
  142. gen.set("owned_interface_name", interface.name);
  143. gen.set("owned_prototype_class", interface.prototype_class);
  144. gen.append(R"~~~(
  145. namespace_object->define_intrinsic_accessor("@owned_interface_name@", attr, [](auto& realm) -> JS::Value { return &Bindings::ensure_web_constructor<@owned_prototype_class@>(realm, "@interface_name@.@owned_interface_name@"sv); });)~~~");
  146. }
  147. gen.append(R"~~~(
  148. }
  149. )~~~");
  150. };
  151. auto add_interface = [](SourceGenerator& gen, StringView name, StringView prototype_class, StringView constructor_class, Optional<LegacyConstructor> const& legacy_constructor, StringView named_properties_class) {
  152. gen.set("interface_name", name);
  153. gen.set("prototype_class", prototype_class);
  154. gen.set("constructor_class", constructor_class);
  155. gen.append(R"~~~(
  156. template<>
  157. void Intrinsics::create_web_prototype_and_constructor<@prototype_class@>(JS::Realm& realm)
  158. {
  159. auto& vm = realm.vm();
  160. )~~~");
  161. if (!named_properties_class.is_empty()) {
  162. gen.set("named_properties_class", named_properties_class);
  163. gen.append(R"~~~(
  164. auto named_properties_object = heap().allocate<@named_properties_class@>(realm, realm);
  165. m_prototypes.set("@named_properties_class@"sv, named_properties_object);
  166. )~~~");
  167. }
  168. gen.append(R"~~~(
  169. auto prototype = heap().allocate<@prototype_class@>(realm, realm);
  170. m_prototypes.set("@interface_name@"sv, prototype);
  171. auto constructor = heap().allocate<@constructor_class@>(realm, realm);
  172. m_constructors.set("@interface_name@"sv, constructor);
  173. prototype->define_direct_property(vm.names.constructor, constructor.ptr(), JS::Attribute::Writable | JS::Attribute::Configurable);
  174. constructor->define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "@interface_name@"_string), JS::Attribute::Configurable);
  175. )~~~");
  176. if (legacy_constructor.has_value()) {
  177. gen.set("legacy_interface_name", legacy_constructor->name);
  178. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  179. gen.append(R"~~~(
  180. auto legacy_constructor = heap().allocate<@legacy_constructor_class@>(realm, realm);
  181. m_constructors.set("@legacy_interface_name@"sv, legacy_constructor);
  182. legacy_constructor->define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "@legacy_interface_name@"_string), JS::Attribute::Configurable);)~~~");
  183. }
  184. gen.append(R"~~~(
  185. }
  186. )~~~");
  187. };
  188. for (auto& interface : exposed_interfaces) {
  189. auto gen = generator.fork();
  190. String named_properties_class;
  191. if (interface.extended_attributes.contains("Global") && interface.supports_named_properties()) {
  192. named_properties_class = MUST(String::formatted("{}Properties", interface.name));
  193. }
  194. if (interface.is_namespace)
  195. add_namespace(gen, interface.name, interface.namespace_class);
  196. else
  197. add_interface(gen, interface.namespaced_name, interface.prototype_class, interface.constructor_class, lookup_legacy_constructor(interface), named_properties_class);
  198. }
  199. generator.append(R"~~~(
  200. }
  201. )~~~");
  202. auto generated_intrinsics_path = LexicalPath(output_path).append("IntrinsicDefinitions.cpp"sv).string();
  203. auto generated_intrinsics_file = TRY(Core::File::open(generated_intrinsics_path, Core::File::OpenMode::Write));
  204. TRY(generated_intrinsics_file->write_until_depleted(generator.as_string_view().bytes()));
  205. return {};
  206. }
  207. static ErrorOr<void> generate_exposed_interface_header(StringView class_name, StringView output_path)
  208. {
  209. StringBuilder builder;
  210. SourceGenerator generator(builder);
  211. generator.set("global_object_snake_name", DeprecatedString(class_name).to_snakecase());
  212. generator.append(R"~~~(
  213. #pragma once
  214. #include <LibJS/Forward.h>
  215. namespace Web::Bindings {
  216. void add_@global_object_snake_name@_exposed_interfaces(JS::Object&);
  217. }
  218. )~~~");
  219. auto generated_header_path = LexicalPath(output_path).append(DeprecatedString::formatted("{}ExposedInterfaces.h", class_name)).string();
  220. auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
  221. TRY(generated_header_file->write_until_depleted(generator.as_string_view().bytes()));
  222. return {};
  223. }
  224. static ErrorOr<void> generate_exposed_interface_implementation(StringView class_name, StringView output_path, Vector<IDL::Interface&>& exposed_interfaces)
  225. {
  226. StringBuilder builder;
  227. SourceGenerator generator(builder);
  228. generator.set("global_object_name", class_name);
  229. generator.set("global_object_snake_name", DeprecatedString(class_name).to_snakecase());
  230. generator.append(R"~~~(
  231. #include <LibJS/Runtime/Object.h>
  232. #include <LibWeb/Bindings/Intrinsics.h>
  233. #include <LibWeb/Bindings/@global_object_name@ExposedInterfaces.h>
  234. )~~~");
  235. for (auto& interface : exposed_interfaces) {
  236. auto gen = generator.fork();
  237. gen.set("namespace_class", interface.namespace_class);
  238. gen.set("prototype_class", interface.prototype_class);
  239. gen.set("constructor_class", interface.constructor_class);
  240. if (interface.is_namespace) {
  241. gen.append(R"~~~(#include <LibWeb/Bindings/@namespace_class@.h>
  242. )~~~");
  243. } else {
  244. gen.append(R"~~~(#include <LibWeb/Bindings/@constructor_class@.h>
  245. #include <LibWeb/Bindings/@prototype_class@.h>
  246. )~~~");
  247. if (auto const& legacy_constructor = lookup_legacy_constructor(interface); legacy_constructor.has_value()) {
  248. gen.set("legacy_constructor_class", legacy_constructor->constructor_class);
  249. gen.append(R"~~~(#include <LibWeb/Bindings/@legacy_constructor_class@.h>
  250. )~~~");
  251. }
  252. }
  253. }
  254. generator.append(R"~~~(
  255. namespace Web::Bindings {
  256. void add_@global_object_snake_name@_exposed_interfaces(JS::Object& global)
  257. {
  258. static constexpr u8 attr = JS::Attribute::Writable | JS::Attribute::Configurable;
  259. )~~~");
  260. auto add_interface = [](SourceGenerator& gen, StringView name, StringView prototype_class, Optional<LegacyConstructor> const& legacy_constructor) {
  261. gen.set("interface_name", name);
  262. gen.set("prototype_class", prototype_class);
  263. gen.append(R"~~~(
  264. global.define_intrinsic_accessor("@interface_name@", attr, [](auto& realm) -> JS::Value { return &ensure_web_constructor<@prototype_class@>(realm, "@interface_name@"sv); });)~~~");
  265. if (legacy_constructor.has_value()) {
  266. gen.set("legacy_interface_name", legacy_constructor->name);
  267. gen.append(R"~~~(
  268. global.define_intrinsic_accessor("@legacy_interface_name@", attr, [](auto& realm) -> JS::Value { return &ensure_web_constructor<@prototype_class@>(realm, "@legacy_interface_name@"sv); });)~~~");
  269. }
  270. };
  271. auto add_namespace = [](SourceGenerator& gen, StringView name, StringView namespace_class) {
  272. gen.set("interface_name", name);
  273. gen.set("namespace_class", namespace_class);
  274. gen.append(R"~~~(
  275. global.define_intrinsic_accessor("@interface_name@", attr, [](auto& realm) -> JS::Value { return &ensure_web_namespace<@namespace_class@>(realm, "@interface_name@"sv); });)~~~");
  276. };
  277. for (auto& interface : exposed_interfaces) {
  278. auto gen = generator.fork();
  279. if (interface.is_namespace)
  280. add_namespace(gen, interface.name, interface.namespace_class);
  281. else if (!interface.extended_attributes.contains("LegacyNamespace"sv))
  282. add_interface(gen, interface.namespaced_name, interface.prototype_class, lookup_legacy_constructor(interface));
  283. }
  284. generator.append(R"~~~(
  285. }
  286. }
  287. )~~~");
  288. auto generated_implementation_path = LexicalPath(output_path).append(DeprecatedString::formatted("{}ExposedInterfaces.cpp", class_name)).string();
  289. auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
  290. TRY(generated_implementation_file->write_until_depleted(generator.as_string_view().bytes()));
  291. return {};
  292. }
  293. ErrorOr<int> serenity_main(Main::Arguments arguments)
  294. {
  295. Core::ArgsParser args_parser;
  296. StringView output_path;
  297. StringView base_path;
  298. Vector<DeprecatedString> paths;
  299. args_parser.add_option(output_path, "Path to output generated files into", "output-path", 'o', "output-path");
  300. args_parser.add_option(base_path, "Path to root of IDL file tree", "base-path", 'b', "base-path");
  301. args_parser.add_positional_argument(paths, "Paths of every IDL file that could be Exposed", "paths");
  302. args_parser.parse(arguments);
  303. VERIFY(!paths.is_empty());
  304. VERIFY(!base_path.is_empty());
  305. const LexicalPath lexical_base(base_path);
  306. // Read in all IDL files, we must own the storage for all of these for the lifetime of the program
  307. Vector<DeprecatedString> file_contents;
  308. for (DeprecatedString const& path : paths) {
  309. auto file_or_error = Core::File::open(path, Core::File::OpenMode::Read);
  310. if (file_or_error.is_error()) {
  311. s_error_string = DeprecatedString::formatted("Unable to open file {}", path);
  312. return Error::from_string_view(s_error_string.view());
  313. }
  314. auto file = file_or_error.release_value();
  315. auto string = MUST(file->read_until_eof());
  316. file_contents.append(DeprecatedString(ReadonlyBytes(string)));
  317. }
  318. VERIFY(paths.size() == file_contents.size());
  319. Vector<IDL::Parser> parsers;
  320. Vector<IDL::Interface&> intrinsics;
  321. Vector<IDL::Interface&> window_exposed;
  322. Vector<IDL::Interface&> dedicated_worker_exposed;
  323. Vector<IDL::Interface&> shared_worker_exposed;
  324. // TODO: service_worker_exposed
  325. for (size_t i = 0; i < paths.size(); ++i) {
  326. IDL::Parser parser(paths[i], file_contents[i], lexical_base.string());
  327. TRY(add_to_interface_sets(parser.parse(), intrinsics, window_exposed, dedicated_worker_exposed, shared_worker_exposed));
  328. parsers.append(move(parser));
  329. }
  330. TRY(generate_forwarding_header(output_path, intrinsics));
  331. TRY(generate_intrinsic_definitions(output_path, intrinsics));
  332. TRY(generate_exposed_interface_header("Window"sv, output_path));
  333. TRY(generate_exposed_interface_header("DedicatedWorker"sv, output_path));
  334. TRY(generate_exposed_interface_header("SharedWorker"sv, output_path));
  335. // TODO: ServiceWorkerExposed.h
  336. TRY(generate_exposed_interface_implementation("Window"sv, output_path, window_exposed));
  337. TRY(generate_exposed_interface_implementation("DedicatedWorker"sv, output_path, dedicated_worker_exposed));
  338. TRY(generate_exposed_interface_implementation("SharedWorker"sv, output_path, shared_worker_exposed));
  339. // TODO: ServiceWorkerExposed.cpp
  340. return 0;
  341. }
  342. enum ExposedTo {
  343. Nobody = 0x0,
  344. DedicatedWorker = 0x1,
  345. SharedWorker = 0x2,
  346. ServiceWorker = 0x4,
  347. AudioWorklet = 0x8,
  348. Window = 0x10,
  349. AllWorkers = 0xF, // FIXME: Is "AudioWorklet" a Worker? We'll assume it is for now
  350. All = 0x1F,
  351. };
  352. AK_ENUM_BITWISE_OPERATORS(ExposedTo);
  353. static ErrorOr<ExposedTo> parse_exposure_set(IDL::Interface& interface)
  354. {
  355. // NOTE: This roughly follows the definitions of https://webidl.spec.whatwg.org/#Exposed
  356. // It does not remotely interpret all the abstract operations therein though.
  357. auto maybe_exposed = interface.extended_attributes.get("Exposed");
  358. if (!maybe_exposed.has_value()) {
  359. s_error_string = DeprecatedString::formatted("Interface {} is missing extended attribute Exposed", interface.name);
  360. return Error::from_string_view(s_error_string.view());
  361. }
  362. auto exposed = maybe_exposed.value().trim_whitespace();
  363. if (exposed == "*"sv)
  364. return ExposedTo::All;
  365. if (exposed == "Nobody"sv)
  366. return ExposedTo::Nobody;
  367. if (exposed == "Window"sv)
  368. return ExposedTo::Window;
  369. if (exposed == "Worker"sv)
  370. return ExposedTo::AllWorkers;
  371. if (exposed == "AudioWorklet"sv)
  372. return ExposedTo::AudioWorklet;
  373. if (exposed[0] == '(') {
  374. ExposedTo whom = Nobody;
  375. for (StringView candidate : exposed.substring_view(1, exposed.length() - 1).split_view(',')) {
  376. candidate = candidate.trim_whitespace();
  377. if (candidate == "Window"sv) {
  378. whom |= ExposedTo::Window;
  379. } else if (candidate == "Worker"sv) {
  380. whom |= ExposedTo::AllWorkers;
  381. } else if (candidate == "DedicatedWorker"sv) {
  382. whom |= ExposedTo::DedicatedWorker;
  383. } else if (candidate == "SharedWorker"sv) {
  384. whom |= ExposedTo::SharedWorker;
  385. } else if (candidate == "ServiceWorker"sv) {
  386. whom |= ExposedTo::ServiceWorker;
  387. } else if (candidate == "AudioWorklet"sv) {
  388. whom |= ExposedTo::AudioWorklet;
  389. } else {
  390. s_error_string = DeprecatedString::formatted("Unknown Exposed attribute candidate {} in {} in {}", candidate, exposed, interface.name);
  391. return Error::from_string_view(s_error_string.view());
  392. }
  393. }
  394. if (whom == ExposedTo::Nobody) {
  395. s_error_string = DeprecatedString::formatted("Unknown Exposed attribute {} in {}", exposed, interface.name);
  396. return Error::from_string_view(s_error_string.view());
  397. }
  398. return whom;
  399. }
  400. s_error_string = DeprecatedString::formatted("Unknown Exposed attribute {} in {}", exposed, interface.name);
  401. return Error::from_string_view(s_error_string.view());
  402. }
  403. 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)
  404. {
  405. // TODO: Add service worker exposed and audio worklet exposed
  406. auto whom = TRY(parse_exposure_set(interface));
  407. intrinsics.append(interface);
  408. if (whom & ExposedTo::Window)
  409. window_exposed.append(interface);
  410. if (whom & ExposedTo::DedicatedWorker)
  411. dedicated_worker_exposed.append(interface);
  412. if (whom & ExposedTo::SharedWorker)
  413. shared_worker_exposed.append(interface);
  414. return {};
  415. }