IDLParser.cpp 44 KB

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