IDLParser.cpp 41 KB

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