exec_program.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "executable_semantics/interpreter/exec_program.h"
  5. #include "common/check.h"
  6. #include "common/ostream.h"
  7. #include "executable_semantics/common/arena.h"
  8. #include "executable_semantics/common/tracing_flag.h"
  9. #include "executable_semantics/interpreter/interpreter.h"
  10. #include "executable_semantics/interpreter/type_checker.h"
  11. namespace Carbon {
  12. // Adds builtins, currently only Print(). Note Print() is experimental, not
  13. // standardized, but is made available for printing state in tests.
  14. static void AddIntrinsics(Ptr<Arena> arena,
  15. std::vector<Ptr<const Declaration>>* declarations) {
  16. SourceLocation loc("<intrinsic>", 0);
  17. std::vector<TuplePattern::Field> print_fields = {TuplePattern::Field(
  18. "0",
  19. arena->New<BindingPattern>(
  20. loc, "format_str",
  21. arena->New<ExpressionPattern>(arena->New<StringTypeLiteral>(loc))))};
  22. auto print_return =
  23. arena->New<Return>(loc,
  24. arena->New<IntrinsicExpression>(
  25. IntrinsicExpression::IntrinsicKind::Print),
  26. false);
  27. auto print = arena->New<FunctionDeclaration>(arena->New<FunctionDefinition>(
  28. loc, "Print", std::vector<GenericBinding>(),
  29. arena->New<TuplePattern>(loc, print_fields),
  30. arena->New<ExpressionPattern>(arena->New<TupleLiteral>(loc)),
  31. /*is_omitted_return_type=*/false, print_return));
  32. declarations->insert(declarations->begin(), print);
  33. }
  34. void ExecProgram(Ptr<Arena> arena, AST ast) {
  35. AddIntrinsics(arena, &ast.declarations);
  36. if (tracing_output) {
  37. llvm::outs() << "********** source program **********\n";
  38. for (const auto decl : ast.declarations) {
  39. llvm::outs() << *decl;
  40. }
  41. llvm::outs() << "********** type checking **********\n";
  42. }
  43. TypeChecker type_checker(arena);
  44. TypeChecker::TypeCheckContext p = type_checker.TopLevel(ast.declarations);
  45. TypeEnv top = p.types;
  46. Env ct_top = p.values;
  47. std::vector<Ptr<const Declaration>> new_decls;
  48. for (const auto decl : ast.declarations) {
  49. new_decls.push_back(type_checker.MakeTypeChecked(decl, top, ct_top));
  50. }
  51. if (tracing_output) {
  52. llvm::outs() << "\n";
  53. llvm::outs() << "********** type checking complete **********\n";
  54. for (const auto decl : new_decls) {
  55. llvm::outs() << *decl;
  56. }
  57. llvm::outs() << "********** starting execution **********\n";
  58. }
  59. int result = Interpreter(arena).InterpProgram(new_decls);
  60. llvm::outs() << "result: " << result << "\n";
  61. }
  62. } // namespace Carbon