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. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "toy/Parser.h" 14 15 #include "llvm/ADT/StringRef.h" 16 #include "llvm/Support/CommandLine.h" 17 #include "llvm/Support/ErrorOr.h" 18 #include "llvm/Support/MemoryBuffer.h" 19 #include "llvm/Support/raw_ostream.h" 20 21 using namespace toy; 22 namespace cl = llvm::cl; 23 24 static cl::opt<std::string> inputFilename(cl::Positional, 25 cl::desc("<input toy file>"), 26 cl::init("-"), 27 cl::value_desc("filename")); 28 namespace { 29 enum Action { None, DumpAST }; 30 } 31 32 static cl::opt<enum Action> 33 emitAction("emit", cl::desc("Select the kind of output desired"), 34 cl::values(clEnumValN(DumpAST, "ast", "output the AST dump"))); 35 36 /// Returns a Toy AST resulting from parsing the file or a nullptr on error. 37 std::unique_ptr<toy::ModuleAST> parseInputFile(llvm::StringRef filename) { 38 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr = 39 llvm::MemoryBuffer::getFileOrSTDIN(filename); 40 if (std::error_code ec = fileOrErr.getError()) { 41 llvm::errs() << "Could not open input file: " << ec.message() << "\n"; 42 return nullptr; 43 } 44 auto buffer = fileOrErr.get()->getBuffer(); 45 LexerBuffer lexer(buffer.begin(), buffer.end(), std::string(filename)); 46 Parser parser(lexer); 47 return parser.parseModule(); 48 } 49 50 int main(int argc, char **argv) { 51 cl::ParseCommandLineOptions(argc, argv, "toy compiler\n"); 52 53 auto moduleAST = parseInputFile(inputFilename); 54 if (!moduleAST) 55 return 1; 56 57 switch (emitAction) { 58 case Action::DumpAST: 59 dump(*moduleAST); 60 return 0; 61 default: 62 llvm::errs() << "No action specified (parsing only?), use -emit=<action>\n"; 63 } 64 65 return 0; 66 } 67