SpecParser.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 tokenization_result = tokenize_tree(ctx, element, true);
  56. if (tokenization_result.is_error()) {
  57. ctx.diag().error(ctx.location_from_xml_offset(tokenization_result.error()->offset()),
  58. "{}", tokenization_result.error()->to_string());
  59. return {};
  60. }
  61. auto [tokens, substeps] = tokenization_result.release_value();
  62. AlgorithmStep result(ctx);
  63. result.m_tokens = move(tokens);
  64. result.m_node = element;
  65. if (substeps) {
  66. // FIXME: Remove this once macOS Lagom CI updates to Clang >= 16.
  67. auto substeps_copy = substeps;
  68. auto step_list = ctx.with_new_step_list_nesting_level([&] {
  69. return AlgorithmStepList::create(ctx, substeps_copy);
  70. });
  71. result.m_substeps = step_list.has_value() ? step_list->tree() : error_tree;
  72. }
  73. auto parse_result = result.parse();
  74. if (parse_result.is_error()) {
  75. ctx.diag().error(ctx.location_from_xml_offset(parse_result.error()->offset()),
  76. "{}", parse_result.error()->to_string());
  77. return {};
  78. }
  79. result.m_expression = parse_result.release_value();
  80. return result;
  81. }
  82. ParseErrorOr<Tree> AlgorithmStep::parse()
  83. {
  84. TextParser parser(m_tokens, m_node);
  85. if (m_substeps)
  86. return parser.parse_step_with_substeps(RefPtr(m_substeps).release_nonnull());
  87. else
  88. return parser.parse_step_without_substeps();
  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. ParseErrorOr<void> SpecificationClause::parse_header(XML::Node const* element)
  211. {
  212. VERIFY(element->as_element().name == tag_h1);
  213. auto tokens = TRY(tokenize_tree(*m_ctx_pointer, element));
  214. TextParser parser(tokens.tokens, element);
  215. m_header = TRY(parser.parse_clause_header());
  216. return {};
  217. }
  218. void SpecificationClause::parse(XML::Node const* element)
  219. {
  220. auto& ctx = context();
  221. u32 child_index = 0;
  222. Optional<NonnullRefPtr<ParseError>> header_parse_error;
  223. for (auto const& child : element->as_element().children) {
  224. child->content.visit(
  225. [&](XML::Node::Element const& element) {
  226. if (child_index == 0) {
  227. if (element.name != tag_h1) {
  228. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  229. "<h1> must be the first child of <emu-clause>");
  230. return;
  231. }
  232. if (auto error = parse_header(child); error.is_error())
  233. header_parse_error = error.release_error();
  234. else
  235. ctx.current_logical_scope().section = MUST(String::from_utf8(m_header.section_number));
  236. } else {
  237. if (element.name == tag_h1) {
  238. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  239. "<h1> can only be the first child of <emu-clause>");
  240. return;
  241. }
  242. if (element.name == tag_emu_clause) {
  243. m_subclauses.append(create(ctx, child));
  244. return;
  245. }
  246. if (header_parse_error.has_value()) {
  247. ctx.diag().warn(ctx.location_from_xml_offset(child->offset),
  248. "node content will be ignored since section header was not parsed successfully");
  249. // TODO: Integrate backtracing parser errors better
  250. ctx.diag().note(ctx.location_from_xml_offset(header_parse_error.value()->offset()),
  251. "{}", header_parse_error.value()->to_string());
  252. header_parse_error.clear();
  253. }
  254. }
  255. ++child_index;
  256. },
  257. [&](XML::Node::Text const&) {
  258. if (!contains_empty_text(child)) {
  259. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  260. "non-empty text node should not be a child of <emu-clause>");
  261. }
  262. },
  263. [&](auto) {});
  264. }
  265. }
  266. bool SpecFunction::post_initialize(XML::Node const* element)
  267. {
  268. VERIFY(element->as_element().name == tag_emu_clause);
  269. auto& ctx = context();
  270. auto maybe_id = get_attribute_by_name(element, attribute_id);
  271. if (!maybe_id.has_value()) {
  272. ctx.diag().error(ctx.location_from_xml_offset(element->offset),
  273. "no id attribute");
  274. } else {
  275. m_id = maybe_id.value();
  276. }
  277. auto maybe_abstract_operation_id = get_attribute_by_name(element, attribute_aoid);
  278. if (maybe_abstract_operation_id.has_value())
  279. m_name = maybe_abstract_operation_id.value();
  280. m_section_number = m_header.section_number;
  281. auto const& [function_name, arguments] = m_header.header.get<ClauseHeader::FunctionDefinition>();
  282. m_arguments = arguments;
  283. if (m_name != function_name) {
  284. ctx.diag().warn(ctx.location_from_xml_offset(element->offset),
  285. "function name in header and <emu-clause>[aoid] do not match");
  286. }
  287. Vector<XML::Node const*> algorithm_nodes;
  288. for (auto const& child : element->as_element().children) {
  289. child->content.visit(
  290. [&](XML::Node::Element const& element) {
  291. if (element.name == tag_h1) {
  292. // Processed in SpecificationClause
  293. } else if (element.name == tag_p) {
  294. ctx.diag().warn(ctx.location_from_xml_offset(child->offset),
  295. "prose is ignored");
  296. } else if (element.name == tag_emu_alg) {
  297. algorithm_nodes.append(child);
  298. } else {
  299. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  300. "<{}> should not be a child of <emu-clause> specifing function"sv, element.name);
  301. }
  302. },
  303. [&](auto const&) {});
  304. }
  305. if (algorithm_nodes.size() != 1) {
  306. ctx.diag().error(ctx.location_from_xml_offset(element->offset),
  307. "<emu-clause> specifing function should have exactly one <emu-alg> child"sv);
  308. return false;
  309. }
  310. auto maybe_algorithm = Algorithm::create(ctx, algorithm_nodes[0]);
  311. if (maybe_algorithm.has_value()) {
  312. m_algorithm = maybe_algorithm.release_value();
  313. return true;
  314. } else {
  315. return false;
  316. }
  317. }
  318. void SpecFunction::do_collect(TranslationUnitRef translation_unit)
  319. {
  320. translation_unit->adopt_function(make_ref_counted<FunctionDefinition>(m_name, m_algorithm.tree(), move(m_arguments)));
  321. }
  322. Specification Specification::create(SpecificationParsingContext& ctx, XML::Node const* element)
  323. {
  324. VERIFY(element->as_element().name == tag_specification);
  325. Specification specification;
  326. specification.parse(ctx, element);
  327. return specification;
  328. }
  329. void Specification::collect_into(TranslationUnitRef translation_unit)
  330. {
  331. for (auto& clause : m_clauses)
  332. clause->collect_into(translation_unit);
  333. }
  334. void Specification::parse(SpecificationParsingContext& ctx, XML::Node const* element)
  335. {
  336. for (auto const& child : element->as_element().children) {
  337. child->content.visit(
  338. [&](XML::Node::Element const& element) {
  339. if (element.name == tag_emu_intro) {
  340. // Introductory comments are ignored.
  341. } else if (element.name == tag_emu_clause) {
  342. m_clauses.append(SpecificationClause::create(ctx, child));
  343. } else if (element.name == tag_emu_import) {
  344. parse(ctx, child);
  345. } else {
  346. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  347. "<{}> should not be a child of <specification>", element.name);
  348. }
  349. },
  350. [&](XML::Node::Text const&) {
  351. if (!contains_empty_text(child)) {
  352. ctx.diag().error(ctx.location_from_xml_offset(child->offset),
  353. "non-empty text node should not be a child of <specification>");
  354. }
  355. },
  356. [&](auto) {});
  357. }
  358. }
  359. SpecParsingStep::SpecParsingStep()
  360. : CompilationStep("parser"sv)
  361. {
  362. }
  363. SpecParsingStep::~SpecParsingStep() = default;
  364. void SpecParsingStep::run(TranslationUnitRef translation_unit)
  365. {
  366. SpecificationParsingContext ctx(translation_unit);
  367. auto filename = translation_unit->filename();
  368. auto file_or_error = Core::File::open_file_or_standard_stream(filename, Core::File::OpenMode::Read);
  369. if (file_or_error.is_error()) {
  370. ctx.diag().fatal_error(Location::global_scope(),
  371. "unable to open '{}': {}", filename, file_or_error.error());
  372. return;
  373. }
  374. auto input_or_error = file_or_error.value()->read_until_eof();
  375. if (input_or_error.is_error()) {
  376. ctx.diag().fatal_error(Location::global_scope(),
  377. "unable to read '{}': {}", filename, input_or_error.error());
  378. return;
  379. }
  380. m_input = input_or_error.release_value();
  381. XML::Parser parser { m_input };
  382. auto document_or_error = parser.parse();
  383. if (document_or_error.is_error()) {
  384. ctx.diag().fatal_error(ctx.file_scope(),
  385. "XML::Parser failed to parse input: {}", document_or_error.error());
  386. ctx.diag().note(ctx.file_scope(),
  387. "since XML::Parser backtracks on error, the message above is likely to point to the "
  388. "first tag in the input - use external XML verifier to find out the exact cause of error");
  389. return;
  390. }
  391. m_document = make<XML::Document>(document_or_error.release_value());
  392. auto const& root = m_document->root();
  393. if (!root.is_element() || root.as_element().name != tag_specification) {
  394. ctx.diag().fatal_error(ctx.location_from_xml_offset(root.offset),
  395. "document root must be <specification> tag");
  396. return;
  397. }
  398. auto specification = Specification::create(ctx, &root);
  399. specification.collect_into(translation_unit);
  400. }
  401. }