CppASTConverter.cpp 8.8 KB

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