SpecParser.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (c) 2023, Dan Klishch <danilklishch@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/NonnullOwnPtr.h>
  7. #include <LibCore/File.h>
  8. #include <LibXML/Parser/Parser.h>
  9. #include "Function.h"
  10. #include "Parser/Lexer.h"
  11. #include "Parser/SpecParser.h"
  12. #include "Parser/TextParser.h"
  13. #include "Parser/XMLUtils.h"
  14. namespace JSSpecCompiler {
  15. DiagnosticEngine& SpecificationParsingContext::diag()
  16. {
  17. return m_translation_unit->diag();
  18. }
  19. template<typename Func>
  20. auto SpecificationParsingContext::with_new_logical_scope(Func&& func)
  21. {
  22. TemporaryChange<RefPtr<LogicalLocation>> change(m_current_logical_scope, make_ref_counted<LogicalLocation>());
  23. return func();
  24. }
  25. LogicalLocation& SpecificationParsingContext::current_logical_scope()
  26. {
  27. return *m_current_logical_scope;
  28. }
  29. template<typename Func>
  30. auto SpecificationParsingContext::with_new_step_list_nesting_level(Func&& func)
  31. {
  32. TemporaryChange change(m_step_list_nesting_level, m_step_list_nesting_level + 1);
  33. return func();
  34. }
  35. int SpecificationParsingContext::step_list_nesting_level() const
  36. {
  37. return m_step_list_nesting_level;
  38. }
  39. Location SpecificationParsingContext::file_scope() const
  40. {
  41. return { .filename = m_translation_unit->filename() };
  42. }
  43. Location SpecificationParsingContext::location_from_xml_offset(XML::Offset offset) const
  44. {
  45. return {
  46. .filename = m_translation_unit->filename(),
  47. .line = offset.line,
  48. .column = offset.column,
  49. .logical_location = m_current_logical_scope,
  50. };
  51. }
  52. Optional<AlgorithmStep> AlgorithmStep::create(SpecificationParsingContext& ctx, XML::Node const* element)
  53. {
  54. VERIFY(element->as_element().name == tag_li);
  55. auto [maybe_tokens, substeps] = tokenize_step(ctx, element);
  56. AlgorithmStep result(ctx);
  57. result.m_node = element;
  58. if (substeps) {
  59. // FIXME: Remove this once macOS Lagom CI updates to Clang >= 16.
  60. auto substeps_copy = substeps;
  61. auto step_list = ctx.with_new_step_list_nesting_level([&] {
  62. return AlgorithmStepList::create(ctx, substeps_copy);
  63. });
  64. result.m_substeps = step_list.has_value() ? step_list->tree() : error_tree;
  65. }
  66. if (!maybe_tokens.has_value())
  67. return {};
  68. result.m_tokens = maybe_tokens.release_value();
  69. if (!result.parse())
  70. return {};
  71. return result;
  72. }
  73. bool AlgorithmStep::parse()
  74. {
  75. TextParser parser(m_ctx, m_tokens, m_node);
  76. TextParseErrorOr<Tree> parse_result = TextParseError {};
  77. if (m_substeps)
  78. parse_result = parser.parse_step_with_substeps(RefPtr(m_substeps).release_nonnull());
  79. else
  80. parse_result = parser.parse_step_without_substeps();
  81. if (parse_result.is_error()) {
  82. auto [location, message] = parser.get_diagnostic();
  83. m_ctx.diag().error(location, "{}", message);
  84. return false;
  85. } else {
  86. m_expression = parse_result.release_value();
  87. return true;
  88. }
  89. }
  90. Optional<AlgorithmStepList> AlgorithmStepList::create(SpecificationParsingContext& ctx, XML::Node const* element)
  91. {
  92. VERIFY(element->as_element().name == tag_ol);
  93. AlgorithmStepList result;
  94. Vector<Tree> step_expressions;
  95. bool all_steps_parsed = true;
  96. int step_number = 0;
  97. auto const& parent_scope = ctx.current_logical_scope();
  98. for (auto const& child : element->as_element().children) {
  99. child->content.visit(
  100. [&](XML::Node::Element const& element) {
  101. if (element.name == tag_li) {
  102. auto step_creation_result = ctx.with_new_logical_scope([&] {
  103. update_logical_scope_for_step(ctx, parent_scope, step_number);
  104. return AlgorithmStep::create(ctx, child);
  105. });
  106. if (!step_creation_result.has_value())
  107. all_steps_parsed = false;
  108. else
  109. step_expressions.append(step_creation_result.release_value().tree());
  110. ++step_number;
  111. return;
  112. }
  113. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  114. "<{}> should not be a child of algorithm step list"sv, element.name);
  115. },
  116. [&](XML::Node::Text const&) {
  117. if (!contains_empty_text(child)) {
  118. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  119. "non-empty text node should not be a child of algorithm step list");
  120. }
  121. },
  122. [&](auto const&) {});
  123. }
  124. if (!all_steps_parsed)
  125. return {};
  126. result.m_expression = make_ref_counted<TreeList>(move(step_expressions));
  127. return result;
  128. }
  129. void AlgorithmStepList::update_logical_scope_for_step(SpecificationParsingContext& ctx, LogicalLocation const& parent_scope, int step_number)
  130. {
  131. int nesting_level = ctx.step_list_nesting_level();
  132. String list_step_number;
  133. if (nesting_level == 0 || nesting_level == 3) {
  134. list_step_number = MUST(String::formatted("{}", step_number + 1));
  135. } else if (nesting_level == 1 || nesting_level == 4) {
  136. if (step_number < 26)
  137. list_step_number = String::from_code_point('a' + step_number);
  138. else
  139. list_step_number = MUST(String::formatted("{}", step_number + 1));
  140. } else {
  141. list_step_number = MUST(String::from_byte_string(ByteString::roman_number_from(step_number + 1).to_lowercase()));
  142. }
  143. auto& scope = ctx.current_logical_scope();
  144. scope.section = parent_scope.section;
  145. if (parent_scope.step.is_empty())
  146. scope.step = list_step_number;
  147. else
  148. scope.step = MUST(String::formatted("{}.{}", parent_scope.step, list_step_number));
  149. }
  150. Optional<Algorithm> Algorithm::create(SpecificationParsingContext& ctx, XML::Node const* element)
  151. {
  152. VERIFY(element->as_element().name == tag_emu_alg);
  153. Vector<XML::Node const*> steps_list;
  154. for (auto const& child : element->as_element().children) {
  155. child->content.visit(
  156. [&](XML::Node::Element const& element) {
  157. if (element.name == tag_ol) {
  158. steps_list.append(child);
  159. return;
  160. }
  161. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  162. "<{}> should not be a child of <emu-alg>"sv, element.name);
  163. },
  164. [&](XML::Node::Text const&) {
  165. if (!contains_empty_text(child)) {
  166. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  167. "non-empty text node should not be a child of <emu-alg>");
  168. }
  169. },
  170. [&](auto const&) {});
  171. }
  172. if (steps_list.size() != 1) {
  173. ctx.diag().error(ctx.location_from_xml_offset(element->offset),
  174. "<emu-alg> should have exactly one <ol> child"sv);
  175. return {};
  176. }
  177. auto steps_creation_result = AlgorithmStepList::create(ctx, steps_list[0]);
  178. if (steps_creation_result.has_value()) {
  179. Algorithm algorithm;
  180. algorithm.m_tree = steps_creation_result.release_value().tree();
  181. return algorithm;
  182. }
  183. return {};
  184. }
  185. NonnullOwnPtr<SpecificationClause> SpecificationClause::create(SpecificationParsingContext& ctx, XML::Node const* element)
  186. {
  187. return ctx.with_new_logical_scope([&] {
  188. VERIFY(element->as_element().name == tag_emu_clause);
  189. SpecificationClause specification_clause(ctx);
  190. specification_clause.parse(element);
  191. OwnPtr<SpecificationClause> result;
  192. specification_clause.m_header.header.visit(
  193. [&](AK::Empty const&) {
  194. result = make<SpecificationClause>(move(specification_clause));
  195. },
  196. [&](ClauseHeader::FunctionDefinition const&) {
  197. result = make<SpecFunction>(move(specification_clause));
  198. });
  199. if (!result->post_initialize(element))
  200. result = make<SpecificationClause>(move(*result));
  201. return result.release_nonnull();
  202. });
  203. }
  204. void SpecificationClause::collect_into(TranslationUnitRef translation_unit)
  205. {
  206. do_collect(translation_unit);
  207. for (auto& subclause : m_subclauses)
  208. subclause->collect_into(translation_unit);
  209. }
  210. Optional<FailedTextParseDiagnostic> SpecificationClause::parse_header(XML::Node const* element)
  211. {
  212. auto& ctx = *m_ctx_pointer;
  213. VERIFY(element->as_element().name == tag_h1);
  214. auto maybe_tokens = tokenize_header(ctx, element);
  215. if (!maybe_tokens.has_value())
  216. return {};
  217. auto const& tokens = maybe_tokens.release_value();
  218. TextParser parser(ctx, tokens, element);
  219. auto parse_result = parser.parse_clause_header();
  220. if (parse_result.is_error()) {
  221. // Still try to at least scavenge section number.
  222. if (tokens.size() && tokens[0].type == TokenType::SectionNumber)
  223. ctx.current_logical_scope().section = MUST(String::from_utf8(tokens[0].data));
  224. return parser.get_diagnostic();
  225. }
  226. m_header = parse_result.release_value();
  227. ctx.current_logical_scope().section = MUST(String::from_utf8(m_header.section_number));
  228. return {};
  229. }
  230. void SpecificationClause::parse(XML::Node const* element)
  231. {
  232. auto& ctx = context();
  233. u32 child_index = 0;
  234. bool node_ignored_warning_issued = false;
  235. Optional<FailedTextParseDiagnostic> header_parse_error;
  236. for (auto const& child : element->as_element().children) {
  237. child->content.visit(
  238. [&](XML::Node::Element const& element) {
  239. if (child_index == 0) {
  240. if (element.name != tag_h1) {
  241. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  242. "<h1> must be the first child of <emu-clause>");
  243. return;
  244. }
  245. header_parse_error = parse_header(child);
  246. } else {
  247. if (element.name == tag_h1) {
  248. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  249. "<h1> can only be the first child of <emu-clause>");
  250. return;
  251. }
  252. if (element.name == tag_emu_clause) {
  253. m_subclauses.append(create(ctx, child));
  254. return;
  255. }
  256. if (!node_ignored_warning_issued && m_header.header.has<AK::Empty>()) {
  257. node_ignored_warning_issued = true;
  258. ctx.diag().warn(ctx.location_from_xml_offset(child->offset),
  259. "node content will be ignored since section header was not parsed successfully");
  260. if (header_parse_error.has_value())
  261. ctx.diag().note(header_parse_error->location, "{}", header_parse_error->message);
  262. }
  263. }
  264. ++child_index;
  265. },
  266. [&](XML::Node::Text const&) {
  267. if (!contains_empty_text(child)) {
  268. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  269. "non-empty text node should not be a child of <emu-clause>");
  270. }
  271. },
  272. [&](auto) {});
  273. }
  274. }
  275. bool SpecFunction::post_initialize(XML::Node const* element)
  276. {
  277. VERIFY(element->as_element().name == tag_emu_clause);
  278. auto& ctx = context();
  279. auto maybe_id = get_attribute_by_name(element, attribute_id);
  280. if (!maybe_id.has_value()) {
  281. ctx.diag().error(ctx.location_from_xml_offset(element->offset),
  282. "no id attribute");
  283. } else {
  284. m_id = maybe_id.value();
  285. }
  286. auto maybe_abstract_operation_id = get_attribute_by_name(element, attribute_aoid);
  287. if (maybe_abstract_operation_id.has_value())
  288. m_name = maybe_abstract_operation_id.value();
  289. m_section_number = m_header.section_number;
  290. auto const& [function_name, arguments] = m_header.header.get<ClauseHeader::FunctionDefinition>();
  291. m_arguments = arguments;
  292. if (m_name != function_name) {
  293. ctx.diag().warn(ctx.location_from_xml_offset(element->offset),
  294. "function name in header and <emu-clause>[aoid] do not match");
  295. }
  296. Vector<XML::Node const*> algorithm_nodes;
  297. for (auto const& child : element->as_element().children) {
  298. child->content.visit(
  299. [&](XML::Node::Element const& element) {
  300. if (element.name == tag_h1) {
  301. // Processed in SpecificationClause
  302. } else if (element.name == tag_p) {
  303. ctx.diag().warn(ctx.location_from_xml_offset(child->offset),
  304. "prose is ignored");
  305. } else if (element.name == tag_emu_alg) {
  306. algorithm_nodes.append(child);
  307. } else {
  308. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  309. "<{}> should not be a child of <emu-clause> specifing function"sv, element.name);
  310. }
  311. },
  312. [&](auto const&) {});
  313. }
  314. if (algorithm_nodes.size() != 1) {
  315. ctx.diag().error(ctx.location_from_xml_offset(element->offset),
  316. "<emu-clause> specifing function should have exactly one <emu-alg> child"sv);
  317. return false;
  318. }
  319. auto maybe_algorithm = Algorithm::create(ctx, algorithm_nodes[0]);
  320. if (maybe_algorithm.has_value()) {
  321. m_algorithm = maybe_algorithm.release_value();
  322. return true;
  323. } else {
  324. return false;
  325. }
  326. }
  327. void SpecFunction::do_collect(TranslationUnitRef translation_unit)
  328. {
  329. translation_unit->adopt_function(make_ref_counted<FunctionDefinition>(m_name, m_algorithm.tree(), move(m_arguments)));
  330. }
  331. Specification Specification::create(SpecificationParsingContext& ctx, XML::Node const* element)
  332. {
  333. VERIFY(element->as_element().name == tag_specification);
  334. Specification specification;
  335. specification.parse(ctx, element);
  336. return specification;
  337. }
  338. void Specification::collect_into(TranslationUnitRef translation_unit)
  339. {
  340. for (auto& clause : m_clauses)
  341. clause->collect_into(translation_unit);
  342. }
  343. void Specification::parse(SpecificationParsingContext& ctx, XML::Node const* element)
  344. {
  345. for (auto const& child : element->as_element().children) {
  346. child->content.visit(
  347. [&](XML::Node::Element const& element) {
  348. if (element.name == tag_emu_intro) {
  349. // Introductory comments are ignored.
  350. } else if (element.name == tag_emu_clause) {
  351. m_clauses.append(SpecificationClause::create(ctx, child));
  352. } else if (element.name == tag_emu_import) {
  353. parse(ctx, child);
  354. } else {
  355. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  356. "<{}> should not be a child of <specification>", element.name);
  357. }
  358. },
  359. [&](XML::Node::Text const&) {
  360. if (!contains_empty_text(child)) {
  361. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  362. "non-empty text node should not be a child of <specification>");
  363. }
  364. },
  365. [&](auto) {});
  366. }
  367. }
  368. SpecParsingStep::SpecParsingStep()
  369. : CompilationStep("parser"sv)
  370. {
  371. }
  372. SpecParsingStep::~SpecParsingStep() = default;
  373. void SpecParsingStep::run(TranslationUnitRef translation_unit)
  374. {
  375. SpecificationParsingContext ctx(translation_unit);
  376. auto filename = translation_unit->filename();
  377. auto file_or_error = Core::File::open_file_or_standard_stream(filename, Core::File::OpenMode::Read);
  378. if (file_or_error.is_error()) {
  379. ctx.diag().fatal_error(Location::global_scope(),
  380. "unable to open '{}': {}", filename, file_or_error.error());
  381. return;
  382. }
  383. auto input_or_error = file_or_error.value()->read_until_eof();
  384. if (input_or_error.is_error()) {
  385. ctx.diag().fatal_error(Location::global_scope(),
  386. "unable to read '{}': {}", filename, input_or_error.error());
  387. return;
  388. }
  389. m_input = input_or_error.release_value();
  390. XML::Parser parser { m_input };
  391. auto document_or_error = parser.parse();
  392. if (document_or_error.is_error()) {
  393. ctx.diag().fatal_error(ctx.file_scope(),
  394. "XML::Parser failed to parse input: {}", document_or_error.error());
  395. ctx.diag().note(ctx.file_scope(),
  396. "since XML::Parser backtracks on error, the message above is likely to point to the "
  397. "first tag in the input - use external XML verifier to find out the exact cause of error");
  398. return;
  399. }
  400. m_document = make<XML::Document>(document_or_error.release_value());
  401. auto const& root = m_document->root();
  402. if (!root.is_element() || root.as_element().name != tag_specification) {
  403. ctx.diag().fatal_error(ctx.location_from_xml_offset(root.offset),
  404. "document root must be <specification> tag");
  405. return;
  406. }
  407. auto specification = Specification::create(ctx, &root);
  408. specification.collect_into(translation_unit);
  409. }
  410. }