IDLParser.cpp 36 KB

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