CppASTConverter.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. * Copyright (c) 2023, Dan Klishch <danilklishch@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/File.h>
  7. #include "Function.h"
  8. #include "Parser/CppASTConverter.h"
  9. #include "Parser/SpecParser.h"
  10. namespace JSSpecCompiler {
  11. NonnullRefPtr<FunctionDefinition> CppASTConverter::convert()
  12. {
  13. StringView name = m_function->name()->full_name();
  14. Vector<Tree> toplevel_statements;
  15. for (auto const& statement : m_function->definition()->statements()) {
  16. auto maybe_tree = as_nullable_tree(statement);
  17. if (maybe_tree)
  18. toplevel_statements.append(maybe_tree.release_nonnull());
  19. }
  20. auto tree = make_ref_counted<TreeList>(move(toplevel_statements));
  21. return make_ref_counted<FunctionDefinition>(name, tree);
  22. }
  23. template<>
  24. NullableTree CppASTConverter::convert_node(Cpp::VariableDeclaration const& variable_declaration)
  25. {
  26. static Tree variable_declaration_present_error
  27. = make_ref_counted<ErrorNode>("Encountered variable declaration with initial value"sv);
  28. if (variable_declaration.initial_value() != nullptr)
  29. return variable_declaration_present_error;
  30. return nullptr;
  31. }
  32. template<>
  33. NullableTree CppASTConverter::convert_node(Cpp::ReturnStatement const& return_statement)
  34. {
  35. return make_ref_counted<ReturnNode>(as_tree(return_statement.value()));
  36. }
  37. template<>
  38. NullableTree CppASTConverter::convert_node(Cpp::FunctionCall const& function_call)
  39. {
  40. Vector<Tree> arguments;
  41. for (auto const& argument : function_call.arguments())
  42. arguments.append(as_tree(argument));
  43. return make_ref_counted<FunctionCall>(as_tree(function_call.callee()), move(arguments));
  44. }
  45. template<>
  46. NullableTree CppASTConverter::convert_node(Cpp::Name const& name)
  47. {
  48. return make_ref_counted<UnresolvedReference>(name.full_name());
  49. }
  50. template<>
  51. NullableTree CppASTConverter::convert_node(Cpp::IfStatement const& if_statement)
  52. {
  53. // NOTE: This is so complicated since we probably want to test IfBranchMergingPass, which
  54. // expects standalone `IfBranch` and `ElseIfBranch` nodes.
  55. Vector<Tree> trees;
  56. Cpp::IfStatement const* current = &if_statement;
  57. while (true) {
  58. auto predicate = as_tree(current->predicate());
  59. auto then_branch = as_possibly_empty_tree(current->then_statement());
  60. if (trees.is_empty())
  61. trees.append(make_ref_counted<IfBranch>(predicate, then_branch));
  62. else
  63. trees.append(make_ref_counted<ElseIfBranch>(predicate, then_branch));
  64. auto else_statement = dynamic_cast<Cpp::IfStatement const*>(current->else_statement());
  65. if (else_statement)
  66. current = else_statement;
  67. else
  68. break;
  69. }
  70. auto else_statement = current->else_statement();
  71. if (else_statement)
  72. trees.append(make_ref_counted<ElseIfBranch>(
  73. nullptr, as_possibly_empty_tree(else_statement)));
  74. return make_ref_counted<TreeList>(move(trees));
  75. }
  76. template<>
  77. NullableTree CppASTConverter::convert_node(Cpp::BlockStatement const& block)
  78. {
  79. Vector<Tree> statements;
  80. for (auto const& statement : block.statements()) {
  81. auto maybe_tree = as_nullable_tree(statement);
  82. if (maybe_tree)
  83. statements.append(maybe_tree.release_nonnull());
  84. }
  85. return make_ref_counted<TreeList>(move(statements));
  86. }
  87. template<>
  88. NullableTree CppASTConverter::convert_node(Cpp::AssignmentExpression const& assignment)
  89. {
  90. // NOTE: Later stages of the compilation process basically treat `BinaryOperator::Declaration`
  91. // the same as `BinaryOperator::Assignment`, so variable shadowing is impossible. The only
  92. // difference in their semantics is that "declarations" define names of local variables.
  93. // Since we are effectively ignoring actual C++ variable declarations, we need to define
  94. // locals somewhere else. Using "declarations" instead of "assignments" here does this job
  95. // cleanly.
  96. return make_ref_counted<BinaryOperation>(
  97. BinaryOperator::Declaration, as_tree(assignment.lhs()), as_tree(assignment.rhs()));
  98. }
  99. template<>
  100. NullableTree CppASTConverter::convert_node(Cpp::NumericLiteral const& literal)
  101. {
  102. // TODO: Numerical literals are not limited to i64.
  103. return make_ref_counted<MathematicalConstant>(literal.value().to_number<i64>().value());
  104. }
  105. template<>
  106. NullableTree CppASTConverter::convert_node(Cpp::StringLiteral const& literal)
  107. {
  108. return make_ref_counted<StringLiteral>(literal.value());
  109. }
  110. template<>
  111. NullableTree CppASTConverter::convert_node(Cpp::BinaryExpression const& expression)
  112. {
  113. static constexpr auto operator_translation = []() consteval {
  114. Array<BinaryOperator, to_underlying(Cpp::BinaryOp::Arrow) + 1> table;
  115. #define ASSIGN_TRANSLATION(cpp_name, our_name) \
  116. table[to_underlying(Cpp::BinaryOp::cpp_name)] = BinaryOperator::our_name
  117. ASSIGN_TRANSLATION(Addition, Plus);
  118. ASSIGN_TRANSLATION(Subtraction, Minus);
  119. ASSIGN_TRANSLATION(Multiplication, Multiplication);
  120. ASSIGN_TRANSLATION(Division, Division);
  121. ASSIGN_TRANSLATION(Modulo, Invalid);
  122. ASSIGN_TRANSLATION(GreaterThan, CompareGreater);
  123. ASSIGN_TRANSLATION(GreaterThanEquals, Invalid);
  124. ASSIGN_TRANSLATION(LessThan, CompareLess);
  125. ASSIGN_TRANSLATION(LessThanEquals, Invalid);
  126. ASSIGN_TRANSLATION(BitwiseAnd, Invalid);
  127. ASSIGN_TRANSLATION(BitwiseOr, Invalid);
  128. ASSIGN_TRANSLATION(BitwiseXor, Invalid);
  129. ASSIGN_TRANSLATION(LeftShift, Invalid);
  130. ASSIGN_TRANSLATION(RightShift, Invalid);
  131. ASSIGN_TRANSLATION(EqualsEquals, CompareEqual);
  132. ASSIGN_TRANSLATION(NotEqual, CompareNotEqual);
  133. ASSIGN_TRANSLATION(LogicalOr, Invalid);
  134. ASSIGN_TRANSLATION(LogicalAnd, Invalid);
  135. ASSIGN_TRANSLATION(Arrow, Invalid);
  136. #undef ASSIGN_TRANSLATION
  137. return table;
  138. }();
  139. auto translated_operator = operator_translation[to_underlying(expression.op())];
  140. // TODO: Print nicer error.
  141. VERIFY(translated_operator != BinaryOperator::Invalid);
  142. return make_ref_counted<BinaryOperation>(translated_operator, as_tree(expression.lhs()), as_tree(expression.rhs()));
  143. }
  144. NullableTree CppASTConverter::as_nullable_tree(Cpp::Statement const* statement)
  145. {
  146. static Tree unknown_ast_node_error
  147. = make_ref_counted<ErrorNode>("Encountered unknown C++ AST node"sv);
  148. Optional<NullableTree> result;
  149. auto dispatch_convert_if_one_of = [&]<typename... Ts> {
  150. (([&]<typename T> {
  151. if (result.has_value())
  152. return;
  153. auto casted_ptr = dynamic_cast<T const*>(statement);
  154. if (casted_ptr != nullptr)
  155. result = convert_node<T>(*casted_ptr);
  156. }).template operator()<Ts>(),
  157. ...);
  158. };
  159. dispatch_convert_if_one_of.operator()<
  160. Cpp::VariableDeclaration,
  161. Cpp::ReturnStatement,
  162. Cpp::FunctionCall,
  163. Cpp::Name,
  164. Cpp::IfStatement,
  165. Cpp::BlockStatement,
  166. Cpp::AssignmentExpression,
  167. Cpp::NumericLiteral,
  168. Cpp::StringLiteral,
  169. Cpp::BinaryExpression>();
  170. if (result.has_value())
  171. return *result;
  172. return unknown_ast_node_error;
  173. }
  174. Tree CppASTConverter::as_tree(Cpp::Statement const* statement)
  175. {
  176. static Tree empty_tree_error
  177. = make_ref_counted<ErrorNode>("AST conversion unexpectedly produced empty tree"sv);
  178. auto result = as_nullable_tree(statement);
  179. if (result)
  180. return result.release_nonnull();
  181. return empty_tree_error;
  182. }
  183. Tree CppASTConverter::as_possibly_empty_tree(Cpp::Statement const* statement)
  184. {
  185. auto result = as_nullable_tree(statement);
  186. if (result)
  187. return result.release_nonnull();
  188. return make_ref_counted<TreeList>(Vector<Tree> {});
  189. }
  190. CppParsingStep::CppParsingStep()
  191. : CompilationStep("parser"sv)
  192. {
  193. }
  194. CppParsingStep::~CppParsingStep() = default;
  195. void CppParsingStep::run(TranslationUnitRef translation_unit)
  196. {
  197. auto filename = translation_unit->filename;
  198. auto file = Core::File::open_file_or_standard_stream(filename, Core::File::OpenMode::Read).release_value_but_fixme_should_propagate_errors();
  199. m_input = file->read_until_eof().release_value_but_fixme_should_propagate_errors();
  200. Cpp::Preprocessor preprocessor { filename, m_input };
  201. m_parser = adopt_own_if_nonnull(new Cpp::Parser { preprocessor.process_and_lex(), filename });
  202. auto cpp_translation_unit = m_parser->parse();
  203. VERIFY(m_parser->errors().is_empty());
  204. for (auto const& declaration : cpp_translation_unit->declarations()) {
  205. if (declaration->is_function()) {
  206. auto const* cpp_function = AK::verify_cast<Cpp::FunctionDeclaration>(declaration.ptr());
  207. translation_unit->adopt_function(CppASTConverter(cpp_function).convert());
  208. }
  209. }
  210. }
  211. }