IDLParser.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. interface.constructor_class = DeprecatedString::formatted("{}Constructor", interface.name);
  494. interface.prototype_class = DeprecatedString::formatted("{}Prototype", interface.name);
  495. interface.prototype_base_class = DeprecatedString::formatted("{}Prototype", interface.parent_name.is_empty() ? "Object" : interface.parent_name);
  496. interface.global_mixin_class = DeprecatedString::formatted("{}GlobalMixin", interface.name);
  497. consume_whitespace();
  498. }
  499. void Parser::parse_enumeration(Interface& interface)
  500. {
  501. assert_string("enum"sv);
  502. consume_whitespace();
  503. Enumeration enumeration {};
  504. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  505. consume_whitespace();
  506. assert_specific('{');
  507. bool first = true;
  508. for (; !lexer.is_eof();) {
  509. consume_whitespace();
  510. if (lexer.next_is('}'))
  511. break;
  512. if (!first) {
  513. assert_specific(',');
  514. consume_whitespace();
  515. }
  516. assert_specific('"');
  517. auto string = lexer.consume_until('"');
  518. assert_specific('"');
  519. consume_whitespace();
  520. if (enumeration.values.contains(string))
  521. report_parsing_error(DeprecatedString::formatted("Enumeration {} contains duplicate member '{}'", name, string), filename, input, lexer.tell());
  522. else
  523. enumeration.values.set(string);
  524. if (first)
  525. enumeration.first_member = move(string);
  526. first = false;
  527. }
  528. consume_whitespace();
  529. assert_specific('}');
  530. assert_specific(';');
  531. HashTable<DeprecatedString> names_already_seen;
  532. for (auto& entry : enumeration.values)
  533. enumeration.translated_cpp_names.set(entry, convert_enumeration_value_to_cpp_enum_member(entry, names_already_seen));
  534. interface.enumerations.set(name, move(enumeration));
  535. consume_whitespace();
  536. }
  537. void Parser::parse_typedef(Interface& interface)
  538. {
  539. assert_string("typedef"sv);
  540. consume_whitespace();
  541. HashMap<DeprecatedString, DeprecatedString> extended_attributes;
  542. if (lexer.consume_specific('['))
  543. extended_attributes = parse_extended_attributes();
  544. auto type = parse_type();
  545. consume_whitespace();
  546. auto name = lexer.consume_until(';');
  547. assert_specific(';');
  548. interface.typedefs.set(name, Typedef { move(extended_attributes), move(type) });
  549. consume_whitespace();
  550. }
  551. void Parser::parse_dictionary(Interface& interface)
  552. {
  553. assert_string("dictionary"sv);
  554. consume_whitespace();
  555. Dictionary dictionary {};
  556. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  557. consume_whitespace();
  558. if (lexer.consume_specific(':')) {
  559. consume_whitespace();
  560. dictionary.parent_name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  561. consume_whitespace();
  562. }
  563. assert_specific('{');
  564. for (;;) {
  565. consume_whitespace();
  566. if (lexer.consume_specific('}')) {
  567. consume_whitespace();
  568. assert_specific(';');
  569. break;
  570. }
  571. bool required = false;
  572. HashMap<DeprecatedString, DeprecatedString> extended_attributes;
  573. if (lexer.consume_specific("required")) {
  574. required = true;
  575. consume_whitespace();
  576. if (lexer.consume_specific('['))
  577. extended_attributes = parse_extended_attributes();
  578. }
  579. auto type = parse_type();
  580. consume_whitespace();
  581. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ';'; });
  582. consume_whitespace();
  583. Optional<StringView> default_value;
  584. if (lexer.consume_specific('=')) {
  585. VERIFY(!required);
  586. consume_whitespace();
  587. default_value = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ';'; });
  588. consume_whitespace();
  589. }
  590. assert_specific(';');
  591. DictionaryMember member {
  592. required,
  593. move(type),
  594. name,
  595. move(extended_attributes),
  596. Optional<DeprecatedString>(move(default_value)),
  597. };
  598. dictionary.members.append(move(member));
  599. }
  600. // dictionary members need to be evaluated in lexicographical order
  601. quick_sort(dictionary.members, [&](auto& one, auto& two) {
  602. return one.name < two.name;
  603. });
  604. interface.dictionaries.set(name, move(dictionary));
  605. consume_whitespace();
  606. }
  607. void Parser::parse_interface_mixin(Interface& interface)
  608. {
  609. auto mixin_interface_ptr = make<Interface>();
  610. auto& mixin_interface = *mixin_interface_ptr;
  611. VERIFY(top_level_interfaces().set(move(mixin_interface_ptr)) == AK::HashSetResult::InsertedNewEntry);
  612. mixin_interface.module_own_path = interface.module_own_path;
  613. mixin_interface.is_mixin = true;
  614. assert_string("interface"sv);
  615. consume_whitespace();
  616. assert_string("mixin"sv);
  617. auto offset = lexer.tell();
  618. parse_interface(mixin_interface);
  619. if (!mixin_interface.parent_name.is_empty())
  620. report_parsing_error("Mixin interfaces are not allowed to have inherited parents"sv, filename, input, offset);
  621. auto name = mixin_interface.name;
  622. interface.mixins.set(move(name), &mixin_interface);
  623. }
  624. void Parser::parse_callback_function(HashMap<DeprecatedString, DeprecatedString>& extended_attributes, Interface& interface)
  625. {
  626. assert_string("callback"sv);
  627. consume_whitespace();
  628. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  629. consume_whitespace();
  630. assert_specific('=');
  631. consume_whitespace();
  632. auto return_type = parse_type();
  633. consume_whitespace();
  634. assert_specific('(');
  635. auto parameters = parse_parameters();
  636. assert_specific(')');
  637. consume_whitespace();
  638. assert_specific(';');
  639. interface.callback_functions.set(name, CallbackFunction { move(return_type), move(parameters), extended_attributes.contains("LegacyTreatNonObjectAsNull") });
  640. consume_whitespace();
  641. }
  642. void Parser::parse_non_interface_entities(bool allow_interface, Interface& interface)
  643. {
  644. consume_whitespace();
  645. while (!lexer.is_eof()) {
  646. HashMap<DeprecatedString, DeprecatedString> extended_attributes;
  647. if (lexer.consume_specific('['))
  648. extended_attributes = parse_extended_attributes();
  649. if (lexer.next_is("dictionary")) {
  650. parse_dictionary(interface);
  651. } else if (lexer.next_is("enum")) {
  652. parse_enumeration(interface);
  653. } else if (lexer.next_is("typedef")) {
  654. parse_typedef(interface);
  655. } else if (lexer.next_is("interface mixin")) {
  656. parse_interface_mixin(interface);
  657. } else if (lexer.next_is("callback")) {
  658. parse_callback_function(extended_attributes, interface);
  659. } else if ((allow_interface && !lexer.next_is("interface")) || !allow_interface) {
  660. auto current_offset = lexer.tell();
  661. auto name = lexer.consume_until([](auto ch) { return is_ascii_space(ch); });
  662. consume_whitespace();
  663. if (lexer.consume_specific("includes")) {
  664. consume_whitespace();
  665. auto mixin_name = lexer.consume_until([](auto ch) { return is_ascii_space(ch) || ch == ';'; });
  666. interface.included_mixins.ensure(name).set(mixin_name);
  667. consume_whitespace();
  668. assert_specific(';');
  669. consume_whitespace();
  670. } else {
  671. report_parsing_error("expected 'enum' or 'dictionary'"sv, filename, input, current_offset);
  672. }
  673. } else {
  674. interface.extended_attributes = move(extended_attributes);
  675. break;
  676. }
  677. }
  678. consume_whitespace();
  679. }
  680. static void resolve_union_typedefs(Interface& interface, UnionType& union_);
  681. static void resolve_typedef(Interface& interface, NonnullRefPtr<Type const>& type, HashMap<DeprecatedString, DeprecatedString>* extended_attributes = {})
  682. {
  683. if (is<ParameterizedType>(*type)) {
  684. auto& parameterized_type = const_cast<Type&>(*type).as_parameterized();
  685. auto& parameters = static_cast<Vector<NonnullRefPtr<Type const>>&>(parameterized_type.parameters());
  686. for (auto& parameter : parameters)
  687. resolve_typedef(interface, parameter);
  688. return;
  689. }
  690. // Resolve anonymous union types until we get named types that can be resolved in the next step.
  691. if (is<UnionType>(*type) && type->name().is_empty()) {
  692. resolve_union_typedefs(interface, const_cast<Type&>(*type).as_union());
  693. return;
  694. }
  695. auto it = interface.typedefs.find(type->name());
  696. if (it == interface.typedefs.end())
  697. return;
  698. bool nullable = type->is_nullable();
  699. type = it->value.type;
  700. const_cast<Type&>(*type).set_nullable(nullable);
  701. if (extended_attributes) {
  702. for (auto& attribute : it->value.extended_attributes)
  703. extended_attributes->set(attribute.key, attribute.value);
  704. }
  705. // Recursively resolve typedefs in unions after we resolved the type itself - e.g. for this:
  706. // typedef (A or B) Union1;
  707. // typedef (C or D) Union2;
  708. // typedef (Union1 or Union2) NestedUnion;
  709. // We run:
  710. // - resolve_typedef(NestedUnion) -> NestedUnion gets replaced by UnionType(Union1, Union2)
  711. // - resolve_typedef(Union1) -> Union1 gets replaced by UnionType(A, B)
  712. // - resolve_typedef(Union2) -> Union2 gets replaced by UnionType(C, D)
  713. // So whatever referenced NestedUnion ends up with the following resolved union:
  714. // UnionType(UnionType(A, B), UnionType(C, D))
  715. // Note that flattening unions is handled separately as per the spec.
  716. if (is<UnionType>(*type))
  717. resolve_union_typedefs(interface, const_cast<Type&>(*type).as_union());
  718. }
  719. static void resolve_union_typedefs(Interface& interface, UnionType& union_)
  720. {
  721. auto& member_types = static_cast<Vector<NonnullRefPtr<Type const>>&>(union_.member_types());
  722. for (auto& member_type : member_types)
  723. resolve_typedef(interface, member_type);
  724. }
  725. static void resolve_parameters_typedefs(Interface& interface, Vector<Parameter>& parameters)
  726. {
  727. for (auto& parameter : parameters)
  728. resolve_typedef(interface, parameter.type, &parameter.extended_attributes);
  729. }
  730. template<typename FunctionType>
  731. void resolve_function_typedefs(Interface& interface, FunctionType& function)
  732. {
  733. resolve_typedef(interface, function.return_type);
  734. resolve_parameters_typedefs(interface, function.parameters);
  735. }
  736. Interface& Parser::parse()
  737. {
  738. auto this_module = Core::DeprecatedFile::real_path_for(filename);
  739. auto interface_ptr = make<Interface>();
  740. auto& interface = *interface_ptr;
  741. VERIFY(top_level_interfaces().set(move(interface_ptr)) == AK::HashSetResult::InsertedNewEntry);
  742. interface.module_own_path = this_module;
  743. top_level_resolved_imports().set(this_module, &interface);
  744. Vector<Interface&> imports;
  745. HashTable<DeprecatedString> required_imported_paths;
  746. while (lexer.consume_specific("#import")) {
  747. consume_whitespace();
  748. assert_specific('<');
  749. auto path = lexer.consume_until('>');
  750. lexer.ignore();
  751. auto maybe_interface = resolve_import(path);
  752. if (maybe_interface.has_value()) {
  753. for (auto& entry : maybe_interface.value().required_imported_paths)
  754. required_imported_paths.set(entry);
  755. imports.append(maybe_interface.release_value());
  756. }
  757. consume_whitespace();
  758. }
  759. interface.required_imported_paths = required_imported_paths;
  760. parse_non_interface_entities(true, interface);
  761. if (lexer.consume_specific("interface"))
  762. parse_interface(interface);
  763. parse_non_interface_entities(false, interface);
  764. for (auto& import : imports) {
  765. // FIXME: Instead of copying every imported entity into the current interface, query imports directly
  766. for (auto& dictionary : import.dictionaries)
  767. interface.dictionaries.set(dictionary.key, dictionary.value);
  768. for (auto& enumeration : import.enumerations) {
  769. auto enumeration_copy = enumeration.value;
  770. enumeration_copy.is_original_definition = false;
  771. interface.enumerations.set(enumeration.key, move(enumeration_copy));
  772. }
  773. for (auto& typedef_ : import.typedefs)
  774. interface.typedefs.set(typedef_.key, typedef_.value);
  775. for (auto& mixin : import.mixins) {
  776. if (auto it = interface.mixins.find(mixin.key); it != interface.mixins.end() && it->value != mixin.value)
  777. report_parsing_error(DeprecatedString::formatted("Mixin '{}' was already defined in {}", mixin.key, mixin.value->module_own_path), filename, input, lexer.tell());
  778. interface.mixins.set(mixin.key, mixin.value);
  779. }
  780. for (auto& callback_function : import.callback_functions)
  781. interface.callback_functions.set(callback_function.key, callback_function.value);
  782. }
  783. // Resolve mixins
  784. if (auto it = interface.included_mixins.find(interface.name); it != interface.included_mixins.end()) {
  785. for (auto& entry : it->value) {
  786. auto mixin_it = interface.mixins.find(entry);
  787. if (mixin_it == interface.mixins.end())
  788. report_parsing_error(DeprecatedString::formatted("Mixin '{}' was never defined", entry), filename, input, lexer.tell());
  789. auto& mixin = mixin_it->value;
  790. interface.attributes.extend(mixin->attributes);
  791. interface.constants.extend(mixin->constants);
  792. interface.functions.extend(mixin->functions);
  793. interface.static_functions.extend(mixin->static_functions);
  794. if (interface.has_stringifier && mixin->has_stringifier)
  795. report_parsing_error(DeprecatedString::formatted("Both interface '{}' and mixin '{}' have defined stringifier attributes", interface.name, mixin->name), filename, input, lexer.tell());
  796. if (mixin->has_stringifier) {
  797. interface.stringifier_attribute = mixin->stringifier_attribute;
  798. interface.has_stringifier = true;
  799. }
  800. if (mixin->has_unscopable_member)
  801. interface.has_unscopable_member = true;
  802. }
  803. }
  804. // Resolve typedefs
  805. for (auto& attribute : interface.attributes)
  806. resolve_typedef(interface, attribute.type, &attribute.extended_attributes);
  807. for (auto& constant : interface.constants)
  808. resolve_typedef(interface, constant.type);
  809. for (auto& constructor : interface.constructors)
  810. resolve_parameters_typedefs(interface, constructor.parameters);
  811. for (auto& function : interface.functions)
  812. resolve_function_typedefs(interface, function);
  813. for (auto& static_function : interface.static_functions)
  814. resolve_function_typedefs(interface, static_function);
  815. if (interface.value_iterator_type.has_value())
  816. resolve_typedef(interface, *interface.value_iterator_type);
  817. if (interface.pair_iterator_types.has_value()) {
  818. resolve_typedef(interface, interface.pair_iterator_types->get<0>());
  819. resolve_typedef(interface, interface.pair_iterator_types->get<1>());
  820. }
  821. if (interface.named_property_getter.has_value())
  822. resolve_function_typedefs(interface, *interface.named_property_getter);
  823. if (interface.named_property_setter.has_value())
  824. resolve_function_typedefs(interface, *interface.named_property_setter);
  825. if (interface.indexed_property_getter.has_value())
  826. resolve_function_typedefs(interface, *interface.indexed_property_getter);
  827. if (interface.indexed_property_setter.has_value())
  828. resolve_function_typedefs(interface, *interface.indexed_property_setter);
  829. if (interface.named_property_deleter.has_value())
  830. resolve_function_typedefs(interface, *interface.named_property_deleter);
  831. if (interface.named_property_getter.has_value())
  832. resolve_function_typedefs(interface, *interface.named_property_getter);
  833. for (auto& dictionary : interface.dictionaries) {
  834. for (auto& dictionary_member : dictionary.value.members)
  835. resolve_typedef(interface, dictionary_member.type, &dictionary_member.extended_attributes);
  836. }
  837. for (auto& callback_function : interface.callback_functions)
  838. resolve_function_typedefs(interface, callback_function.value);
  839. // Create overload sets
  840. for (auto& function : interface.functions) {
  841. auto& overload_set = interface.overload_sets.ensure(function.name);
  842. function.overload_index = overload_set.size();
  843. overload_set.append(function);
  844. }
  845. for (auto& overload_set : interface.overload_sets) {
  846. if (overload_set.value.size() == 1)
  847. continue;
  848. for (auto& overloaded_function : overload_set.value)
  849. overloaded_function.is_overloaded = true;
  850. }
  851. for (auto& function : interface.static_functions) {
  852. auto& overload_set = interface.static_overload_sets.ensure(function.name);
  853. function.overload_index = overload_set.size();
  854. overload_set.append(function);
  855. }
  856. for (auto& overload_set : interface.static_overload_sets) {
  857. if (overload_set.value.size() == 1)
  858. continue;
  859. for (auto& overloaded_function : overload_set.value)
  860. overloaded_function.is_overloaded = true;
  861. }
  862. // FIXME: Add support for overloading constructors
  863. if (interface.will_generate_code())
  864. interface.required_imported_paths.set(this_module);
  865. interface.imported_modules = move(imports);
  866. if (top_level_parser() == this)
  867. VERIFY(import_stack.is_empty());
  868. return interface;
  869. }
  870. Parser::Parser(DeprecatedString filename, StringView contents, DeprecatedString import_base_path)
  871. : import_base_path(move(import_base_path))
  872. , filename(move(filename))
  873. , input(contents)
  874. , lexer(input)
  875. {
  876. }
  877. Parser::Parser(Parser* parent, DeprecatedString filename, StringView contents, DeprecatedString import_base_path)
  878. : import_base_path(move(import_base_path))
  879. , filename(move(filename))
  880. , input(contents)
  881. , lexer(input)
  882. , parent(parent)
  883. {
  884. }
  885. Parser* Parser::top_level_parser()
  886. {
  887. Parser* current = this;
  888. for (Parser* next = this; next; next = next->parent)
  889. current = next;
  890. return current;
  891. }
  892. HashMap<DeprecatedString, Interface*>& Parser::top_level_resolved_imports()
  893. {
  894. return top_level_parser()->resolved_imports;
  895. }
  896. HashTable<NonnullOwnPtr<Interface>>& Parser::top_level_interfaces()
  897. {
  898. return top_level_parser()->interfaces;
  899. }
  900. Vector<DeprecatedString> Parser::imported_files() const
  901. {
  902. return const_cast<Parser*>(this)->top_level_resolved_imports().keys();
  903. }
  904. }