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