1 //===- toyc.cpp - The Toy Compiler ----------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the entry point for the Toy compiler.
11 //===----------------------------------------------------------------------===//
14 #include "toy/Lexer.h"
15 #include "toy/Parser.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/ErrorOr.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/raw_ostream.h"
24 #include <system_error>
27 namespace cl
= llvm::cl
;
29 static cl::opt
<std::string
> inputFilename(cl::Positional
,
30 cl::desc("<input toy file>"),
32 cl::value_desc("filename"));
34 enum Action
{ None
, DumpAST
};
37 static cl::opt
<enum Action
>
38 emitAction("emit", cl::desc("Select the kind of output desired"),
39 cl::values(clEnumValN(DumpAST
, "ast", "output the AST dump")));
41 /// Returns a Toy AST resulting from parsing the file or a nullptr on error.
42 std::unique_ptr
<toy::ModuleAST
> parseInputFile(llvm::StringRef filename
) {
43 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> fileOrErr
=
44 llvm::MemoryBuffer::getFileOrSTDIN(filename
);
45 if (std::error_code ec
= fileOrErr
.getError()) {
46 llvm::errs() << "Could not open input file: " << ec
.message() << "\n";
49 auto buffer
= fileOrErr
.get()->getBuffer();
50 LexerBuffer
lexer(buffer
.begin(), buffer
.end(), std::string(filename
));
52 return parser
.parseModule();
55 int main(int argc
, char **argv
) {
56 cl::ParseCommandLineOptions(argc
, argv
, "toy compiler\n");
58 auto moduleAST
= parseInputFile(inputFilename
);
67 llvm::errs() << "No action specified (parsing only?), use -emit=<action>\n";