| 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/AST.h" |
| 14 | #include "toy/Lexer.h" |
| 15 | #include "toy/Parser.h" |
| 16 | |
| 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> |
| 25 | |
| 26 | using namespace toy; |
| 27 | namespace cl = llvm::cl; |
| 28 | |
| 29 | static cl::opt<std::string> inputFilename(cl::Positional, |
| 30 | cl::desc("<input toy file>" ), |
| 31 | cl::init(Val: "-" ), |
| 32 | cl::value_desc("filename" )); |
| 33 | namespace { |
| 34 | enum Action { None, DumpAST }; |
| 35 | } // namespace |
| 36 | |
| 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" ))); |
| 40 | |
| 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: filename); |
| 45 | if (std::error_code ec = fileOrErr.getError()) { |
| 46 | llvm::errs() << "Could not open input file: " << ec.message() << "\n" ; |
| 47 | return nullptr; |
| 48 | } |
| 49 | auto buffer = fileOrErr.get()->getBuffer(); |
| 50 | LexerBuffer lexer(buffer.begin(), buffer.end(), std::string(filename)); |
| 51 | Parser parser(lexer); |
| 52 | return parser.parseModule(); |
| 53 | } |
| 54 | |
| 55 | int main(int argc, char **argv) { |
| 56 | cl::ParseCommandLineOptions(argc, argv, Overview: "toy compiler\n" ); |
| 57 | |
| 58 | auto moduleAST = parseInputFile(filename: inputFilename); |
| 59 | if (!moduleAST) |
| 60 | return 1; |
| 61 | |
| 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" ; |
| 68 | } |
| 69 | |
| 70 | return 0; |
| 71 | } |
| 72 | |