IDLParser.cpp 42 KB

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