exec_program.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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(
  15. Nonnull<Arena*> arena,
  16. std::vector<Nonnull<const Declaration*>>* declarations) {
  17. SourceLocation loc("<intrinsic>", 0);
  18. std::vector<TuplePattern::Field> print_fields = {TuplePattern::Field(
  19. "0",
  20. arena->New<BindingPattern>(
  21. loc, "format_str",
  22. arena->New<ExpressionPattern>(arena->New<StringTypeLiteral>(loc))))};
  23. auto print_return =
  24. arena->New<Return>(loc,
  25. arena->New<IntrinsicExpression>(
  26. IntrinsicExpression::IntrinsicKind::Print),
  27. false);
  28. auto print = arena->New<FunctionDeclaration>(arena->New<FunctionDefinition>(
  29. loc, "Print", std::vector<GenericBinding>(),
  30. arena->New<TuplePattern>(loc, print_fields),
  31. arena->New<ExpressionPattern>(arena->New<TupleLiteral>(loc)),
  32. /*is_omitted_return_type=*/false, print_return));
  33. declarations->insert(declarations->begin(), print);
  34. }
  35. void ExecProgram(Nonnull<Arena*> arena, AST ast) {
  36. AddIntrinsics(arena, &ast.declarations);
  37. if (tracing_output) {
  38. llvm::outs() << "********** source program **********\n";
  39. for (const auto decl : ast.declarations) {
  40. llvm::outs() << *decl;
  41. }
  42. llvm::outs() << "********** type checking **********\n";
  43. }
  44. TypeChecker type_checker(arena);
  45. TypeChecker::TypeCheckContext p = type_checker.TopLevel(ast.declarations);
  46. TypeEnv top = p.types;
  47. Env ct_top = p.values;
  48. std::vector<Nonnull<const Declaration*>> new_decls;
  49. for (const auto decl : ast.declarations) {
  50. new_decls.push_back(type_checker.MakeTypeChecked(decl, top, ct_top));
  51. }
  52. if (tracing_output) {
  53. llvm::outs() << "\n";
  54. llvm::outs() << "********** type checking complete **********\n";
  55. for (const auto decl : new_decls) {
  56. llvm::outs() << *decl;
  57. }
  58. llvm::outs() << "********** starting execution **********\n";
  59. }
  60. int result = Interpreter(arena).InterpProgram(new_decls);
  61. llvm::outs() << "result: " << result << "\n";
  62. }
  63. } // namespace Carbon