IDLParser.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include "IDLParser.h"
  10. #include <AK/Assertions.h>
  11. #include <AK/LexicalPath.h>
  12. #include <AK/QuickSort.h>
  13. #include <LibCore/File.h>
  14. #include <LibFileSystem/FileSystem.h>
  15. [[noreturn]] static void report_parsing_error(StringView message, StringView filename, StringView input, size_t offset)
  16. {
  17. // FIXME: Spaghetti code ahead.
  18. size_t lineno = 1;
  19. size_t colno = 1;
  20. size_t start_line = 0;
  21. size_t line_length = 0;
  22. for (size_t index = 0; index < input.length(); ++index) {
  23. if (offset == index)
  24. colno = index - start_line + 1;
  25. if (input[index] == '\n') {
  26. if (index >= offset)
  27. break;
  28. start_line = index + 1;
  29. line_length = 0;
  30. ++lineno;
  31. } else {
  32. ++line_length;
  33. }
  34. }
  35. StringBuilder error_message;
  36. error_message.appendff("{}\n", input.substring_view(start_line, line_length));
  37. for (size_t i = 0; i < colno - 1; ++i)
  38. error_message.append(' ');
  39. error_message.append("\033[1;31m^\n"sv);
  40. error_message.appendff("{}:{}: error: {}\033[0m\n", filename, lineno, message);
  41. warnln("{}", error_message.string_view());
  42. exit(EXIT_FAILURE);
  43. }
  44. static ByteString convert_enumeration_value_to_cpp_enum_member(ByteString const& value, HashTable<ByteString>& names_already_seen)
  45. {
  46. StringBuilder builder;
  47. GenericLexer lexer { value };
  48. while (!lexer.is_eof()) {
  49. lexer.ignore_while([](auto c) { return is_ascii_space(c) || c == '-' || c == '_'; });
  50. auto word = lexer.consume_while([](auto c) { return is_ascii_alphanumeric(c); });
  51. if (!word.is_empty()) {
  52. builder.append(word.to_titlecase_string());
  53. } else {
  54. auto non_alnum_string = lexer.consume_while([](auto c) { return !is_ascii_alphanumeric(c); });
  55. if (!non_alnum_string.is_empty())
  56. builder.append('_');
  57. }
  58. }
  59. if (builder.is_empty())
  60. builder.append("Empty"sv);
  61. while (names_already_seen.contains(builder.string_view()))
  62. builder.append('_');
  63. names_already_seen.set(builder.string_view());
  64. return builder.to_byte_string();
  65. }
  66. namespace IDL {
  67. void Parser::assert_specific(char ch)
  68. {
  69. if (!lexer.consume_specific(ch))
  70. report_parsing_error(ByteString::formatted("expected '{}'", ch), filename, input, lexer.tell());
  71. }
  72. void Parser::consume_whitespace()
  73. {
  74. bool consumed = true;
  75. while (consumed) {
  76. consumed = lexer.consume_while(is_ascii_space).length() > 0;
  77. if (lexer.consume_specific("//"sv)) {
  78. lexer.consume_until('\n');
  79. lexer.ignore();
  80. consumed = true;
  81. }
  82. }
  83. }
  84. void Parser::assert_string(StringView expected)
  85. {
  86. if (!lexer.consume_specific(expected))
  87. report_parsing_error(ByteString::formatted("expected '{}'", expected), filename, input, lexer.tell());
  88. }
  89. HashMap<ByteString, ByteString> Parser::parse_extended_attributes()
  90. {
  91. HashMap<ByteString, ByteString> extended_attributes;
  92. for (;;) {
  93. consume_whitespace();
  94. if (lexer.consume_specific(']'))
  95. break;
  96. auto name = lexer.consume_until([](auto ch) { return ch == ']' || ch == '=' || ch == ','; });
  97. if (lexer.consume_specific('=')) {
  98. bool did_open_paren = false;
  99. auto value = lexer.consume_until(
  100. [&did_open_paren](auto ch) {
  101. if (ch == '(') {
  102. did_open_paren = true;
  103. return false;
  104. }
  105. if (did_open_paren)
  106. return ch == ')';
  107. return ch == ']' || ch == ',';
  108. });
  109. extended_attributes.set(name, value);
  110. } else {
  111. extended_attributes.set(name, {});
  112. }
  113. lexer.consume_specific(',');
  114. }
  115. consume_whitespace();
  116. return extended_attributes;
  117. }
  118. static HashTable<ByteString> import_stack;
  119. Optional<Interface&> Parser::resolve_import(auto path)
  120. {
  121. auto include_path = LexicalPath::join(import_base_path, path).string();
  122. if (!FileSystem::exists(include_path))
  123. report_parsing_error(ByteString::formatted("{}: No such file or directory", include_path), filename, input, lexer.tell());
  124. auto real_path_error_or = FileSystem::real_path(include_path);
  125. if (real_path_error_or.is_error())
  126. report_parsing_error(ByteString::formatted("Failed to resolve path {}: {}", include_path, real_path_error_or.error()), filename, input, lexer.tell());
  127. auto real_path = real_path_error_or.release_value();
  128. if (top_level_resolved_imports().contains(real_path))
  129. return *top_level_resolved_imports().find(real_path)->value;
  130. if (import_stack.contains(real_path))
  131. report_parsing_error(ByteString::formatted("Circular import detected: {}", include_path), filename, input, lexer.tell());
  132. import_stack.set(real_path);
  133. auto file_or_error = Core::File::open(real_path, Core::File::OpenMode::Read);
  134. if (file_or_error.is_error())
  135. report_parsing_error(ByteString::formatted("Failed to open {}: {}", real_path, file_or_error.error()), filename, input, lexer.tell());
  136. auto data_or_error = file_or_error.value()->read_until_eof();
  137. if (data_or_error.is_error())
  138. report_parsing_error(ByteString::formatted("Failed to read {}: {}", real_path, data_or_error.error()), filename, input, lexer.tell());
  139. auto& result = Parser(this, real_path, data_or_error.value(), import_base_path).parse();
  140. import_stack.remove(real_path);
  141. top_level_resolved_imports().set(real_path, &result);
  142. return result;
  143. }
  144. NonnullRefPtr<Type const> Parser::parse_type()
  145. {
  146. if (lexer.consume_specific('(')) {
  147. Vector<NonnullRefPtr<Type const>> union_member_types;
  148. union_member_types.append(parse_type());
  149. consume_whitespace();
  150. assert_string("or"sv);
  151. consume_whitespace();
  152. union_member_types.append(parse_type());
  153. consume_whitespace();
  154. while (lexer.consume_specific("or"sv)) {
  155. consume_whitespace();
  156. union_member_types.append(parse_type());
  157. consume_whitespace();
  158. }
  159. assert_specific(')');
  160. bool nullable = lexer.consume_specific('?');
  161. auto type = adopt_ref(*new UnionType("", nullable, move(union_member_types)));
  162. if (nullable) {
  163. if (type->number_of_nullable_member_types() > 0)
  164. report_parsing_error("nullable union type cannot contain another nullable type"sv, filename, input, lexer.tell());
  165. // FIXME: A nullable union type cannot include a dictionary type as one of its flattened member types.
  166. }
  167. return type;
  168. }
  169. bool unsigned_ = lexer.consume_specific("unsigned"sv);
  170. if (unsigned_)
  171. consume_whitespace();
  172. // FIXME: Actually treat "unrestricted" and normal floats/doubles differently.
  173. if (lexer.consume_specific("unrestricted"sv))
  174. consume_whitespace();
  175. auto name = lexer.consume_until([](auto ch) { return !is_ascii_alphanumeric(ch) && ch != '_'; });
  176. if (name.equals_ignoring_ascii_case("long"sv)) {
  177. consume_whitespace();
  178. if (lexer.consume_specific("long"sv))
  179. name = "long long"sv;
  180. }
  181. Vector<NonnullRefPtr<Type const>> parameters;
  182. bool is_parameterized_type = false;
  183. if (lexer.consume_specific('<')) {
  184. is_parameterized_type = true;
  185. parameters.append(parse_type());
  186. while (lexer.consume_specific(',')) {
  187. consume_whitespace();
  188. parameters.append(parse_type());
  189. }
  190. lexer.consume_specific('>');
  191. }
  192. auto nullable = lexer.consume_specific('?');
  193. StringBuilder builder;
  194. if (unsigned_)
  195. builder.append("unsigned "sv);
  196. builder.append(name);
  197. if (nullable) {
  198. // https://webidl.spec.whatwg.org/#dfn-nullable-type
  199. // The inner type must not be:
  200. // - any,
  201. if (name == "any"sv)
  202. report_parsing_error("'any' cannot be nullable"sv, filename, input, lexer.tell());
  203. // - a promise type,
  204. if (name == "Promise"sv)
  205. report_parsing_error("'Promise' cannot be nullable"sv, filename, input, lexer.tell());
  206. // - an observable array type,
  207. if (name == "ObservableArray")
  208. report_parsing_error("'ObservableArray' cannot be nullable"sv, filename, input, lexer.tell());
  209. // - another nullable type, or
  210. // - a union type that itself includes a nullable type or has a dictionary type as one of its flattened
  211. // member types
  212. // Note: This case is handled above
  213. }
  214. if (is_parameterized_type)
  215. return adopt_ref(*new ParameterizedType(builder.to_byte_string(), nullable, move(parameters)));
  216. return adopt_ref(*new Type(builder.to_byte_string(), nullable));
  217. }
  218. void Parser::parse_attribute(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface)
  219. {
  220. bool inherit = lexer.consume_specific("inherit"sv);
  221. if (inherit)
  222. consume_whitespace();
  223. bool readonly = lexer.consume_specific("readonly"sv);
  224. if (readonly)
  225. consume_whitespace();
  226. if (lexer.consume_specific("attribute"sv))
  227. consume_whitespace();
  228. else
  229. report_parsing_error("expected 'attribute'"sv, filename, input, lexer.tell());
  230. auto type = parse_type();
  231. consume_whitespace();
  232. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ';'; });
  233. consume_whitespace();
  234. assert_specific(';');
  235. auto name_as_string = name.to_byte_string();
  236. auto getter_callback_name = ByteString::formatted("{}_getter", name_as_string.to_snakecase());
  237. auto setter_callback_name = ByteString::formatted("{}_setter", name_as_string.to_snakecase());
  238. Attribute attribute {
  239. inherit,
  240. readonly,
  241. move(type),
  242. move(name_as_string),
  243. move(extended_attributes),
  244. move(getter_callback_name),
  245. move(setter_callback_name),
  246. };
  247. interface.attributes.append(move(attribute));
  248. }
  249. void Parser::parse_constant(Interface& interface)
  250. {
  251. lexer.consume_specific("const"sv);
  252. consume_whitespace();
  253. auto type = parse_type();
  254. consume_whitespace();
  255. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == '='; });
  256. consume_whitespace();
  257. lexer.consume_specific('=');
  258. consume_whitespace();
  259. auto value = lexer.consume_while([](auto ch) { return !is_ascii_space(ch) && ch != ';'; });
  260. consume_whitespace();
  261. assert_specific(';');
  262. Constant constant {
  263. move(type),
  264. move(name),
  265. move(value),
  266. };
  267. interface.constants.append(move(constant));
  268. }
  269. Vector<Parameter> Parser::parse_parameters()
  270. {
  271. consume_whitespace();
  272. Vector<Parameter> parameters;
  273. for (;;) {
  274. if (lexer.next_is(')'))
  275. break;
  276. HashMap<ByteString, ByteString> extended_attributes;
  277. if (lexer.consume_specific('['))
  278. extended_attributes = parse_extended_attributes();
  279. bool optional = lexer.consume_specific("optional"sv);
  280. if (optional)
  281. consume_whitespace();
  282. if (lexer.consume_specific('[')) {
  283. // Not explicitly forbidden by the grammar but unlikely to happen in practice - if it does,
  284. // we'll have to teach the parser how to merge two sets of extended attributes.
  285. VERIFY(extended_attributes.is_empty());
  286. extended_attributes = parse_extended_attributes();
  287. }
  288. auto type = parse_type();
  289. bool variadic = lexer.consume_specific("..."sv);
  290. consume_whitespace();
  291. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ',' || ch == ')' || ch == '='; });
  292. Parameter parameter = { move(type), move(name), optional, {}, move(extended_attributes), variadic };
  293. consume_whitespace();
  294. if (variadic) {
  295. // Variadic parameters must be last and do not have default values.
  296. parameters.append(move(parameter));
  297. break;
  298. }
  299. if (lexer.next_is(')')) {
  300. parameters.append(move(parameter));
  301. break;
  302. }
  303. if (lexer.next_is('=') && optional) {
  304. assert_specific('=');
  305. consume_whitespace();
  306. auto default_value = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ',' || ch == ')'; });
  307. parameter.optional_default_value = default_value;
  308. }
  309. parameters.append(move(parameter));
  310. if (lexer.next_is(')'))
  311. break;
  312. assert_specific(',');
  313. consume_whitespace();
  314. }
  315. return parameters;
  316. }
  317. Function Parser::parse_function(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface, IsSpecialOperation is_special_operation)
  318. {
  319. bool static_ = false;
  320. if (lexer.consume_specific("static"sv)) {
  321. static_ = true;
  322. consume_whitespace();
  323. }
  324. auto return_type = parse_type();
  325. consume_whitespace();
  326. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == '('; });
  327. consume_whitespace();
  328. assert_specific('(');
  329. auto parameters = parse_parameters();
  330. assert_specific(')');
  331. consume_whitespace();
  332. assert_specific(';');
  333. Function function { move(return_type), name, move(parameters), move(extended_attributes), {}, false };
  334. // "Defining a special operation with an identifier is equivalent to separating the special operation out into its own declaration without an identifier."
  335. if (is_special_operation == IsSpecialOperation::No || (is_special_operation == IsSpecialOperation::Yes && !name.is_empty())) {
  336. if (!static_)
  337. interface.functions.append(function);
  338. else
  339. interface.static_functions.append(function);
  340. }
  341. return function;
  342. }
  343. void Parser::parse_constructor(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface)
  344. {
  345. assert_string("constructor"sv);
  346. consume_whitespace();
  347. assert_specific('(');
  348. auto parameters = parse_parameters();
  349. assert_specific(')');
  350. consume_whitespace();
  351. assert_specific(';');
  352. interface.constructors.append(Constructor { interface.name, move(parameters), move(extended_attributes) });
  353. }
  354. void Parser::parse_stringifier(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface)
  355. {
  356. assert_string("stringifier"sv);
  357. consume_whitespace();
  358. interface.has_stringifier = true;
  359. if (lexer.next_is("attribute"sv) || lexer.next_is("inherit"sv) || lexer.next_is("readonly"sv)) {
  360. parse_attribute(extended_attributes, interface);
  361. interface.stringifier_attribute = interface.attributes.last().name;
  362. } else {
  363. assert_specific(';');
  364. }
  365. }
  366. void Parser::parse_iterable(Interface& interface)
  367. {
  368. assert_string("iterable"sv);
  369. assert_specific('<');
  370. auto first_type = parse_type();
  371. if (lexer.next_is(',')) {
  372. if (interface.supports_indexed_properties())
  373. report_parsing_error("Interfaces with a pair iterator must not supported indexed properties."sv, filename, input, lexer.tell());
  374. assert_specific(',');
  375. consume_whitespace();
  376. auto second_type = parse_type();
  377. interface.pair_iterator_types = Tuple { move(first_type), move(second_type) };
  378. } else {
  379. if (!interface.supports_indexed_properties())
  380. report_parsing_error("Interfaces with a value iterator must supported indexed properties."sv, filename, input, lexer.tell());
  381. interface.value_iterator_type = move(first_type);
  382. }
  383. assert_specific('>');
  384. assert_specific(';');
  385. }
  386. void Parser::parse_getter(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface)
  387. {
  388. assert_string("getter"sv);
  389. consume_whitespace();
  390. auto function = parse_function(extended_attributes, interface, IsSpecialOperation::Yes);
  391. if (function.parameters.size() != 1)
  392. report_parsing_error(ByteString::formatted("Named/indexed property getters must have only 1 parameter, got {} parameters.", function.parameters.size()), filename, input, lexer.tell());
  393. auto& identifier = function.parameters.first();
  394. if (identifier.type->is_nullable())
  395. report_parsing_error("identifier's type must not be nullable."sv, filename, input, lexer.tell());
  396. if (identifier.optional)
  397. report_parsing_error("identifier must not be optional."sv, filename, input, lexer.tell());
  398. // FIXME: Disallow variadic functions once they're supported.
  399. if (identifier.type->name() == "DOMString") {
  400. if (interface.named_property_getter.has_value())
  401. report_parsing_error("An interface can only have one named property getter."sv, filename, input, lexer.tell());
  402. interface.named_property_getter = move(function);
  403. } else if (identifier.type->name() == "unsigned long") {
  404. if (interface.indexed_property_getter.has_value())
  405. report_parsing_error("An interface can only have one indexed property getter."sv, filename, input, lexer.tell());
  406. interface.indexed_property_getter = move(function);
  407. } else {
  408. report_parsing_error(ByteString::formatted("Named/indexed property getter's identifier's type must be either 'DOMString' or 'unsigned long', got '{}'.", identifier.type->name()), filename, input, lexer.tell());
  409. }
  410. }
  411. void Parser::parse_setter(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface)
  412. {
  413. assert_string("setter"sv);
  414. consume_whitespace();
  415. auto function = parse_function(extended_attributes, interface, IsSpecialOperation::Yes);
  416. if (function.parameters.size() != 2)
  417. report_parsing_error(ByteString::formatted("Named/indexed property setters must have only 2 parameters, got {} parameter(s).", function.parameters.size()), filename, input, lexer.tell());
  418. auto& identifier = function.parameters.first();
  419. if (identifier.type->is_nullable())
  420. report_parsing_error("identifier's type must not be nullable."sv, filename, input, lexer.tell());
  421. if (identifier.optional)
  422. report_parsing_error("identifier must not be optional."sv, filename, input, lexer.tell());
  423. // FIXME: Disallow variadic functions once they're supported.
  424. if (identifier.type->name() == "DOMString") {
  425. if (interface.named_property_setter.has_value())
  426. report_parsing_error("An interface can only have one named property setter."sv, filename, input, lexer.tell());
  427. if (!interface.named_property_getter.has_value())
  428. report_parsing_error("A named property setter must be accompanied by a named property getter."sv, filename, input, lexer.tell());
  429. interface.named_property_setter = move(function);
  430. } else if (identifier.type->name() == "unsigned long") {
  431. if (interface.indexed_property_setter.has_value())
  432. report_parsing_error("An interface can only have one indexed property setter."sv, filename, input, lexer.tell());
  433. if (!interface.indexed_property_getter.has_value())
  434. report_parsing_error("An indexed property setter must be accompanied by an indexed property getter."sv, filename, input, lexer.tell());
  435. interface.indexed_property_setter = move(function);
  436. } else {
  437. report_parsing_error(ByteString::formatted("Named/indexed property setter's identifier's type must be either 'DOMString' or 'unsigned long', got '{}'.", identifier.type->name()), filename, input, lexer.tell());
  438. }
  439. }
  440. void Parser::parse_deleter(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface)
  441. {
  442. assert_string("deleter"sv);
  443. consume_whitespace();
  444. auto function = parse_function(extended_attributes, interface, IsSpecialOperation::Yes);
  445. if (function.parameters.size() != 1)
  446. report_parsing_error(ByteString::formatted("Named property deleter must have only 1 parameter, got {} parameters.", function.parameters.size()), filename, input, lexer.tell());
  447. auto& identifier = function.parameters.first();
  448. if (identifier.type->is_nullable())
  449. report_parsing_error("identifier's type must not be nullable."sv, filename, input, lexer.tell());
  450. if (identifier.optional)
  451. report_parsing_error("identifier must not be optional."sv, filename, input, lexer.tell());
  452. // FIXME: Disallow variadic functions once they're supported.
  453. if (identifier.type->name() == "DOMString") {
  454. if (interface.named_property_deleter.has_value())
  455. report_parsing_error("An interface can only have one named property deleter."sv, filename, input, lexer.tell());
  456. if (!interface.named_property_getter.has_value())
  457. report_parsing_error("A named property deleter must be accompanied by a named property getter."sv, filename, input, lexer.tell());
  458. interface.named_property_deleter = move(function);
  459. } else {
  460. report_parsing_error(ByteString::formatted("Named property deleter's identifier's type must be 'DOMString', got '{}'.", identifier.type->name()), filename, input, lexer.tell());
  461. }
  462. }
  463. void Parser::parse_interface(Interface& interface)
  464. {
  465. consume_whitespace();
  466. interface.name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  467. consume_whitespace();
  468. if (lexer.consume_specific(':')) {
  469. consume_whitespace();
  470. interface.parent_name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  471. consume_whitespace();
  472. }
  473. assert_specific('{');
  474. for (;;) {
  475. HashMap<ByteString, ByteString> extended_attributes;
  476. consume_whitespace();
  477. if (lexer.consume_specific('}')) {
  478. consume_whitespace();
  479. assert_specific(';');
  480. break;
  481. }
  482. if (lexer.consume_specific('[')) {
  483. extended_attributes = parse_extended_attributes();
  484. if (!interface.has_unscopable_member && extended_attributes.contains("Unscopable"))
  485. interface.has_unscopable_member = true;
  486. }
  487. if (lexer.next_is("constructor")) {
  488. parse_constructor(extended_attributes, interface);
  489. continue;
  490. }
  491. if (lexer.next_is("const")) {
  492. parse_constant(interface);
  493. continue;
  494. }
  495. if (lexer.next_is("stringifier")) {
  496. parse_stringifier(extended_attributes, interface);
  497. continue;
  498. }
  499. if (lexer.next_is("iterable")) {
  500. parse_iterable(interface);
  501. continue;
  502. }
  503. if (lexer.next_is("inherit") || lexer.next_is("readonly") || lexer.next_is("attribute")) {
  504. parse_attribute(extended_attributes, interface);
  505. continue;
  506. }
  507. if (lexer.next_is("getter")) {
  508. parse_getter(extended_attributes, interface);
  509. continue;
  510. }
  511. if (lexer.next_is("setter")) {
  512. parse_setter(extended_attributes, interface);
  513. continue;
  514. }
  515. if (lexer.next_is("deleter")) {
  516. parse_deleter(extended_attributes, interface);
  517. continue;
  518. }
  519. parse_function(extended_attributes, interface);
  520. }
  521. if (auto legacy_namespace = interface.extended_attributes.get("LegacyNamespace"sv); legacy_namespace.has_value())
  522. interface.namespaced_name = ByteString::formatted("{}.{}", *legacy_namespace, interface.name);
  523. else
  524. interface.namespaced_name = interface.name;
  525. interface.constructor_class = ByteString::formatted("{}Constructor", interface.name);
  526. interface.prototype_class = ByteString::formatted("{}Prototype", interface.name);
  527. interface.prototype_base_class = ByteString::formatted("{}Prototype", interface.parent_name.is_empty() ? "Object" : interface.parent_name);
  528. interface.global_mixin_class = ByteString::formatted("{}GlobalMixin", interface.name);
  529. consume_whitespace();
  530. }
  531. void Parser::parse_namespace(Interface& interface)
  532. {
  533. consume_whitespace();
  534. interface.name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  535. interface.is_namespace = true;
  536. consume_whitespace();
  537. assert_specific('{');
  538. for (;;) {
  539. consume_whitespace();
  540. if (lexer.consume_specific('}')) {
  541. consume_whitespace();
  542. assert_specific(';');
  543. break;
  544. }
  545. HashMap<ByteString, ByteString> extended_attributes;
  546. parse_function(extended_attributes, interface);
  547. }
  548. interface.namespace_class = ByteString::formatted("{}Namespace", interface.name);
  549. consume_whitespace();
  550. }
  551. void Parser::parse_enumeration(HashMap<ByteString, ByteString> extended_attributes, Interface& interface)
  552. {
  553. assert_string("enum"sv);
  554. consume_whitespace();
  555. Enumeration enumeration {};
  556. enumeration.extended_attributes = move(extended_attributes);
  557. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  558. consume_whitespace();
  559. assert_specific('{');
  560. bool first = true;
  561. for (; !lexer.is_eof();) {
  562. consume_whitespace();
  563. if (lexer.next_is('}'))
  564. break;
  565. if (!first) {
  566. assert_specific(',');
  567. consume_whitespace();
  568. }
  569. assert_specific('"');
  570. auto string = lexer.consume_until('"');
  571. assert_specific('"');
  572. consume_whitespace();
  573. if (enumeration.values.contains(string))
  574. report_parsing_error(ByteString::formatted("Enumeration {} contains duplicate member '{}'", name, string), filename, input, lexer.tell());
  575. else
  576. enumeration.values.set(string);
  577. if (first)
  578. enumeration.first_member = move(string);
  579. first = false;
  580. }
  581. consume_whitespace();
  582. assert_specific('}');
  583. assert_specific(';');
  584. HashTable<ByteString> names_already_seen;
  585. for (auto& entry : enumeration.values)
  586. enumeration.translated_cpp_names.set(entry, convert_enumeration_value_to_cpp_enum_member(entry, names_already_seen));
  587. interface.enumerations.set(name, move(enumeration));
  588. consume_whitespace();
  589. }
  590. void Parser::parse_typedef(Interface& interface)
  591. {
  592. assert_string("typedef"sv);
  593. consume_whitespace();
  594. HashMap<ByteString, ByteString> extended_attributes;
  595. if (lexer.consume_specific('['))
  596. extended_attributes = parse_extended_attributes();
  597. auto type = parse_type();
  598. consume_whitespace();
  599. auto name = lexer.consume_until(';');
  600. assert_specific(';');
  601. interface.typedefs.set(name, Typedef { move(extended_attributes), move(type) });
  602. consume_whitespace();
  603. }
  604. void Parser::parse_dictionary(Interface& interface)
  605. {
  606. assert_string("dictionary"sv);
  607. consume_whitespace();
  608. Dictionary dictionary {};
  609. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  610. consume_whitespace();
  611. if (lexer.consume_specific(':')) {
  612. consume_whitespace();
  613. dictionary.parent_name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  614. consume_whitespace();
  615. }
  616. assert_specific('{');
  617. for (;;) {
  618. consume_whitespace();
  619. if (lexer.consume_specific('}')) {
  620. consume_whitespace();
  621. assert_specific(';');
  622. break;
  623. }
  624. bool required = false;
  625. HashMap<ByteString, ByteString> extended_attributes;
  626. if (lexer.consume_specific("required"sv)) {
  627. required = true;
  628. consume_whitespace();
  629. }
  630. if (lexer.consume_specific('['))
  631. extended_attributes = parse_extended_attributes();
  632. auto type = parse_type();
  633. consume_whitespace();
  634. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ';'; });
  635. consume_whitespace();
  636. Optional<StringView> default_value;
  637. if (lexer.consume_specific('=')) {
  638. VERIFY(!required);
  639. consume_whitespace();
  640. default_value = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ';'; });
  641. consume_whitespace();
  642. }
  643. assert_specific(';');
  644. DictionaryMember member {
  645. required,
  646. move(type),
  647. name,
  648. move(extended_attributes),
  649. Optional<ByteString>(move(default_value)),
  650. };
  651. dictionary.members.append(move(member));
  652. }
  653. // dictionary members need to be evaluated in lexicographical order
  654. quick_sort(dictionary.members, [&](auto& one, auto& two) {
  655. return one.name < two.name;
  656. });
  657. interface.dictionaries.set(name, move(dictionary));
  658. consume_whitespace();
  659. }
  660. void Parser::parse_interface_mixin(Interface& interface)
  661. {
  662. auto mixin_interface_ptr = make<Interface>();
  663. auto& mixin_interface = *mixin_interface_ptr;
  664. VERIFY(top_level_interfaces().set(move(mixin_interface_ptr)) == AK::HashSetResult::InsertedNewEntry);
  665. mixin_interface.module_own_path = interface.module_own_path;
  666. mixin_interface.is_mixin = true;
  667. assert_string("interface"sv);
  668. consume_whitespace();
  669. assert_string("mixin"sv);
  670. auto offset = lexer.tell();
  671. parse_interface(mixin_interface);
  672. if (!mixin_interface.parent_name.is_empty())
  673. report_parsing_error("Mixin interfaces are not allowed to have inherited parents"sv, filename, input, offset);
  674. auto name = mixin_interface.name;
  675. interface.mixins.set(move(name), &mixin_interface);
  676. }
  677. void Parser::parse_callback_function(HashMap<ByteString, ByteString>& extended_attributes, Interface& interface)
  678. {
  679. assert_string("callback"sv);
  680. consume_whitespace();
  681. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  682. consume_whitespace();
  683. assert_specific('=');
  684. consume_whitespace();
  685. auto return_type = parse_type();
  686. consume_whitespace();
  687. assert_specific('(');
  688. auto parameters = parse_parameters();
  689. assert_specific(')');
  690. consume_whitespace();
  691. assert_specific(';');
  692. interface.callback_functions.set(name, CallbackFunction { move(return_type), move(parameters), extended_attributes.contains("LegacyTreatNonObjectAsNull") });
  693. consume_whitespace();
  694. }
  695. void Parser::parse_non_interface_entities(bool allow_interface, Interface& interface)
  696. {
  697. consume_whitespace();
  698. while (!lexer.is_eof()) {
  699. HashMap<ByteString, ByteString> extended_attributes;
  700. if (lexer.consume_specific('['))
  701. extended_attributes = parse_extended_attributes();
  702. if (lexer.next_is("dictionary")) {
  703. parse_dictionary(interface);
  704. } else if (lexer.next_is("enum")) {
  705. parse_enumeration(extended_attributes, interface);
  706. } else if (lexer.next_is("typedef")) {
  707. parse_typedef(interface);
  708. } else if (lexer.next_is("interface mixin")) {
  709. parse_interface_mixin(interface);
  710. } else if (lexer.next_is("callback")) {
  711. parse_callback_function(extended_attributes, interface);
  712. } else if ((allow_interface && !lexer.next_is("interface") && !lexer.next_is("namespace")) || !allow_interface) {
  713. auto current_offset = lexer.tell();
  714. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  715. consume_whitespace();
  716. if (lexer.consume_specific("includes"sv)) {
  717. consume_whitespace();
  718. auto mixin_name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ';'; });
  719. interface.included_mixins.ensure(name).set(mixin_name);
  720. consume_whitespace();
  721. assert_specific(';');
  722. consume_whitespace();
  723. } else {
  724. report_parsing_error("expected 'enum' or 'dictionary'"sv, filename, input, current_offset);
  725. }
  726. } else {
  727. interface.extended_attributes = move(extended_attributes);
  728. break;
  729. }
  730. }
  731. consume_whitespace();
  732. }
  733. static void resolve_union_typedefs(Interface& interface, UnionType& union_);
  734. static void resolve_typedef(Interface& interface, NonnullRefPtr<Type const>& type, HashMap<ByteString, ByteString>* extended_attributes = {})
  735. {
  736. if (is<ParameterizedType>(*type)) {
  737. auto& parameterized_type = const_cast<Type&>(*type).as_parameterized();
  738. auto& parameters = static_cast<Vector<NonnullRefPtr<Type const>>&>(parameterized_type.parameters());
  739. for (auto& parameter : parameters)
  740. resolve_typedef(interface, parameter);
  741. return;
  742. }
  743. // Resolve anonymous union types until we get named types that can be resolved in the next step.
  744. if (is<UnionType>(*type) && type->name().is_empty()) {
  745. resolve_union_typedefs(interface, const_cast<Type&>(*type).as_union());
  746. return;
  747. }
  748. auto it = interface.typedefs.find(type->name());
  749. if (it == interface.typedefs.end())
  750. return;
  751. bool nullable = type->is_nullable();
  752. type = it->value.type;
  753. const_cast<Type&>(*type).set_nullable(nullable);
  754. if (extended_attributes) {
  755. for (auto& attribute : it->value.extended_attributes)
  756. extended_attributes->set(attribute.key, attribute.value);
  757. }
  758. // Recursively resolve typedefs in unions after we resolved the type itself - e.g. for this:
  759. // typedef (A or B) Union1;
  760. // typedef (C or D) Union2;
  761. // typedef (Union1 or Union2) NestedUnion;
  762. // We run:
  763. // - resolve_typedef(NestedUnion) -> NestedUnion gets replaced by UnionType(Union1, Union2)
  764. // - resolve_typedef(Union1) -> Union1 gets replaced by UnionType(A, B)
  765. // - resolve_typedef(Union2) -> Union2 gets replaced by UnionType(C, D)
  766. // So whatever referenced NestedUnion ends up with the following resolved union:
  767. // UnionType(UnionType(A, B), UnionType(C, D))
  768. // Note that flattening unions is handled separately as per the spec.
  769. if (is<UnionType>(*type))
  770. resolve_union_typedefs(interface, const_cast<Type&>(*type).as_union());
  771. }
  772. static void resolve_union_typedefs(Interface& interface, UnionType& union_)
  773. {
  774. auto& member_types = static_cast<Vector<NonnullRefPtr<Type const>>&>(union_.member_types());
  775. for (auto& member_type : member_types)
  776. resolve_typedef(interface, member_type);
  777. }
  778. static void resolve_parameters_typedefs(Interface& interface, Vector<Parameter>& parameters)
  779. {
  780. for (auto& parameter : parameters)
  781. resolve_typedef(interface, parameter.type, &parameter.extended_attributes);
  782. }
  783. template<typename FunctionType>
  784. void resolve_function_typedefs(Interface& interface, FunctionType& function)
  785. {
  786. resolve_typedef(interface, function.return_type);
  787. resolve_parameters_typedefs(interface, function.parameters);
  788. }
  789. Interface& Parser::parse()
  790. {
  791. auto this_module_or_error = FileSystem::real_path(filename);
  792. if (this_module_or_error.is_error()) {
  793. report_parsing_error(ByteString::formatted("Failed to resolve path '{}': {}", filename, this_module_or_error.error()), filename, input, 0);
  794. VERIFY_NOT_REACHED();
  795. }
  796. auto this_module = this_module_or_error.release_value();
  797. auto interface_ptr = make<Interface>();
  798. auto& interface = *interface_ptr;
  799. VERIFY(top_level_interfaces().set(move(interface_ptr)) == AK::HashSetResult::InsertedNewEntry);
  800. interface.module_own_path = this_module;
  801. top_level_resolved_imports().set(this_module, &interface);
  802. Vector<Interface&> imports;
  803. {
  804. HashTable<ByteString> required_imported_paths;
  805. while (lexer.consume_specific("#import"sv)) {
  806. consume_whitespace();
  807. assert_specific('<');
  808. auto path = lexer.consume_until('>');
  809. lexer.ignore();
  810. auto maybe_interface = resolve_import(path);
  811. if (maybe_interface.has_value()) {
  812. for (auto& entry : maybe_interface.value().required_imported_paths)
  813. required_imported_paths.set(entry);
  814. imports.append(maybe_interface.release_value());
  815. }
  816. consume_whitespace();
  817. }
  818. interface.required_imported_paths = move(required_imported_paths);
  819. }
  820. parse_non_interface_entities(true, interface);
  821. if (lexer.consume_specific("interface"sv))
  822. parse_interface(interface);
  823. else if (lexer.consume_specific("namespace"sv))
  824. parse_namespace(interface);
  825. parse_non_interface_entities(false, interface);
  826. for (auto& import : imports) {
  827. // FIXME: Instead of copying every imported entity into the current interface, query imports directly
  828. for (auto& dictionary : import.dictionaries)
  829. interface.dictionaries.set(dictionary.key, dictionary.value);
  830. for (auto& enumeration : import.enumerations) {
  831. auto enumeration_copy = enumeration.value;
  832. enumeration_copy.is_original_definition = false;
  833. interface.enumerations.set(enumeration.key, move(enumeration_copy));
  834. }
  835. for (auto& typedef_ : import.typedefs)
  836. interface.typedefs.set(typedef_.key, typedef_.value);
  837. for (auto& mixin : import.mixins) {
  838. if (auto it = interface.mixins.find(mixin.key); it != interface.mixins.end() && it->value != mixin.value)
  839. report_parsing_error(ByteString::formatted("Mixin '{}' was already defined in {}", mixin.key, mixin.value->module_own_path), filename, input, lexer.tell());
  840. interface.mixins.set(mixin.key, mixin.value);
  841. }
  842. for (auto& callback_function : import.callback_functions)
  843. interface.callback_functions.set(callback_function.key, callback_function.value);
  844. }
  845. // Resolve mixins
  846. if (auto it = interface.included_mixins.find(interface.name); it != interface.included_mixins.end()) {
  847. for (auto& entry : it->value) {
  848. auto mixin_it = interface.mixins.find(entry);
  849. if (mixin_it == interface.mixins.end())
  850. report_parsing_error(ByteString::formatted("Mixin '{}' was never defined", entry), filename, input, lexer.tell());
  851. auto& mixin = mixin_it->value;
  852. interface.attributes.extend(mixin->attributes);
  853. interface.constants.extend(mixin->constants);
  854. interface.functions.extend(mixin->functions);
  855. interface.static_functions.extend(mixin->static_functions);
  856. if (interface.has_stringifier && mixin->has_stringifier)
  857. report_parsing_error(ByteString::formatted("Both interface '{}' and mixin '{}' have defined stringifier attributes", interface.name, mixin->name), filename, input, lexer.tell());
  858. if (mixin->has_stringifier) {
  859. interface.stringifier_attribute = mixin->stringifier_attribute;
  860. interface.has_stringifier = true;
  861. }
  862. if (mixin->has_unscopable_member)
  863. interface.has_unscopable_member = true;
  864. }
  865. }
  866. // Resolve typedefs
  867. for (auto& attribute : interface.attributes)
  868. resolve_typedef(interface, attribute.type, &attribute.extended_attributes);
  869. for (auto& constant : interface.constants)
  870. resolve_typedef(interface, constant.type);
  871. for (auto& constructor : interface.constructors)
  872. resolve_parameters_typedefs(interface, constructor.parameters);
  873. for (auto& function : interface.functions)
  874. resolve_function_typedefs(interface, function);
  875. for (auto& static_function : interface.static_functions)
  876. resolve_function_typedefs(interface, static_function);
  877. if (interface.value_iterator_type.has_value())
  878. resolve_typedef(interface, *interface.value_iterator_type);
  879. if (interface.pair_iterator_types.has_value()) {
  880. resolve_typedef(interface, interface.pair_iterator_types->get<0>());
  881. resolve_typedef(interface, interface.pair_iterator_types->get<1>());
  882. }
  883. if (interface.named_property_getter.has_value())
  884. resolve_function_typedefs(interface, *interface.named_property_getter);
  885. if (interface.named_property_setter.has_value())
  886. resolve_function_typedefs(interface, *interface.named_property_setter);
  887. if (interface.indexed_property_getter.has_value())
  888. resolve_function_typedefs(interface, *interface.indexed_property_getter);
  889. if (interface.indexed_property_setter.has_value())
  890. resolve_function_typedefs(interface, *interface.indexed_property_setter);
  891. if (interface.named_property_deleter.has_value())
  892. resolve_function_typedefs(interface, *interface.named_property_deleter);
  893. if (interface.named_property_getter.has_value())
  894. resolve_function_typedefs(interface, *interface.named_property_getter);
  895. for (auto& dictionary : interface.dictionaries) {
  896. for (auto& dictionary_member : dictionary.value.members)
  897. resolve_typedef(interface, dictionary_member.type, &dictionary_member.extended_attributes);
  898. }
  899. for (auto& callback_function : interface.callback_functions)
  900. resolve_function_typedefs(interface, callback_function.value);
  901. // Create overload sets
  902. for (auto& function : interface.functions) {
  903. auto& overload_set = interface.overload_sets.ensure(function.name);
  904. function.overload_index = overload_set.size();
  905. overload_set.append(function);
  906. }
  907. for (auto& overload_set : interface.overload_sets) {
  908. if (overload_set.value.size() == 1)
  909. continue;
  910. for (auto& overloaded_function : overload_set.value)
  911. overloaded_function.is_overloaded = true;
  912. }
  913. for (auto& function : interface.static_functions) {
  914. auto& overload_set = interface.static_overload_sets.ensure(function.name);
  915. function.overload_index = overload_set.size();
  916. overload_set.append(function);
  917. }
  918. for (auto& overload_set : interface.static_overload_sets) {
  919. if (overload_set.value.size() == 1)
  920. continue;
  921. for (auto& overloaded_function : overload_set.value)
  922. overloaded_function.is_overloaded = true;
  923. }
  924. // FIXME: Add support for overloading constructors
  925. if (interface.will_generate_code())
  926. interface.required_imported_paths.set(this_module);
  927. interface.imported_modules = move(imports);
  928. if (top_level_parser() == this)
  929. VERIFY(import_stack.is_empty());
  930. return interface;
  931. }
  932. Parser::Parser(ByteString filename, StringView contents, ByteString import_base_path)
  933. : import_base_path(move(import_base_path))
  934. , filename(move(filename))
  935. , input(contents)
  936. , lexer(input)
  937. {
  938. }
  939. Parser::Parser(Parser* parent, ByteString filename, StringView contents, ByteString import_base_path)
  940. : import_base_path(move(import_base_path))
  941. , filename(move(filename))
  942. , input(contents)
  943. , lexer(input)
  944. , parent(parent)
  945. {
  946. }
  947. Parser* Parser::top_level_parser()
  948. {
  949. Parser* current = this;
  950. for (Parser* next = this; next; next = next->parent)
  951. current = next;
  952. return current;
  953. }
  954. HashMap<ByteString, Interface*>& Parser::top_level_resolved_imports()
  955. {
  956. return top_level_parser()->resolved_imports;
  957. }
  958. HashTable<NonnullOwnPtr<Interface>>& Parser::top_level_interfaces()
  959. {
  960. return top_level_parser()->interfaces;
  961. }
  962. Vector<ByteString> Parser::imported_files() const
  963. {
  964. return const_cast<Parser*>(this)->top_level_resolved_imports().keys();
  965. }
  966. }