Express prelude using Carbon syntax (#955)

This should be clearer, more maintainable, and more scalable than building the prelude AST by hand.
This commit is contained in:
Geoff Romer
2021-11-29 13:56:55 -08:00
committed by GitHub
parent b14c97d0d7
commit 3e188c8562
9 changed files with 106 additions and 38 deletions
+38
View File
@@ -5,12 +5,47 @@
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include "executable_semantics/common/arena.h"
#include "executable_semantics/common/nonnull.h"
#include "executable_semantics/interpreter/exec_program.h"
#include "executable_semantics/syntax/parse.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/InitLLVM.h"
// The Carbon prelude.
//
// TODO: Make this a separate source file that's embedded in the interpreter
// at build time. See https://github.com/bazelbuild/rules_cc/issues/41 for a
// possible mechanism.
static constexpr std::string_view Prelude = R"(
package Carbon api;
// Note that Print is experimental, and not part of an accepted proposal, but
// is included here for printing state in tests.
fn Print(format_str: String) {
__intrinsic_print(format_str);
}
)";
// Adds the Carbon prelude to `declarations`.
static void AddPrelude(
Carbon::Nonnull<Carbon::Arena*> arena,
std::vector<Carbon::Nonnull<Carbon::Declaration*>>* declarations) {
std::variant<Carbon::AST, Carbon::SyntaxErrorCode> parse_result =
ParseFromString(arena, "<prelude>", Prelude, false);
if (std::holds_alternative<Carbon::SyntaxErrorCode>(parse_result)) {
// Try again with tracing, to help diagnose the problem.
ParseFromString(arena, "<prelude>", Prelude, true);
FATAL() << "Failed to parse prelude.";
}
const auto& prelude = std::get<Carbon::AST>(parse_result);
declarations->insert(declarations->begin(), prelude.declarations.begin(),
prelude.declarations.end());
}
auto main(int argc, char* argv[]) -> int {
llvm::setBugReportMsg(
"Please report issues to "
@@ -38,6 +73,9 @@ auto main(int argc, char* argv[]) -> int {
// Diagnostic already reported to std::cerr; this is just a return code.
return *error;
}
auto& ast = std::get<Carbon::AST>(ast_or_error);
AddPrelude(&arena, &ast.declarations);
// Typecheck and run the parsed program.
Carbon::ExecProgram(&arena, std::get<Carbon::AST>(ast_or_error),