syntax_helpers.cpp 2.5 KB

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