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
LLVMErrorHandler(void * UserData,const std::string & Message,bool GenCrashDiag)35 static void LLVMErrorHandler(void *UserData, const std::string &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;
main(int argc,const char ** argv)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 auto Interp = ExitOnErr(clang::Interpreter::create(std::move(CI)));
84 for (const std::string &input : OptInputs) {
85 if (auto Err = Interp->ParseAndExecute(input))
86 llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
87 }
88
89 if (OptInputs.empty()) {
90 llvm::LineEditor LE("clang-repl");
91 // FIXME: Add LE.setListCompleter
92 while (llvm::Optional<std::string> Line = LE.readLine()) {
93 if (*Line == "quit")
94 break;
95 if (auto Err = Interp->ParseAndExecute(*Line))
96 llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
97 }
98 }
99
100 // Our error handler depends on the Diagnostics object, which we're
101 // potentially about to delete. Uninstall the handler now so that any
102 // later errors use the default handling behavior instead.
103 llvm::remove_fatal_error_handler();
104
105 llvm::llvm_shutdown();
106
107 return 0;
108 }
109