IDLParser.cpp 36 KB

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