CppASTConverter.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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/SpecificationParsing.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. VERIFY(literal.value().to_number<i64>().has_value());
  107. return make_ref_counted<MathematicalConstant>(MUST(Crypto::BigFraction::from_string(literal.value())));
  108. }
  109. template<>
  110. NullableTree CppASTConverter::convert_node(Cpp::StringLiteral const& literal)
  111. {
  112. return make_ref_counted<StringLiteral>(literal.value());
  113. }
  114. template<>
  115. NullableTree CppASTConverter::convert_node(Cpp::BinaryExpression const& expression)
  116. {
  117. static constexpr auto operator_translation = []() consteval {
  118. Array<BinaryOperator, to_underlying(Cpp::BinaryOp::Arrow) + 1> table;
  119. #define ASSIGN_TRANSLATION(cpp_name, our_name) \
  120. table[to_underlying(Cpp::BinaryOp::cpp_name)] = BinaryOperator::our_name
  121. ASSIGN_TRANSLATION(Addition, Plus);
  122. ASSIGN_TRANSLATION(Subtraction, Minus);
  123. ASSIGN_TRANSLATION(Multiplication, Multiplication);
  124. ASSIGN_TRANSLATION(Division, Division);
  125. ASSIGN_TRANSLATION(Modulo, Invalid);
  126. ASSIGN_TRANSLATION(GreaterThan, CompareGreater);
  127. ASSIGN_TRANSLATION(GreaterThanEquals, Invalid);
  128. ASSIGN_TRANSLATION(LessThan, CompareLess);
  129. ASSIGN_TRANSLATION(LessThanEquals, Invalid);
  130. ASSIGN_TRANSLATION(BitwiseAnd, Invalid);
  131. ASSIGN_TRANSLATION(BitwiseOr, Invalid);
  132. ASSIGN_TRANSLATION(BitwiseXor, Invalid);
  133. ASSIGN_TRANSLATION(LeftShift, Invalid);
  134. ASSIGN_TRANSLATION(RightShift, Invalid);
  135. ASSIGN_TRANSLATION(EqualsEquals, CompareEqual);
  136. ASSIGN_TRANSLATION(NotEqual, CompareNotEqual);
  137. ASSIGN_TRANSLATION(LogicalOr, Invalid);
  138. ASSIGN_TRANSLATION(LogicalAnd, Invalid);
  139. ASSIGN_TRANSLATION(Arrow, Invalid);
  140. #undef ASSIGN_TRANSLATION
  141. return table;
  142. }();
  143. auto translated_operator = operator_translation[to_underlying(expression.op())];
  144. // TODO: Print nicer error.
  145. VERIFY(translated_operator != BinaryOperator::Invalid);
  146. return make_ref_counted<BinaryOperation>(translated_operator, as_tree(expression.lhs()), as_tree(expression.rhs()));
  147. }
  148. NullableTree CppASTConverter::as_nullable_tree(Cpp::Statement const* statement)
  149. {
  150. static Tree unknown_ast_node_error
  151. = make_ref_counted<ErrorNode>("Encountered unknown C++ AST node"sv);
  152. Optional<NullableTree> result;
  153. auto dispatch_convert_if_one_of = [&]<typename... Ts> {
  154. (([&]<typename T> {
  155. if (result.has_value())
  156. return;
  157. auto casted_ptr = dynamic_cast<T const*>(statement);
  158. if (casted_ptr != nullptr)
  159. result = convert_node<T>(*casted_ptr);
  160. }).template operator()<Ts>(),
  161. ...);
  162. };
  163. dispatch_convert_if_one_of.operator()<
  164. Cpp::VariableDeclaration,
  165. Cpp::ReturnStatement,
  166. Cpp::FunctionCall,
  167. Cpp::Name,
  168. Cpp::IfStatement,
  169. Cpp::BlockStatement,
  170. Cpp::AssignmentExpression,
  171. Cpp::NumericLiteral,
  172. Cpp::StringLiteral,
  173. Cpp::BinaryExpression>();
  174. if (result.has_value())
  175. return *result;
  176. return unknown_ast_node_error;
  177. }
  178. Tree CppASTConverter::as_tree(Cpp::Statement const* statement)
  179. {
  180. static Tree empty_tree_error
  181. = make_ref_counted<ErrorNode>("AST conversion unexpectedly produced empty tree"sv);
  182. auto result = as_nullable_tree(statement);
  183. if (result)
  184. return result.release_nonnull();
  185. return empty_tree_error;
  186. }
  187. Tree CppASTConverter::as_possibly_empty_tree(Cpp::Statement const* statement)
  188. {
  189. auto result = as_nullable_tree(statement);
  190. if (result)
  191. return result.release_nonnull();
  192. return make_ref_counted<TreeList>(Vector<Tree> {});
  193. }
  194. CppParsingStep::CppParsingStep()
  195. : CompilationStep("parser"sv)
  196. {
  197. }
  198. CppParsingStep::~CppParsingStep() = default;
  199. void CppParsingStep::run(TranslationUnitRef translation_unit)
  200. {
  201. auto filename = translation_unit->filename();
  202. auto file = Core::File::open_file_or_standard_stream(filename, Core::File::OpenMode::Read).release_value_but_fixme_should_propagate_errors();
  203. m_input = file->read_until_eof().release_value_but_fixme_should_propagate_errors();
  204. Cpp::Preprocessor preprocessor { filename, m_input };
  205. m_parser = adopt_own_if_nonnull(new Cpp::Parser { preprocessor.process_and_lex(), filename });
  206. auto cpp_translation_unit = m_parser->parse();
  207. VERIFY(m_parser->errors().is_empty());
  208. for (auto const& declaration : cpp_translation_unit->declarations()) {
  209. if (declaration->is_function()) {
  210. auto const* cpp_function = AK::verify_cast<Cpp::FunctionDeclaration>(declaration.ptr());
  211. translation_unit->adopt_function(CppASTConverter(cpp_function).convert());
  212. }
  213. }
  214. }
  215. }