brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.3 KiB · b9f3a2d Raw
73 lines · cpp
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-exception6//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 26using namespace toy;27namespace cl = llvm::cl;28 29static cl::opt<std::string> inputFilename(cl::Positional,30                                          cl::desc("<input toy file>"),31                                          cl::init("-"),32                                          cl::value_desc("filename"));33namespace {34enum Action { None, DumpAST };35} // namespace36 37static 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.42static std::unique_ptr<toy::ModuleAST>43parseInputFile(llvm::StringRef filename) {44  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =45      llvm::MemoryBuffer::getFileOrSTDIN(filename);46  if (std::error_code ec = fileOrErr.getError()) {47    llvm::errs() << "Could not open input file: " << ec.message() << "\n";48    return nullptr;49  }50  auto buffer = fileOrErr.get()->getBuffer();51  LexerBuffer lexer(buffer.begin(), buffer.end(), std::string(filename));52  Parser parser(lexer);53  return parser.parseModule();54}55 56int main(int argc, char **argv) {57  cl::ParseCommandLineOptions(argc, argv, "toy compiler\n");58 59  auto moduleAST = parseInputFile(inputFilename);60  if (!moduleAST)61    return 1;62 63  switch (emitAction) {64  case Action::DumpAST:65    dump(*moduleAST);66    return 0;67  default:68    llvm::errs() << "No action specified (parsing only?), use -emit=<action>\n";69  }70 71  return 0;72}73