IDLParser.cpp 41 KB

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