1 //===--- tools/clang-repl/ClangRepl.cpp - clang-repl - the Clang REPL -----===//
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 a REPL tool on top of clang.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Interpreter/Interpreter.h"
17 
18 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
19 #include "llvm/LineEditor/LineEditor.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ManagedStatic.h" // llvm_shutdown
22 #include "llvm/Support/Signals.h"
23 #include "llvm/Support/TargetSelect.h" // llvm::Initialize*
24 
25 static llvm::cl::list<std::string>
26     ClangArgs("Xcc", llvm::cl::ZeroOrMore,
27               llvm::cl::desc("Argument to pass to the CompilerInvocation"),
28               llvm::cl::CommaSeparated);
29 static llvm::cl::opt<bool> OptHostSupportsJit("host-supports-jit",
30                                               llvm::cl::Hidden);
31 static llvm::cl::list<std::string> OptInputs(llvm::cl::Positional,
32                                              llvm::cl::ZeroOrMore,
33                                              llvm::cl::desc("[code to run]"));
34 
35 static void LLVMErrorHandler(void *UserData, const char *Message,
36                              bool GenCrashDiag) {
37   auto &Diags = *static_cast<clang::DiagnosticsEngine *>(UserData);
38 
39   Diags.Report(clang::diag::err_fe_error_backend) << Message;
40 
41   // Run the interrupt handlers to make sure any special cleanups get done, in
42   // particular that we remove files registered with RemoveFileOnSignal.
43   llvm::sys::RunInterruptHandlers();
44 
45   // We cannot recover from llvm errors.  When reporting a fatal error, exit
46   // with status 70 to generate crash diagnostics.  For BSD systems this is
47   // defined as an internal software error. Otherwise, exit with status 1.
48 
49   exit(GenCrashDiag ? 70 : 1);
50 }
51 
52 llvm::ExitOnError ExitOnErr;
53 int main(int argc, const char **argv) {
54   ExitOnErr.setBanner("clang-repl: ");
55   llvm::cl::ParseCommandLineOptions(argc, argv);
56 
57   std::vector<const char *> ClangArgv(ClangArgs.size());
58   std::transform(ClangArgs.begin(), ClangArgs.end(), ClangArgv.begin(),
59                  [](const std::string &s) -> const char * { return s.data(); });
60   llvm::InitializeNativeTarget();
61   llvm::InitializeNativeTargetAsmPrinter();
62 
63   if (OptHostSupportsJit) {
64     auto J = llvm::orc::LLJITBuilder().create();
65     if (J)
66       llvm::outs() << "true\n";
67     else {
68       llvm::consumeError(J.takeError());
69       llvm::outs() << "false\n";
70     }
71     return 0;
72   }
73 
74   // FIXME: Investigate if we could use runToolOnCodeWithArgs from tooling. It
75   // can replace the boilerplate code for creation of the compiler instance.
76   auto CI = ExitOnErr(clang::IncrementalCompilerBuilder::create(ClangArgv));
77 
78   // Set an error handler, so that any LLVM backend diagnostics go through our
79   // error handler.
80   llvm::install_fatal_error_handler(LLVMErrorHandler,
81                                     static_cast<void *>(&CI->getDiagnostics()));
82 
83   // Load any requested plugins.
84   CI->LoadRequestedPlugins();
85 
86   auto Interp = ExitOnErr(clang::Interpreter::create(std::move(CI)));
87   for (const std::string &input : OptInputs) {
88     if (auto Err = Interp->ParseAndExecute(input))
89       llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
90   }
91 
92   if (OptInputs.empty()) {
93     llvm::LineEditor LE("clang-repl");
94     // FIXME: Add LE.setListCompleter
95     while (llvm::Optional<std::string> Line = LE.readLine()) {
96       if (*Line == "quit")
97         break;
98       if (auto Err = Interp->ParseAndExecute(*Line))
99         llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
100     }
101   }
102 
103   // Our error handler depends on the Diagnostics object, which we're
104   // potentially about to delete. Uninstall the handler now so that any
105   // later errors use the default handling behavior instead.
106   llvm::remove_fatal_error_handler();
107 
108   llvm::llvm_shutdown();
109 
110   return 0;
111 }
112