IDLParser.cpp 38 KB

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