IDLParser.cpp 36 KB

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