[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / mlir / examples / toy / Ch1 / toyc.cpp
blobfb7b484a92fb9f206adfb73827902222ec4fd621
1 //===- toyc.cpp - The Toy Compiler ----------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the entry point for the Toy compiler.
11 //===----------------------------------------------------------------------===//
13 #include "toy/AST.h"
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"
22 #include <memory>
23 #include <string>
24 #include <system_error>
26 using namespace toy;
27 namespace cl = llvm::cl;
29 static cl::opt<std::string> inputFilename(cl::Positional,
30 cl::desc("<input toy file>"),
31 cl::init("-"),
32 cl::value_desc("filename"));
33 namespace {
34 enum Action { None, DumpAST };
35 } // namespace
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";
47 return nullptr;
49 auto buffer = fileOrErr.get()->getBuffer();
50 LexerBuffer lexer(buffer.begin(), buffer.end(), std::string(filename));
51 Parser parser(lexer);
52 return parser.parseModule();
55 int main(int argc, char **argv) {
56 cl::ParseCommandLineOptions(argc, argv, "toy compiler\n");
58 auto moduleAST = parseInputFile(inputFilename);
59 if (!moduleAST)
60 return 1;
62 switch (emitAction) {
63 case Action::DumpAST:
64 dump(*moduleAST);
65 return 0;
66 default:
67 llvm::errs() << "No action specified (parsing only?), use -emit=<action>\n";
70 return 0;