[executable semantics] Add Syntax driver (#362)

Slowly bringing this into line with Bison's C++ example parser
so we can use strong semantic values for symbols rather than
leaking pointers.  First step is to thread a `ParseAndLexContext` 
object through the whole syntactic analysis state, like the 
example has.  In the example, it's called `driver`.

Co-authored-by: Geoff Romer <gromer@google.com>
This commit is contained in:
Dave Abrahams
2021-03-09 19:46:30 -08:00
committed by GitHub
co-authored by Geoff Romer
parent 5375c01056
commit 07a37933c6
12 changed files with 187 additions and 50 deletions
+12 -29
View File
@@ -6,50 +6,33 @@
#include <cstring>
#include <iostream>
#include "executable_semantics/syntax/parser.h"
#include "executable_semantics/syntax/parse.h"
#include "executable_semantics/syntax/syntax_helpers.h"
#include "executable_semantics/tracing_flag.h"
#include "llvm/Support/CommandLine.h"
extern FILE* yyin;
int main(int argc, char* argv[]) {
// yydebug = 1;
using llvm::cl::desc;
using llvm::cl::opt;
opt<bool> quiet_option("quiet", desc("Disable tracing"));
opt<std::string> input_filename(llvm::cl::Positional, desc("<input file>"));
llvm::cl::ParseCommandLineOptions(argc, argv);
opt<bool> quietOption("quiet", desc("Disable tracing"));
opt<std::string> inputFileName(llvm::cl::Positional, desc("<input file>"),
llvm::cl::Required);
if (input_filename.getNumOccurrences() > 0) {
Carbon::input_filename = input_filename.c_str();
yyin = fopen(input_filename.c_str(), "r");
if (yyin == nullptr) {
std::cerr << "Error opening '" << input_filename
<< "': " << strerror(errno) << std::endl;
return 1;
}
}
if (quiet_option) {
llvm::cl::ParseCommandLineOptions(argc, argv);
if (quietOption) {
Carbon::tracing_output = false;
}
// No AST yet
std::optional<Carbon::AST> parsedInput = std::nullopt;
std::variant<Carbon::AST, Carbon::SyntaxErrorCode> astOrError =
Carbon::parse(inputFileName);
// Parse and handle syntax errors
auto syntaxErrorCode = yyparse(parsedInput);
if (syntaxErrorCode != 0) {
return syntaxErrorCode;
}
if (parsedInput == std::nullopt) {
std::cerr << "Internal error: parser validated syntax yet didn't produce "
"an AST.\n";
return 1;
if (auto* error = std::get_if<Carbon::SyntaxErrorCode>(&astOrError)) {
// Diagnostic already reported to std::cerr; this is just a return code.
return *error;
}
// Typecheck and run the parsed program.
Carbon::ExecProgram(*parsedInput);
Carbon::ExecProgram(std::get<Carbon::AST>(astOrError));
}