1//===-- ClangExpressionParser.cpp -----------------------------------------===//
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#include "clang/AST/ASTContext.h"
10#include "clang/AST/ASTDiagnostic.h"
11#include "clang/AST/ExternalASTSource.h"
12#include "clang/AST/PrettyPrinter.h"
13#include "clang/Basic/Builtins.h"
14#include "clang/Basic/DarwinSDKInfo.h"
15#include "clang/Basic/DiagnosticIDs.h"
16#include "clang/Basic/IdentifierTable.h"
17#include "clang/Basic/SourceLocation.h"
18#include "clang/Basic/TargetInfo.h"
19#include "clang/Basic/Version.h"
20#include "clang/CodeGen/CodeGenAction.h"
21#include "clang/CodeGen/ModuleBuilder.h"
22#include "clang/Edit/Commit.h"
23#include "clang/Edit/EditedSource.h"
24#include "clang/Edit/EditsReceiver.h"
25#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/CompilerInvocation.h"
27#include "clang/Frontend/FrontendActions.h"
28#include "clang/Frontend/FrontendDiagnostic.h"
29#include "clang/Frontend/FrontendPluginRegistry.h"
30#include "clang/Frontend/TextDiagnostic.h"
31#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
33#include "clang/Lex/Preprocessor.h"
34#include "clang/Parse/ParseAST.h"
35#include "clang/Rewrite/Core/Rewriter.h"
36#include "clang/Rewrite/Frontend/FrontendActions.h"
37#include "clang/Sema/CodeCompleteConsumer.h"
38#include "clang/Sema/Sema.h"
39#include "clang/Sema/SemaConsumer.h"
40
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ExecutionEngine/ExecutionEngine.h"
43#include "llvm/Support/CrashRecoveryContext.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Support/Error.h"
46#include "llvm/Support/FileSystem.h"
47#include "llvm/Support/TargetSelect.h"
48#include "llvm/TargetParser/Triple.h"
49
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Module.h"
52#include "llvm/Support/DynamicLibrary.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/Signals.h"
56#include "llvm/TargetParser/Host.h"
57
58#include "ClangDiagnostic.h"
59#include "ClangExpressionParser.h"
60#include "ClangUserExpression.h"
61
62#include "ASTUtils.h"
63#include "ClangASTSource.h"
64#include "ClangExpressionDeclMap.h"
65#include "ClangExpressionHelper.h"
66#include "ClangHost.h"
67#include "ClangModulesDeclVendor.h"
68#include "ClangPersistentVariables.h"
69#include "IRDynamicChecks.h"
70#include "IRForTarget.h"
71#include "ModuleDependencyCollector.h"
72
73#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
74#include "lldb/Core/Debugger.h"
75#include "lldb/Core/Disassembler.h"
76#include "lldb/Core/Module.h"
77#include "lldb/Expression/IRExecutionUnit.h"
78#include "lldb/Expression/IRInterpreter.h"
79#include "lldb/Host/File.h"
80#include "lldb/Host/HostInfo.h"
81#include "lldb/Symbol/SymbolVendor.h"
82#include "lldb/Target/ExecutionContext.h"
83#include "lldb/Target/ExecutionContextScope.h"
84#include "lldb/Target/Language.h"
85#include "lldb/Target/Process.h"
86#include "lldb/Target/Target.h"
87#include "lldb/Target/ThreadPlanCallFunction.h"
88#include "lldb/Utility/DataBufferHeap.h"
89#include "lldb/Utility/LLDBAssert.h"
90#include "lldb/Utility/LLDBLog.h"
91#include "lldb/Utility/Log.h"
92#include "lldb/Utility/Stream.h"
93#include "lldb/Utility/StreamString.h"
94#include "lldb/Utility/StringList.h"
95
96#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
97#include "Plugins/Platform/MacOSX/PlatformDarwin.h"
98#include "lldb/Utility/XcodeSDK.h"
99
100#include <cctype>
101#include <memory>
102#include <optional>
103
104using namespace clang;
105using namespace llvm;
106using namespace lldb_private;
107
108//===----------------------------------------------------------------------===//
109// Utility Methods for Clang
110//===----------------------------------------------------------------------===//
111
112class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
113 ClangModulesDeclVendor &m_decl_vendor;
114 ClangPersistentVariables &m_persistent_vars;
115 clang::SourceManager &m_source_mgr;
116 StreamString m_error_stream;
117 bool m_has_errors = false;
118
119public:
120 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
121 ClangPersistentVariables &persistent_vars,
122 clang::SourceManager &source_mgr)
123 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
124 m_source_mgr(source_mgr) {}
125
126 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
127 const clang::Module * /*null*/) override {
128 // Ignore modules that are imported in the wrapper code as these are not
129 // loaded by the user.
130 llvm::StringRef filename =
131 m_source_mgr.getPresumedLoc(Loc: import_location).getFilename();
132 if (filename == ClangExpressionSourceCode::g_prefix_file_name)
133 return;
134
135 SourceModule module;
136
137 for (const IdentifierLoc &component : path)
138 module.path.push_back(
139 x: ConstString(component.getIdentifierInfo()->getName()));
140
141 StreamString error_stream;
142
143 ClangModulesDeclVendor::ModuleVector exported_modules;
144 if (!m_decl_vendor.AddModule(module, exported_modules: &exported_modules, error_stream&: m_error_stream))
145 m_has_errors = true;
146
147 for (ClangModulesDeclVendor::ModuleID module : exported_modules)
148 m_persistent_vars.AddHandLoadedClangModule(module);
149 }
150
151 bool hasErrors() { return m_has_errors; }
152
153 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
154};
155
156static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) {
157 for (auto &fix_it : Info.getFixItHints()) {
158 if (fix_it.isNull())
159 continue;
160 diag->AddFixitHint(fixit: fix_it);
161 }
162}
163
164class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
165public:
166 ClangDiagnosticManagerAdapter(DiagnosticOptions &opts, StringRef filename)
167 : m_options(opts), m_filename(filename) {
168 m_options.ShowPresumedLoc = true;
169 m_options.ShowLevel = false;
170 m_os = std::make_shared<llvm::raw_string_ostream>(args&: m_output);
171 m_passthrough =
172 std::make_shared<clang::TextDiagnosticPrinter>(args&: *m_os, args&: m_options);
173 }
174
175 void ResetManager(DiagnosticManager *manager = nullptr) {
176 m_manager = manager;
177 }
178
179 /// Returns the last error ClangDiagnostic message that the
180 /// DiagnosticManager received or a nullptr.
181 ClangDiagnostic *MaybeGetLastClangDiag() const {
182 if (m_manager->Diagnostics().empty())
183 return nullptr;
184 auto &diags = m_manager->Diagnostics();
185 for (auto it = diags.rbegin(); it != diags.rend(); it++) {
186 lldb_private::Diagnostic *diag = it->get();
187 if (ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(Val: diag)) {
188 if (clang_diag->GetSeverity() == lldb::eSeverityWarning)
189 return nullptr;
190 if (clang_diag->GetSeverity() == lldb::eSeverityError)
191 return clang_diag;
192 }
193 }
194 return nullptr;
195 }
196
197 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
198 const clang::Diagnostic &Info) override {
199 if (!m_manager) {
200 // We have no DiagnosticManager before/after parsing but we still could
201 // receive diagnostics (e.g., by the ASTImporter failing to copy decls
202 // when we move the expression result ot the ScratchASTContext). Let's at
203 // least log these diagnostics until we find a way to properly render
204 // them and display them to the user.
205 Log *log = GetLog(mask: LLDBLog::Expressions);
206 if (log) {
207 llvm::SmallVector<char, 32> diag_str;
208 Info.FormatDiagnostic(OutStr&: diag_str);
209 diag_str.push_back(Elt: '\0');
210 const char *plain_diag = diag_str.data();
211 LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);
212 }
213 return;
214 }
215
216 // Update error/warning counters.
217 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
218
219 // Render diagnostic message to m_output.
220 m_output.clear();
221 m_passthrough->HandleDiagnostic(Level: DiagLevel, Info);
222
223 DiagnosticDetail detail;
224 switch (DiagLevel) {
225 case DiagnosticsEngine::Level::Fatal:
226 case DiagnosticsEngine::Level::Error:
227 detail.severity = lldb::eSeverityError;
228 break;
229 case DiagnosticsEngine::Level::Warning:
230 detail.severity = lldb::eSeverityWarning;
231 break;
232 case DiagnosticsEngine::Level::Remark:
233 case DiagnosticsEngine::Level::Ignored:
234 detail.severity = lldb::eSeverityInfo;
235 break;
236 case DiagnosticsEngine::Level::Note:
237 // 'note:' diagnostics for errors and warnings can also contain Fix-Its.
238 // We add these Fix-Its to the last error diagnostic to make sure
239 // that we later have all Fix-Its related to an 'error' diagnostic when
240 // we apply them to the user expression.
241 auto *clang_diag = MaybeGetLastClangDiag();
242 // If we don't have a previous diagnostic there is nothing to do.
243 // If the previous diagnostic already has its own Fix-Its, assume that
244 // the 'note:' Fix-It is just an alternative way to solve the issue and
245 // ignore these Fix-Its.
246 if (!clang_diag || clang_diag->HasFixIts())
247 break;
248 // Ignore all Fix-Its that are not associated with an error.
249 if (clang_diag->GetSeverity() != lldb::eSeverityError)
250 break;
251 AddAllFixIts(diag: clang_diag, Info);
252 break;
253 }
254 // ClangDiagnostic messages are expected to have no whitespace/newlines
255 // around them.
256 std::string stripped_output =
257 std::string(llvm::StringRef(m_output).trim());
258
259 // Translate the source location.
260 if (Info.hasSourceManager()) {
261 DiagnosticDetail::SourceLocation loc;
262 clang::SourceManager &sm = Info.getSourceManager();
263 const clang::SourceLocation sloc = Info.getLocation();
264 if (sloc.isValid()) {
265 const clang::FullSourceLoc fsloc(sloc, sm);
266 clang::PresumedLoc PLoc = fsloc.getPresumedLoc(UseLineDirectives: true);
267 StringRef filename =
268 PLoc.isValid() ? PLoc.getFilename() : StringRef{};
269 loc.file = FileSpec(filename);
270 loc.line = fsloc.getSpellingLineNumber();
271 loc.column = fsloc.getSpellingColumnNumber();
272 loc.in_user_input = filename == m_filename;
273 loc.hidden = filename.starts_with(Prefix: "<lldb wrapper ");
274
275 // Find the range of the primary location.
276 for (const auto &range : Info.getRanges()) {
277 if (range.getBegin() == sloc) {
278 // FIXME: This is probably not handling wide characters correctly.
279 unsigned end_col = sm.getSpellingColumnNumber(Loc: range.getEnd());
280 if (end_col > loc.column)
281 loc.length = end_col - loc.column;
282 break;
283 }
284 }
285 detail.source_location = loc;
286 }
287 }
288 llvm::SmallString<0> msg;
289 Info.FormatDiagnostic(OutStr&: msg);
290 detail.message = msg.str();
291 detail.rendered = stripped_output;
292 auto new_diagnostic =
293 std::make_unique<ClangDiagnostic>(args&: detail, args: Info.getID());
294
295 // Don't store away warning fixits, since the compiler doesn't have
296 // enough context in an expression for the warning to be useful.
297 // FIXME: Should we try to filter out FixIts that apply to our generated
298 // code, and not the user's expression?
299 if (detail.severity == lldb::eSeverityError)
300 AddAllFixIts(diag: new_diagnostic.get(), Info);
301
302 m_manager->AddDiagnostic(diagnostic: std::move(new_diagnostic));
303 }
304
305 void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
306 m_passthrough->BeginSourceFile(LO, PP);
307 }
308
309 void EndSourceFile() override { m_passthrough->EndSourceFile(); }
310
311private:
312 DiagnosticManager *m_manager = nullptr;
313 DiagnosticOptions m_options;
314 std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;
315 /// Output stream of m_passthrough.
316 std::shared_ptr<llvm::raw_string_ostream> m_os;
317 /// Output string filled by m_os.
318 std::string m_output;
319 StringRef m_filename;
320};
321
322/// Returns true if the SDK for the specified triple supports
323/// builtin modules in system headers. This is used to decide
324/// whether to pass -fbuiltin-headers-in-system-modules to
325/// the compiler instance when compiling the `std` module.
326static llvm::Expected<bool>
327sdkSupportsBuiltinModules(lldb_private::Target &target) {
328 auto arch_spec = target.GetArchitecture();
329 auto const &triple = arch_spec.GetTriple();
330 auto module_sp = target.GetExecutableModule();
331 if (!module_sp)
332 return llvm::createStringError(Fmt: "Executable module not found.");
333
334 // Get SDK path that the target was compiled against.
335 auto platform_sp = target.GetPlatform();
336 if (!platform_sp)
337 return llvm::createStringError(Fmt: "No Platform plugin found on target.");
338
339 auto sdk_or_err = platform_sp->GetSDKPathFromDebugInfo(module&: *module_sp);
340 if (!sdk_or_err)
341 return sdk_or_err.takeError();
342
343 // Use the SDK path from debug-info to find a local matching SDK directory.
344 auto sdk_path_or_err =
345 HostInfo::GetSDKRoot(options: HostInfo::SDKOptions{.XcodeSDKSelection: std::move(sdk_or_err->first)});
346 if (!sdk_path_or_err)
347 return sdk_path_or_err.takeError();
348
349 auto VFS = FileSystem::Instance().GetVirtualFileSystem();
350 if (!VFS)
351 return llvm::createStringError(Fmt: "No virtual filesystem available.");
352
353 // Extract SDK version from the /path/to/some.sdk/SDKSettings.json
354 auto parsed_or_err = clang::parseDarwinSDKInfo(VFS&: *VFS, SDKRootPath: *sdk_path_or_err);
355 if (!parsed_or_err)
356 return parsed_or_err.takeError();
357
358 auto maybe_sdk = *parsed_or_err;
359 if (!maybe_sdk)
360 return llvm::createStringError(Fmt: "Couldn't find Darwin SDK info.");
361
362 return XcodeSDK::SDKSupportsBuiltinModules(target_triple: triple, sdk_version: maybe_sdk->getVersion());
363}
364
365static void SetupModuleHeaderPaths(CompilerInstance *compiler,
366 std::vector<std::string> include_directories,
367 lldb::TargetSP target_sp) {
368 Log *log = GetLog(mask: LLDBLog::Expressions);
369
370 HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
371
372 for (const std::string &dir : include_directories) {
373 search_opts.AddPath(Path: dir, Group: frontend::System, IsFramework: false, IgnoreSysRoot: true);
374 LLDB_LOG(log, "Added user include dir: {0}", dir);
375 }
376
377 llvm::SmallString<128> module_cache;
378 const auto &props = ModuleList::GetGlobalModuleListProperties();
379 props.GetClangModulesCachePath().GetPath(path&: module_cache);
380 search_opts.ModuleCachePath = std::string(module_cache.str());
381 LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
382
383 search_opts.ResourceDir = GetClangResourceDir().GetPath();
384
385 search_opts.ImplicitModuleMaps = true;
386}
387
388/// Iff the given identifier is a C++ keyword, remove it from the
389/// identifier table (i.e., make the token a normal identifier).
390static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) {
391 // FIXME: 'using' is used by LLDB for local variables, so we can't remove
392 // this keyword without breaking this functionality.
393 if (token == "using")
394 return;
395 // GCC's '__null' is used by LLDB to define NULL/Nil/nil.
396 if (token == "__null")
397 return;
398
399 LangOptions cpp_lang_opts;
400 cpp_lang_opts.CPlusPlus = true;
401 cpp_lang_opts.CPlusPlus11 = true;
402 cpp_lang_opts.CPlusPlus20 = true;
403
404 clang::IdentifierInfo &ii = idents.get(Name: token);
405 // The identifier has to be a C++-exclusive keyword. if not, then there is
406 // nothing to do.
407 if (!ii.isCPlusPlusKeyword(LangOpts: cpp_lang_opts))
408 return;
409 // If the token is already an identifier, then there is nothing to do.
410 if (ii.getTokenID() == clang::tok::identifier)
411 return;
412 // Otherwise the token is a C++ keyword, so turn it back into a normal
413 // identifier.
414 ii.revertTokenIDToIdentifier();
415}
416
417/// Remove all C++ keywords from the given identifier table.
418static void RemoveAllCppKeywords(IdentifierTable &idents) {
419#define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME));
420#include "clang/Basic/TokenKinds.def"
421}
422
423/// Configures Clang diagnostics for the expression parser.
424static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) {
425 // List of Clang warning groups that are not useful when parsing expressions.
426 const std::vector<const char *> groupsToIgnore = {
427 "unused-value",
428 "odr",
429 "unused-getter-return-value",
430 };
431 for (const char *group : groupsToIgnore) {
432 compiler.getDiagnostics().setSeverityForGroup(
433 Flavor: clang::diag::Flavor::WarningOrError, Group: group,
434 Map: clang::diag::Severity::Ignored, Loc: SourceLocation());
435 }
436}
437
438/// Returns a string representing current ABI.
439///
440/// \param[in] target_arch
441/// The target architecture.
442///
443/// \return
444/// A string representing target ABI for the current architecture.
445static std::string GetClangTargetABI(const ArchSpec &target_arch) {
446 if (target_arch.IsMIPS()) {
447 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
448 case ArchSpec::eMIPSABI_N64:
449 return "n64";
450 case ArchSpec::eMIPSABI_N32:
451 return "n32";
452 case ArchSpec::eMIPSABI_O32:
453 return "o32";
454 default:
455 return {};
456 }
457 }
458
459 if (target_arch.GetTriple().isRISCV64()) {
460 switch (target_arch.GetFlags() & ArchSpec::eRISCV_float_abi_mask) {
461 case ArchSpec::eRISCV_float_abi_soft:
462 return "lp64";
463 case ArchSpec::eRISCV_float_abi_single:
464 return "lp64f";
465 case ArchSpec::eRISCV_float_abi_double:
466 return "lp64d";
467 case ArchSpec::eRISCV_float_abi_quad:
468 return "lp64q";
469 default:
470 return {};
471 }
472 }
473
474 if (target_arch.GetTriple().isRISCV32()) {
475 switch (target_arch.GetFlags() & ArchSpec::eRISCV_float_abi_mask) {
476 case ArchSpec::eRISCV_float_abi_soft:
477 return "ilp32";
478 case ArchSpec::eRISCV_float_abi_single:
479 return "ilp32f";
480 case ArchSpec::eRISCV_float_abi_double:
481 return "ilp32d";
482 case ArchSpec::eRISCV_float_abi_soft | ArchSpec::eRISCV_rve:
483 return "ilp32e";
484 default:
485 return {};
486 }
487 }
488
489 if (target_arch.GetTriple().isLoongArch64()) {
490 switch (target_arch.GetFlags() & ArchSpec::eLoongArch_abi_mask) {
491 case ArchSpec::eLoongArch_abi_soft_float:
492 return "lp64s";
493 case ArchSpec::eLoongArch_abi_single_float:
494 return "lp64f";
495 case ArchSpec::eLoongArch_abi_double_float:
496 return "lp64d";
497 default:
498 return {};
499 }
500 }
501
502 return {};
503}
504
505static void SetupTargetOpts(CompilerInstance &compiler,
506 lldb_private::Target const &target) {
507 Log *log = GetLog(mask: LLDBLog::Expressions);
508 ArchSpec target_arch = target.GetArchitecture();
509
510 const auto target_machine = target_arch.GetMachine();
511 if (target_arch.IsValid()) {
512 std::string triple = target_arch.GetTriple().str();
513 compiler.getTargetOpts().Triple = triple;
514 LLDB_LOGF(log, "Using %s as the target triple",
515 compiler.getTargetOpts().Triple.c_str());
516 } else {
517 // If we get here we don't have a valid target and just have to guess.
518 // Sometimes this will be ok to just use the host target triple (when we
519 // evaluate say "2+3", but other expressions like breakpoint conditions and
520 // other things that _are_ target specific really shouldn't just be using
521 // the host triple. In such a case the language runtime should expose an
522 // overridden options set (3), below.
523 compiler.getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
524 LLDB_LOGF(log, "Using default target triple of %s",
525 compiler.getTargetOpts().Triple.c_str());
526 }
527 // Now add some special fixes for known architectures: Any arm32 iOS
528 // environment, but not on arm64
529 if (compiler.getTargetOpts().Triple.find(s: "arm64") == std::string::npos &&
530 compiler.getTargetOpts().Triple.find(s: "arm") != std::string::npos &&
531 compiler.getTargetOpts().Triple.find(s: "ios") != std::string::npos) {
532 compiler.getTargetOpts().ABI = "apcs-gnu";
533 }
534 // Supported subsets of x86
535 if (target_machine == llvm::Triple::x86 ||
536 target_machine == llvm::Triple::x86_64) {
537 compiler.getTargetOpts().FeaturesAsWritten.push_back(x: "+sse");
538 compiler.getTargetOpts().FeaturesAsWritten.push_back(x: "+sse2");
539 }
540
541 // Set the target CPU to generate code for. This will be empty for any CPU
542 // that doesn't really need to make a special
543 // CPU string.
544 compiler.getTargetOpts().CPU = target_arch.GetClangTargetCPU();
545
546 // Set the target ABI
547 if (std::string abi = GetClangTargetABI(target_arch); !abi.empty())
548 compiler.getTargetOpts().ABI = std::move(abi);
549
550 if ((target_machine == llvm::Triple::riscv64 &&
551 compiler.getTargetOpts().ABI == "lp64f") ||
552 (target_machine == llvm::Triple::riscv32 &&
553 compiler.getTargetOpts().ABI == "ilp32f"))
554 compiler.getTargetOpts().FeaturesAsWritten.emplace_back(args: "+f");
555
556 if ((target_machine == llvm::Triple::riscv64 &&
557 compiler.getTargetOpts().ABI == "lp64d") ||
558 (target_machine == llvm::Triple::riscv32 &&
559 compiler.getTargetOpts().ABI == "ilp32d"))
560 compiler.getTargetOpts().FeaturesAsWritten.emplace_back(args: "+d");
561
562 if ((target_machine == llvm::Triple::loongarch64 &&
563 compiler.getTargetOpts().ABI == "lp64f"))
564 compiler.getTargetOpts().FeaturesAsWritten.emplace_back(args: "+f");
565
566 if ((target_machine == llvm::Triple::loongarch64 &&
567 compiler.getTargetOpts().ABI == "lp64d"))
568 compiler.getTargetOpts().FeaturesAsWritten.emplace_back(args: "+d");
569}
570
571static void SetupLangOpts(CompilerInstance &compiler,
572 ExecutionContextScope &exe_scope,
573 const Expression &expr) {
574 Log *log = GetLog(mask: LLDBLog::Expressions);
575
576 // If the expression is being evaluated in the context of an existing stack
577 // frame, we introspect to see if the language runtime is available.
578
579 lldb::StackFrameSP frame_sp = exe_scope.CalculateStackFrame();
580 lldb::ProcessSP process_sp = exe_scope.CalculateProcess();
581
582 // Defaults to lldb::eLanguageTypeUnknown.
583 lldb::LanguageType frame_lang = expr.Language().AsLanguageType();
584
585 // Make sure the user hasn't provided a preferred execution language with
586 // `expression --language X -- ...`
587 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
588 frame_lang = frame_sp->GetLanguage().AsLanguageType();
589
590 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
591 LLDB_LOGF(log, "Frame has language of type %s",
592 lldb_private::Language::GetNameForLanguageType(frame_lang));
593 }
594
595 lldb::LanguageType language = expr.Language().AsLanguageType();
596 LangOptions &lang_opts = compiler.getLangOpts();
597
598 // FIXME: should this switch on frame_lang?
599 switch (language) {
600 case lldb::eLanguageTypeC:
601 case lldb::eLanguageTypeC89:
602 case lldb::eLanguageTypeC99:
603 case lldb::eLanguageTypeC11:
604 // FIXME: the following language option is a temporary workaround,
605 // to "ask for C, get C++."
606 // For now, the expression parser must use C++ anytime the language is a C
607 // family language, because the expression parser uses features of C++ to
608 // capture values.
609 lang_opts.CPlusPlus = true;
610 break;
611 case lldb::eLanguageTypeObjC:
612 lang_opts.ObjC = true;
613 // FIXME: the following language option is a temporary workaround,
614 // to "ask for ObjC, get ObjC++" (see comment above).
615 lang_opts.CPlusPlus = true;
616
617 // Clang now sets as default C++14 as the default standard (with
618 // GNU extensions), so we do the same here to avoid mismatches that
619 // cause compiler error when evaluating expressions (e.g. nullptr not found
620 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
621 // two lines below) so we decide to be consistent with that, but this could
622 // be re-evaluated in the future.
623 lang_opts.CPlusPlus11 = true;
624 break;
625 case lldb::eLanguageTypeC_plus_plus_20:
626 lang_opts.CPlusPlus20 = true;
627 [[fallthrough]];
628 case lldb::eLanguageTypeC_plus_plus_17:
629 // FIXME: add a separate case for CPlusPlus14. Currently folded into C++17
630 // because C++14 is the default standard for Clang but enabling CPlusPlus14
631 // expression evaluatino doesn't pass the test-suite cleanly.
632 lang_opts.CPlusPlus14 = true;
633 lang_opts.CPlusPlus17 = true;
634 [[fallthrough]];
635 case lldb::eLanguageTypeC_plus_plus:
636 case lldb::eLanguageTypeC_plus_plus_11:
637 case lldb::eLanguageTypeC_plus_plus_14:
638 lang_opts.CPlusPlus11 = true;
639 compiler.getHeaderSearchOpts().UseLibcxx = true;
640 [[fallthrough]];
641 case lldb::eLanguageTypeC_plus_plus_03:
642 lang_opts.CPlusPlus = true;
643 if (process_sp
644 // We're stopped in a frame without debug-info. The user probably
645 // intends to make global queries (which should include Objective-C).
646 && !(frame_sp && frame_sp->HasDebugInformation()))
647 lang_opts.ObjC =
648 process_sp->GetLanguageRuntime(language: lldb::eLanguageTypeObjC) != nullptr;
649 break;
650 case lldb::eLanguageTypeObjC_plus_plus:
651 case lldb::eLanguageTypeUnknown:
652 default:
653 lang_opts.ObjC = true;
654 lang_opts.CPlusPlus = true;
655 lang_opts.CPlusPlus11 = true;
656 compiler.getHeaderSearchOpts().UseLibcxx = true;
657 break;
658 }
659
660 lang_opts.Bool = true;
661 lang_opts.WChar = true;
662 lang_opts.Blocks = true;
663 lang_opts.DebuggerSupport =
664 true; // Features specifically for debugger clients
665 if (expr.DesiredResultType() == Expression::eResultTypeId)
666 lang_opts.DebuggerCastResultToId = true;
667
668 lang_opts.CharIsSigned =
669 ArchSpec(compiler.getTargetOpts().Triple.c_str()).CharIsSignedByDefault();
670
671 // Spell checking is a nice feature, but it ends up completing a lot of types
672 // that we didn't strictly speaking need to complete. As a result, we spend a
673 // long time parsing and importing debug information.
674 lang_opts.SpellChecking = false;
675
676 if (process_sp && lang_opts.ObjC) {
677 if (auto *runtime = ObjCLanguageRuntime::Get(process&: *process_sp)) {
678 switch (runtime->GetRuntimeVersion()) {
679 case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2:
680 lang_opts.ObjCRuntime.set(kind: ObjCRuntime::MacOSX, version: VersionTuple(10, 7));
681 break;
682 case ObjCLanguageRuntime::ObjCRuntimeVersions::eObjC_VersionUnknown:
683 case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V1:
684 lang_opts.ObjCRuntime.set(kind: ObjCRuntime::FragileMacOSX,
685 version: VersionTuple(10, 7));
686 break;
687 case ObjCLanguageRuntime::ObjCRuntimeVersions::eGNUstep_libobjc2:
688 lang_opts.ObjCRuntime.set(kind: ObjCRuntime::GNUstep, version: VersionTuple(2, 0));
689 break;
690 }
691
692 if (runtime->HasNewLiteralsAndIndexing())
693 lang_opts.DebuggerObjCLiteral = true;
694 }
695 }
696
697 lang_opts.ThreadsafeStatics = false;
698 lang_opts.AccessControl = false; // Debuggers get universal access
699 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
700 // We enable all builtin functions beside the builtins from libc/libm (e.g.
701 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
702 // additionally enabling them as expandable builtins is breaking Clang.
703 lang_opts.NoBuiltin = true;
704}
705
706static void SetupImportStdModuleLangOpts(CompilerInstance &compiler,
707 lldb_private::Target &target) {
708 Log *log = GetLog(mask: LLDBLog::Expressions);
709 LangOptions &lang_opts = compiler.getLangOpts();
710 lang_opts.Modules = true;
711 // We want to implicitly build modules.
712 lang_opts.ImplicitModules = true;
713 // To automatically import all submodules when we import 'std'.
714 lang_opts.ModulesLocalVisibility = false;
715
716 // We use the @import statements, so we need this:
717 // FIXME: We could use the modules-ts, but that currently doesn't work.
718 lang_opts.ObjC = true;
719
720 // Options we need to parse libc++ code successfully.
721 // FIXME: We should ask the driver for the appropriate default flags.
722 lang_opts.GNUMode = true;
723 lang_opts.GNUKeywords = true;
724 lang_opts.CPlusPlus11 = true;
725
726 if (auto supported_or_err = sdkSupportsBuiltinModules(target))
727 lang_opts.BuiltinHeadersInSystemModules = !*supported_or_err;
728 else
729 LLDB_LOG_ERROR(log, supported_or_err.takeError(),
730 "Failed to determine BuiltinHeadersInSystemModules when "
731 "setting up import-std-module: {0}");
732
733 // The Darwin libc expects this macro to be set.
734 lang_opts.GNUCVersion = 40201;
735}
736
737//===----------------------------------------------------------------------===//
738// Implementation of ClangExpressionParser
739//===----------------------------------------------------------------------===//
740
741ClangExpressionParser::ClangExpressionParser(
742 ExecutionContextScope *exe_scope, Expression &expr,
743 bool generate_debug_info, std::vector<std::string> include_directories,
744 std::string filename)
745 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
746 m_pp_callbacks(nullptr),
747 m_include_directories(std::move(include_directories)),
748 m_filename(std::move(filename)) {
749 Log *log = GetLog(mask: LLDBLog::Expressions);
750
751 // We can't compile expressions without a target. So if the exe_scope is
752 // null or doesn't have a target, then we just need to get out of here. I'll
753 // lldbassert and not make any of the compiler objects since
754 // I can't return errors directly from the constructor. Further calls will
755 // check if the compiler was made and
756 // bag out if it wasn't.
757
758 if (!exe_scope) {
759 lldbassert(exe_scope &&
760 "Can't make an expression parser with a null scope.");
761 return;
762 }
763
764 lldb::TargetSP target_sp;
765 target_sp = exe_scope->CalculateTarget();
766 if (!target_sp) {
767 lldbassert(target_sp.get() &&
768 "Can't make an expression parser with a null target.");
769 return;
770 }
771
772 // 1. Create a new compiler instance.
773 m_compiler = std::make_unique<CompilerInstance>();
774
775 // Make sure clang uses the same VFS as LLDB.
776 m_compiler->createFileManager(VFS: FileSystem::Instance().GetVirtualFileSystem());
777
778 // 2. Configure the compiler with a set of default options that are
779 // appropriate for most situations.
780 SetupTargetOpts(compiler&: *m_compiler, target: *target_sp);
781
782 // 3. Create and install the target on the compiler.
783 m_compiler->createDiagnostics(VFS&: m_compiler->getVirtualFileSystem());
784 // Limit the number of error diagnostics we emit.
785 // A value of 0 means no limit for both LLDB and Clang.
786 m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());
787
788 if (auto *target_info = TargetInfo::CreateTargetInfo(
789 Diags&: m_compiler->getDiagnostics(),
790 Opts&: m_compiler->getInvocation().getTargetOpts())) {
791 if (log) {
792 LLDB_LOGF(log, "Target datalayout string: '%s'",
793 target_info->getDataLayoutString());
794 LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
795 LLDB_LOGF(log, "Target vector alignment: %d",
796 target_info->getMaxVectorAlign());
797 }
798 m_compiler->setTarget(target_info);
799 } else {
800 if (log)
801 LLDB_LOGF(log, "Failed to create TargetInfo for '%s'",
802 m_compiler->getTargetOpts().Triple.c_str());
803
804 lldbassert(false && "Failed to create TargetInfo.");
805 }
806
807 // 4. Set language options.
808 SetupLangOpts(compiler&: *m_compiler, exe_scope&: *exe_scope, expr);
809 auto *clang_expr = dyn_cast<ClangUserExpression>(Val: &m_expr);
810 if (clang_expr && clang_expr->DidImportCxxModules()) {
811 LLDB_LOG(log, "Adding lang options for importing C++ modules");
812 SetupImportStdModuleLangOpts(compiler&: *m_compiler, target&: *target_sp);
813 SetupModuleHeaderPaths(compiler: m_compiler.get(), include_directories: m_include_directories, target_sp);
814 }
815
816 // Set CodeGen options
817 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
818 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
819 m_compiler->getCodeGenOpts().setFramePointer(
820 CodeGenOptions::FramePointerKind::All);
821 if (generate_debug_info)
822 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
823 else
824 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
825
826 // Disable some warnings.
827 SetupDefaultClangDiagnostics(*m_compiler);
828
829 // Inform the target of the language options
830 //
831 // FIXME: We shouldn't need to do this, the target should be immutable once
832 // created. This complexity should be lifted elsewhere.
833 m_compiler->getTarget().adjust(Diags&: m_compiler->getDiagnostics(),
834 Opts&: m_compiler->getLangOpts(),
835 /*AuxTarget=*/Aux: nullptr);
836
837 // 5. Set up the diagnostic buffer for reporting errors
838 auto diag_mgr = new ClangDiagnosticManagerAdapter(
839 m_compiler->getDiagnostics().getDiagnosticOptions(),
840 clang_expr ? clang_expr->GetFilename() : StringRef());
841 m_compiler->getDiagnostics().setClient(client: diag_mgr);
842
843 // 6. Set up the source management objects inside the compiler
844 m_compiler->createFileManager();
845 if (!m_compiler->hasSourceManager())
846 m_compiler->createSourceManager(FileMgr&: m_compiler->getFileManager());
847 m_compiler->createPreprocessor(TUKind: TU_Complete);
848
849 switch (expr.Language().AsLanguageType()) {
850 case lldb::eLanguageTypeC:
851 case lldb::eLanguageTypeC89:
852 case lldb::eLanguageTypeC99:
853 case lldb::eLanguageTypeC11:
854 case lldb::eLanguageTypeObjC:
855 // This is not a C++ expression but we enabled C++ as explained above.
856 // Remove all C++ keywords from the PP so that the user can still use
857 // variables that have C++ keywords as names (e.g. 'int template;').
858 RemoveAllCppKeywords(idents&: m_compiler->getPreprocessor().getIdentifierTable());
859 break;
860 default:
861 break;
862 }
863
864 if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(
865 Val: target_sp->GetPersistentExpressionStateForLanguage(
866 language: lldb::eLanguageTypeC))) {
867 if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
868 clang_persistent_vars->GetClangModulesDeclVendor()) {
869 std::unique_ptr<PPCallbacks> pp_callbacks(
870 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,
871 m_compiler->getSourceManager()));
872 m_pp_callbacks =
873 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
874 m_compiler->getPreprocessor().addPPCallbacks(C: std::move(pp_callbacks));
875 }
876 }
877
878 // 7. Most of this we get from the CompilerInstance, but we also want to give
879 // the context an ExternalASTSource.
880
881 auto &PP = m_compiler->getPreprocessor();
882 auto &builtin_context = PP.getBuiltinInfo();
883 builtin_context.initializeBuiltins(Table&: PP.getIdentifierTable(),
884 LangOpts: m_compiler->getLangOpts());
885
886 m_compiler->createASTContext();
887 clang::ASTContext &ast_context = m_compiler->getASTContext();
888
889 m_ast_context = std::make_shared<TypeSystemClang>(
890 args: "Expression ASTContext for '" + m_filename + "'", args&: ast_context);
891
892 std::string module_name("$__lldb_module");
893
894 m_llvm_context = std::make_unique<LLVMContext>();
895 m_code_generator.reset(p: CreateLLVMCodeGen(
896 Diags&: m_compiler->getDiagnostics(), ModuleName: module_name,
897 FS: &m_compiler->getVirtualFileSystem(), HeaderSearchOpts: m_compiler->getHeaderSearchOpts(),
898 PreprocessorOpts: m_compiler->getPreprocessorOpts(), CGO: m_compiler->getCodeGenOpts(),
899 C&: *m_llvm_context));
900}
901
902ClangExpressionParser::~ClangExpressionParser() = default;
903
904namespace {
905
906/// \class CodeComplete
907///
908/// A code completion consumer for the clang Sema that is responsible for
909/// creating the completion suggestions when a user requests completion
910/// of an incomplete `expr` invocation.
911class CodeComplete : public CodeCompleteConsumer {
912 CodeCompletionTUInfo m_info;
913
914 std::string m_expr;
915 unsigned m_position = 0;
916 /// The printing policy we use when printing declarations for our completion
917 /// descriptions.
918 clang::PrintingPolicy m_desc_policy;
919
920 struct CompletionWithPriority {
921 CompletionResult::Completion completion;
922 /// See CodeCompletionResult::Priority;
923 unsigned Priority;
924
925 /// Establishes a deterministic order in a list of CompletionWithPriority.
926 /// The order returned here is the order in which the completions are
927 /// displayed to the user.
928 bool operator<(const CompletionWithPriority &o) const {
929 // High priority results should come first.
930 if (Priority != o.Priority)
931 return Priority > o.Priority;
932
933 // Identical priority, so just make sure it's a deterministic order.
934 return completion.GetUniqueKey() < o.completion.GetUniqueKey();
935 }
936 };
937
938 /// The stored completions.
939 /// Warning: These are in a non-deterministic order until they are sorted
940 /// and returned back to the caller.
941 std::vector<CompletionWithPriority> m_completions;
942
943 /// Returns true if the given character can be used in an identifier.
944 /// This also returns true for numbers because for completion we usually
945 /// just iterate backwards over iterators.
946 ///
947 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
948 static bool IsIdChar(char c) {
949 return c == '_' || std::isalnum(c) || c == '$';
950 }
951
952 /// Returns true if the given character is used to separate arguments
953 /// in the command line of lldb.
954 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
955
956 /// Drops all tokens in front of the expression that are unrelated for
957 /// the completion of the cmd line. 'unrelated' means here that the token
958 /// is not interested for the lldb completion API result.
959 StringRef dropUnrelatedFrontTokens(StringRef cmd) const {
960 if (cmd.empty())
961 return cmd;
962
963 // If we are at the start of a word, then all tokens are unrelated to
964 // the current completion logic.
965 if (IsTokenSeparator(c: cmd.back()))
966 return StringRef();
967
968 // Remove all previous tokens from the string as they are unrelated
969 // to completing the current token.
970 StringRef to_remove = cmd;
971 while (!to_remove.empty() && !IsTokenSeparator(c: to_remove.back())) {
972 to_remove = to_remove.drop_back();
973 }
974 cmd = cmd.drop_front(N: to_remove.size());
975
976 return cmd;
977 }
978
979 /// Removes the last identifier token from the given cmd line.
980 StringRef removeLastToken(StringRef cmd) const {
981 while (!cmd.empty() && IsIdChar(c: cmd.back())) {
982 cmd = cmd.drop_back();
983 }
984 return cmd;
985 }
986
987 /// Attempts to merge the given completion from the given position into the
988 /// existing command. Returns the completion string that can be returned to
989 /// the lldb completion API.
990 std::string mergeCompletion(StringRef existing, unsigned pos,
991 StringRef completion) const {
992 StringRef existing_command = existing.substr(Start: 0, N: pos);
993 // We rewrite the last token with the completion, so let's drop that
994 // token from the command.
995 existing_command = removeLastToken(cmd: existing_command);
996 // We also should remove all previous tokens from the command as they
997 // would otherwise be added to the completion that already has the
998 // completion.
999 existing_command = dropUnrelatedFrontTokens(cmd: existing_command);
1000 return existing_command.str() + completion.str();
1001 }
1002
1003public:
1004 /// Constructs a CodeComplete consumer that can be attached to a Sema.
1005 ///
1006 /// \param[out] expr
1007 /// The whole expression string that we are currently parsing. This
1008 /// string needs to be equal to the input the user typed, and NOT the
1009 /// final code that Clang is parsing.
1010 /// \param[out] position
1011 /// The character position of the user cursor in the `expr` parameter.
1012 ///
1013 CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)
1014 : CodeCompleteConsumer(CodeCompleteOptions()),
1015 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
1016 m_position(position), m_desc_policy(ops) {
1017
1018 // Ensure that the printing policy is producing a description that is as
1019 // short as possible.
1020 m_desc_policy.SuppressScope = true;
1021 m_desc_policy.SuppressTagKeyword = true;
1022 m_desc_policy.FullyQualifiedName = false;
1023 m_desc_policy.TerseOutput = true;
1024 m_desc_policy.IncludeNewlines = false;
1025 m_desc_policy.UseVoidForZeroParams = false;
1026 m_desc_policy.Bool = true;
1027 }
1028
1029 /// \name Code-completion filtering
1030 /// Check if the result should be filtered out.
1031 bool isResultFilteredOut(StringRef Filter,
1032 CodeCompletionResult Result) override {
1033 // This code is mostly copied from CodeCompleteConsumer.
1034 switch (Result.Kind) {
1035 case CodeCompletionResult::RK_Declaration:
1036 return !(
1037 Result.Declaration->getIdentifier() &&
1038 Result.Declaration->getIdentifier()->getName().starts_with(Prefix: Filter));
1039 case CodeCompletionResult::RK_Keyword:
1040 return !StringRef(Result.Keyword).starts_with(Prefix: Filter);
1041 case CodeCompletionResult::RK_Macro:
1042 return !Result.Macro->getName().starts_with(Prefix: Filter);
1043 case CodeCompletionResult::RK_Pattern:
1044 return !StringRef(Result.Pattern->getAsString()).starts_with(Prefix: Filter);
1045 }
1046 // If we trigger this assert or the above switch yields a warning, then
1047 // CodeCompletionResult has been enhanced with more kinds of completion
1048 // results. Expand the switch above in this case.
1049 assert(false && "Unknown completion result type?");
1050 // If we reach this, then we should just ignore whatever kind of unknown
1051 // result we got back. We probably can't turn it into any kind of useful
1052 // completion suggestion with the existing code.
1053 return true;
1054 }
1055
1056private:
1057 /// Generate the completion strings for the given CodeCompletionResult.
1058 /// Note that this function has to process results that could come in
1059 /// non-deterministic order, so this function should have no side effects.
1060 /// To make this easier to enforce, this function and all its parameters
1061 /// should always be const-qualified.
1062 /// \return Returns std::nullopt if no completion should be provided for the
1063 /// given CodeCompletionResult.
1064 std::optional<CompletionWithPriority>
1065 getCompletionForResult(const CodeCompletionResult &R) const {
1066 std::string ToInsert;
1067 std::string Description;
1068 // Handle the different completion kinds that come from the Sema.
1069 switch (R.Kind) {
1070 case CodeCompletionResult::RK_Declaration: {
1071 const NamedDecl *D = R.Declaration;
1072 ToInsert = R.Declaration->getNameAsString();
1073 // If we have a function decl that has no arguments we want to
1074 // complete the empty parantheses for the user. If the function has
1075 // arguments, we at least complete the opening bracket.
1076 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: D)) {
1077 if (F->getNumParams() == 0)
1078 ToInsert += "()";
1079 else
1080 ToInsert += "(";
1081 raw_string_ostream OS(Description);
1082 F->print(Out&: OS, Policy: m_desc_policy, Indentation: false);
1083 } else if (const VarDecl *V = dyn_cast<VarDecl>(Val: D)) {
1084 Description = V->getType().getAsString(Policy: m_desc_policy);
1085 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(Val: D)) {
1086 Description = F->getType().getAsString(Policy: m_desc_policy);
1087 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(Val: D)) {
1088 // If we try to complete a namespace, then we can directly append
1089 // the '::'.
1090 if (!N->isAnonymousNamespace())
1091 ToInsert += "::";
1092 }
1093 break;
1094 }
1095 case CodeCompletionResult::RK_Keyword:
1096 ToInsert = R.Keyword;
1097 break;
1098 case CodeCompletionResult::RK_Macro:
1099 ToInsert = R.Macro->getName().str();
1100 break;
1101 case CodeCompletionResult::RK_Pattern:
1102 ToInsert = R.Pattern->getTypedText();
1103 break;
1104 }
1105 // We also filter some internal lldb identifiers here. The user
1106 // shouldn't see these.
1107 if (llvm::StringRef(ToInsert).starts_with(Prefix: "$__lldb_"))
1108 return std::nullopt;
1109 if (ToInsert.empty())
1110 return std::nullopt;
1111 // Merge the suggested Token into the existing command line to comply
1112 // with the kind of result the lldb API expects.
1113 std::string CompletionSuggestion =
1114 mergeCompletion(existing: m_expr, pos: m_position, completion: ToInsert);
1115
1116 CompletionResult::Completion completion(CompletionSuggestion, Description,
1117 CompletionMode::Normal);
1118 return {{.completion: completion, .Priority: R.Priority}};
1119 }
1120
1121public:
1122 /// Adds the completions to the given CompletionRequest.
1123 void GetCompletions(CompletionRequest &request) {
1124 // Bring m_completions into a deterministic order and pass it on to the
1125 // CompletionRequest.
1126 llvm::sort(C&: m_completions);
1127
1128 for (const CompletionWithPriority &C : m_completions)
1129 request.AddCompletion(completion: C.completion.GetCompletion(),
1130 description: C.completion.GetDescription(),
1131 mode: C.completion.GetMode());
1132 }
1133
1134 /// \name Code-completion callbacks
1135 /// Process the finalized code-completion results.
1136 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
1137 CodeCompletionResult *Results,
1138 unsigned NumResults) override {
1139
1140 // The Sema put the incomplete token we try to complete in here during
1141 // lexing, so we need to retrieve it here to know what we are completing.
1142 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
1143
1144 // Iterate over all the results. Filter out results we don't want and
1145 // process the rest.
1146 for (unsigned I = 0; I != NumResults; ++I) {
1147 // Filter the results with the information from the Sema.
1148 if (!Filter.empty() && isResultFilteredOut(Filter, Result: Results[I]))
1149 continue;
1150
1151 CodeCompletionResult &R = Results[I];
1152 std::optional<CompletionWithPriority> CompletionAndPriority =
1153 getCompletionForResult(R);
1154 if (!CompletionAndPriority)
1155 continue;
1156 m_completions.push_back(x: *CompletionAndPriority);
1157 }
1158 }
1159
1160 /// \param S the semantic-analyzer object for which code-completion is being
1161 /// done.
1162 ///
1163 /// \param CurrentArg the index of the current argument.
1164 ///
1165 /// \param Candidates an array of overload candidates.
1166 ///
1167 /// \param NumCandidates the number of overload candidates
1168 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1169 OverloadCandidate *Candidates,
1170 unsigned NumCandidates,
1171 SourceLocation OpenParLoc,
1172 bool Braced) override {
1173 // At the moment we don't filter out any overloaded candidates.
1174 }
1175
1176 CodeCompletionAllocator &getAllocator() override {
1177 return m_info.getAllocator();
1178 }
1179
1180 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
1181};
1182} // namespace
1183
1184bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
1185 unsigned pos, unsigned typed_pos) {
1186 DiagnosticManager mgr;
1187 // We need the raw user expression here because that's what the CodeComplete
1188 // class uses to provide completion suggestions.
1189 // However, the `Text` method only gives us the transformed expression here.
1190 // To actually get the raw user input here, we have to cast our expression to
1191 // the LLVMUserExpression which exposes the right API. This should never fail
1192 // as we always have a ClangUserExpression whenever we call this.
1193 ClangUserExpression *llvm_expr = cast<ClangUserExpression>(Val: &m_expr);
1194 CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(),
1195 typed_pos);
1196 // We don't need a code generator for parsing.
1197 m_code_generator.reset();
1198 // Start parsing the expression with our custom code completion consumer.
1199 ParseInternal(diagnostic_manager&: mgr, completion: &CC, completion_line: line, completion_column: pos);
1200 CC.GetCompletions(request);
1201 return true;
1202}
1203
1204unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
1205 return ParseInternal(diagnostic_manager);
1206}
1207
1208unsigned
1209ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
1210 CodeCompleteConsumer *completion_consumer,
1211 unsigned completion_line,
1212 unsigned completion_column) {
1213 ClangDiagnosticManagerAdapter *adapter =
1214 static_cast<ClangDiagnosticManagerAdapter *>(
1215 m_compiler->getDiagnostics().getClient());
1216
1217 adapter->ResetManager(manager: &diagnostic_manager);
1218
1219 const char *expr_text = m_expr.Text();
1220
1221 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
1222 bool created_main_file = false;
1223
1224 // Clang wants to do completion on a real file known by Clang's file manager,
1225 // so we have to create one to make this work.
1226 // TODO: We probably could also simulate to Clang's file manager that there
1227 // is a real file that contains our code.
1228 bool should_create_file = completion_consumer != nullptr;
1229
1230 // We also want a real file on disk if we generate full debug info.
1231 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
1232 codegenoptions::FullDebugInfo;
1233
1234 if (should_create_file) {
1235 int temp_fd = -1;
1236 llvm::SmallString<128> result_path;
1237 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
1238 tmpdir_file_spec.AppendPathComponent(component: "lldb-%%%%%%.expr");
1239 std::string temp_source_path = tmpdir_file_spec.GetPath();
1240 llvm::sys::fs::createUniqueFile(Model: temp_source_path, ResultFD&: temp_fd, ResultPath&: result_path);
1241 } else {
1242 llvm::sys::fs::createTemporaryFile(Prefix: "lldb", Suffix: "expr", ResultFD&: temp_fd, ResultPath&: result_path);
1243 }
1244
1245 if (temp_fd != -1) {
1246 lldb_private::NativeFile file(temp_fd, File::eOpenOptionWriteOnly, true);
1247 const size_t expr_text_len = strlen(s: expr_text);
1248 size_t bytes_written = expr_text_len;
1249 if (file.Write(buf: expr_text, num_bytes&: bytes_written).Success()) {
1250 if (bytes_written == expr_text_len) {
1251 file.Close();
1252 if (auto fileEntry = m_compiler->getFileManager().getOptionalFileRef(
1253 Filename: result_path)) {
1254 source_mgr.setMainFileID(source_mgr.createFileID(
1255 SourceFile: *fileEntry, IncludePos: SourceLocation(), FileCharacter: SrcMgr::C_User));
1256 created_main_file = true;
1257 }
1258 }
1259 }
1260 }
1261 }
1262
1263 if (!created_main_file) {
1264 std::unique_ptr<MemoryBuffer> memory_buffer =
1265 MemoryBuffer::getMemBufferCopy(InputData: expr_text, BufferName: m_filename);
1266 source_mgr.setMainFileID(source_mgr.createFileID(Buffer: std::move(memory_buffer)));
1267 }
1268
1269 adapter->BeginSourceFile(LO: m_compiler->getLangOpts(),
1270 PP: &m_compiler->getPreprocessor());
1271
1272 ClangExpressionHelper *type_system_helper =
1273 dyn_cast<ClangExpressionHelper>(Val: m_expr.GetTypeSystemHelper());
1274
1275 // If we want to parse for code completion, we need to attach our code
1276 // completion consumer to the Sema and specify a completion position.
1277 // While parsing the Sema will call this consumer with the provided
1278 // completion suggestions.
1279 if (completion_consumer) {
1280 auto main_file =
1281 source_mgr.getFileEntryRefForID(FID: source_mgr.getMainFileID());
1282 auto &PP = m_compiler->getPreprocessor();
1283 // Lines and columns start at 1 in Clang, but code completion positions are
1284 // indexed from 0, so we need to add 1 to the line and column here.
1285 ++completion_line;
1286 ++completion_column;
1287 PP.SetCodeCompletionPoint(File: *main_file, Line: completion_line, Column: completion_column);
1288 }
1289
1290 ASTConsumer *ast_transformer =
1291 type_system_helper->ASTTransformer(passthrough: m_code_generator.get());
1292
1293 std::unique_ptr<clang::ASTConsumer> Consumer;
1294 if (ast_transformer) {
1295 Consumer = std::make_unique<ASTConsumerForwarder>(args&: ast_transformer);
1296 } else if (m_code_generator) {
1297 Consumer = std::make_unique<ASTConsumerForwarder>(args: m_code_generator.get());
1298 } else {
1299 Consumer = std::make_unique<ASTConsumer>();
1300 }
1301
1302 clang::ASTContext &ast_context = m_compiler->getASTContext();
1303
1304 m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
1305 *Consumer, TU_Complete, completion_consumer));
1306 m_compiler->setASTConsumer(std::move(Consumer));
1307
1308 if (ast_context.getLangOpts().Modules) {
1309 m_compiler->createASTReader();
1310 m_ast_context->setSema(&m_compiler->getSema());
1311 }
1312
1313 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
1314 if (decl_map) {
1315 decl_map->InstallCodeGenerator(code_gen: &m_compiler->getASTConsumer());
1316 decl_map->InstallDiagnosticManager(diag_manager&: diagnostic_manager);
1317
1318 clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
1319
1320 auto *ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
1321
1322 if (ast_context.getExternalSource()) {
1323 auto *module_wrapper =
1324 new ExternalASTSourceWrapper(ast_context.getExternalSource());
1325
1326 auto *multiplexer =
1327 new SemaSourceWithPriorities(module_wrapper, ast_source_wrapper);
1328
1329 ast_context.setExternalSource(multiplexer);
1330 } else {
1331 ast_context.setExternalSource(ast_source);
1332 }
1333 m_compiler->getSema().addExternalSource(E: ast_source_wrapper);
1334 decl_map->InstallASTContext(ast_context&: *m_ast_context);
1335 }
1336
1337 // Check that the ASTReader is properly attached to ASTContext and Sema.
1338 if (ast_context.getLangOpts().Modules) {
1339 assert(m_compiler->getASTContext().getExternalSource() &&
1340 "ASTContext doesn't know about the ASTReader?");
1341 assert(m_compiler->getSema().getExternalSource() &&
1342 "Sema doesn't know about the ASTReader?");
1343 }
1344
1345 {
1346 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1347 &m_compiler->getSema());
1348 ParseAST(S&: m_compiler->getSema(), PrintStats: false, SkipFunctionBodies: false);
1349 }
1350
1351 // Make sure we have no pointer to the Sema we are about to destroy.
1352 if (ast_context.getLangOpts().Modules)
1353 m_ast_context->setSema(nullptr);
1354 // Destroy the Sema. This is necessary because we want to emulate the
1355 // original behavior of ParseAST (which also destroys the Sema after parsing).
1356 m_compiler->setSema(nullptr);
1357
1358 adapter->EndSourceFile();
1359
1360 unsigned num_errors = adapter->getNumErrors();
1361
1362 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1363 num_errors++;
1364 diagnostic_manager.PutString(severity: lldb::eSeverityError,
1365 str: "while importing modules:");
1366 diagnostic_manager.AppendMessageToDiagnostic(
1367 str: m_pp_callbacks->getErrorString());
1368 }
1369
1370 if (!num_errors) {
1371 type_system_helper->CommitPersistentDecls();
1372 }
1373
1374 adapter->ResetManager();
1375
1376 return num_errors;
1377}
1378
1379/// Applies the given Fix-It hint to the given commit.
1380static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) {
1381 // This is cobbed from clang::Rewrite::FixItRewriter.
1382 if (fixit.CodeToInsert.empty()) {
1383 if (fixit.InsertFromRange.isValid()) {
1384 commit.insertFromRange(loc: fixit.RemoveRange.getBegin(),
1385 range: fixit.InsertFromRange, /*afterToken=*/false,
1386 beforePreviousInsertions: fixit.BeforePreviousInsertions);
1387 return;
1388 }
1389 commit.remove(range: fixit.RemoveRange);
1390 return;
1391 }
1392 if (fixit.RemoveRange.isTokenRange() ||
1393 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) {
1394 commit.replace(range: fixit.RemoveRange, text: fixit.CodeToInsert);
1395 return;
1396 }
1397 commit.insert(loc: fixit.RemoveRange.getBegin(), text: fixit.CodeToInsert,
1398 /*afterToken=*/false, beforePreviousInsertions: fixit.BeforePreviousInsertions);
1399}
1400
1401bool ClangExpressionParser::RewriteExpression(
1402 DiagnosticManager &diagnostic_manager) {
1403 clang::SourceManager &source_manager = m_compiler->getSourceManager();
1404 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1405 nullptr);
1406 clang::edit::Commit commit(editor);
1407 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1408
1409 class RewritesReceiver : public edit::EditsReceiver {
1410 Rewriter &rewrite;
1411
1412 public:
1413 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1414
1415 void insert(SourceLocation loc, StringRef text) override {
1416 rewrite.InsertText(Loc: loc, Str: text);
1417 }
1418 void replace(CharSourceRange range, StringRef text) override {
1419 rewrite.ReplaceText(Start: range.getBegin(), OrigLength: rewrite.getRangeSize(Range: range), NewStr: text);
1420 }
1421 };
1422
1423 RewritesReceiver rewrites_receiver(rewriter);
1424
1425 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1426 size_t num_diags = diagnostics.size();
1427 if (num_diags == 0)
1428 return false;
1429
1430 for (const auto &diag : diagnostic_manager.Diagnostics()) {
1431 const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(Val: diag.get());
1432 if (!diagnostic)
1433 continue;
1434 if (!diagnostic->HasFixIts())
1435 continue;
1436 for (const FixItHint &fixit : diagnostic->FixIts())
1437 ApplyFixIt(fixit, commit);
1438 }
1439
1440 // FIXME - do we want to try to propagate specific errors here?
1441 if (!commit.isCommitable())
1442 return false;
1443 else if (!editor.commit(commit))
1444 return false;
1445
1446 // Now play all the edits, and stash the result in the diagnostic manager.
1447 editor.applyRewrites(receiver&: rewrites_receiver);
1448 RewriteBuffer &main_file_buffer =
1449 rewriter.getEditBuffer(FID: source_manager.getMainFileID());
1450
1451 std::string fixed_expression;
1452 llvm::raw_string_ostream out_stream(fixed_expression);
1453
1454 main_file_buffer.write(Stream&: out_stream);
1455 diagnostic_manager.SetFixedExpression(fixed_expression);
1456
1457 return true;
1458}
1459
1460static bool FindFunctionInModule(ConstString &mangled_name,
1461 llvm::Module *module, const char *orig_name) {
1462 for (const auto &func : module->getFunctionList()) {
1463 const StringRef &name = func.getName();
1464 if (name.contains(Other: orig_name)) {
1465 mangled_name.SetString(name);
1466 return true;
1467 }
1468 }
1469
1470 return false;
1471}
1472
1473lldb_private::Status ClangExpressionParser::DoPrepareForExecution(
1474 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1475 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1476 bool &can_interpret, ExecutionPolicy execution_policy) {
1477 func_addr = LLDB_INVALID_ADDRESS;
1478 func_end = LLDB_INVALID_ADDRESS;
1479 Log *log = GetLog(mask: LLDBLog::Expressions);
1480
1481 lldb_private::Status err;
1482
1483 std::unique_ptr<llvm::Module> llvm_module_up(
1484 m_code_generator->ReleaseModule());
1485
1486 if (!llvm_module_up) {
1487 err = Status::FromErrorString(str: "IR doesn't contain a module");
1488 return err;
1489 }
1490
1491 ConstString function_name;
1492
1493 if (execution_policy != eExecutionPolicyTopLevel) {
1494 // Find the actual name of the function (it's often mangled somehow)
1495
1496 if (!FindFunctionInModule(mangled_name&: function_name, module: llvm_module_up.get(),
1497 orig_name: m_expr.FunctionName())) {
1498 err = Status::FromErrorStringWithFormat(
1499 format: "Couldn't find %s() in the module", m_expr.FunctionName());
1500 return err;
1501 } else {
1502 LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(),
1503 m_expr.FunctionName());
1504 }
1505 }
1506
1507 SymbolContext sc;
1508
1509 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1510 sc = frame_sp->GetSymbolContext(resolve_scope: lldb::eSymbolContextEverything);
1511 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1512 sc.target_sp = target_sp;
1513 }
1514
1515 LLVMUserExpression::IRPasses custom_passes;
1516 {
1517 auto lang = m_expr.Language();
1518 LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,
1519 lang.GetDescription().data());
1520 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1521 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1522 auto runtime = process_sp->GetLanguageRuntime(language: lang.AsLanguageType());
1523 if (runtime)
1524 runtime->GetIRPasses(custom_passes);
1525 }
1526 }
1527
1528 if (custom_passes.EarlyPasses) {
1529 LLDB_LOGF(log,
1530 "%s - Running Early IR Passes from LanguageRuntime on "
1531 "expression module '%s'",
1532 __FUNCTION__, m_expr.FunctionName());
1533
1534 custom_passes.EarlyPasses->run(M&: *llvm_module_up);
1535 }
1536
1537 execution_unit_sp = std::make_shared<IRExecutionUnit>(
1538 args&: m_llvm_context, // handed off here
1539 args&: llvm_module_up, // handed off here
1540 args&: function_name, args: exe_ctx.GetTargetSP(), args&: sc,
1541 args&: m_compiler->getTargetOpts().Features);
1542
1543 if (auto *options = m_expr.GetOptions())
1544 execution_unit_sp->AppendPreferredSymbolContexts(
1545 contexts: options->GetPreferredSymbolContexts());
1546
1547 ClangExpressionHelper *type_system_helper =
1548 dyn_cast<ClangExpressionHelper>(Val: m_expr.GetTypeSystemHelper());
1549 ClangExpressionDeclMap *decl_map =
1550 type_system_helper->DeclMap(); // result can be NULL
1551
1552 if (decl_map) {
1553 StreamString error_stream;
1554 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1555 *execution_unit_sp, error_stream,
1556 function_name.AsCString());
1557
1558 if (!ir_for_target.runOnModule(llvm_module&: *execution_unit_sp->GetModule())) {
1559 err = Status(error_stream.GetString().str());
1560 return err;
1561 }
1562
1563 Process *process = exe_ctx.GetProcessPtr();
1564
1565 if (execution_policy != eExecutionPolicyAlways &&
1566 execution_policy != eExecutionPolicyTopLevel) {
1567 lldb_private::Status interpret_error;
1568
1569 bool interpret_function_calls =
1570 !process ? false : process->CanInterpretFunctionCalls();
1571 can_interpret = IRInterpreter::CanInterpret(
1572 module&: *execution_unit_sp->GetModule(), function&: *execution_unit_sp->GetFunction(),
1573 error&: interpret_error, support_function_calls: interpret_function_calls);
1574
1575 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1576 err = Status::FromErrorStringWithFormat(
1577 format: "Can't evaluate the expression without a running target due to: %s",
1578 interpret_error.AsCString());
1579 return err;
1580 }
1581 }
1582
1583 if (!process && execution_policy == eExecutionPolicyAlways) {
1584 err = Status::FromErrorString(
1585 str: "Expression needed to run in the target, but the "
1586 "target can't be run");
1587 return err;
1588 }
1589
1590 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1591 err = Status::FromErrorString(
1592 str: "Top-level code needs to be inserted into a runnable "
1593 "target, but the target can't be run");
1594 return err;
1595 }
1596
1597 if (execution_policy == eExecutionPolicyAlways ||
1598 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1599 if (m_expr.NeedsValidation() && process) {
1600 if (!process->GetDynamicCheckers()) {
1601 ClangDynamicCheckerFunctions *dynamic_checkers =
1602 new ClangDynamicCheckerFunctions();
1603
1604 DiagnosticManager install_diags;
1605 if (Error Err = dynamic_checkers->Install(diagnostic_manager&: install_diags, exe_ctx))
1606 return Status::FromError(error: install_diags.GetAsError(
1607 result: lldb::eExpressionSetupError, message: "couldn't install checkers:"));
1608
1609 process->SetDynamicCheckers(dynamic_checkers);
1610
1611 LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "
1612 "Finished installing dynamic checkers ==");
1613 }
1614
1615 if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1616 Val: process->GetDynamicCheckers())) {
1617 IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1618 function_name.AsCString());
1619
1620 llvm::Module *module = execution_unit_sp->GetModule();
1621 if (!module || !ir_dynamic_checks.runOnModule(M&: *module)) {
1622 err = Status::FromErrorString(
1623 str: "Couldn't add dynamic checks to the expression");
1624 return err;
1625 }
1626
1627 if (custom_passes.LatePasses) {
1628 LLDB_LOGF(log,
1629 "%s - Running Late IR Passes from LanguageRuntime on "
1630 "expression module '%s'",
1631 __FUNCTION__, m_expr.FunctionName());
1632
1633 custom_passes.LatePasses->run(M&: *module);
1634 }
1635 }
1636 }
1637 }
1638
1639 if (execution_policy == eExecutionPolicyAlways ||
1640 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1641 execution_unit_sp->GetRunnableInfo(error&: err, func_addr, func_end);
1642 }
1643 } else {
1644 execution_unit_sp->GetRunnableInfo(error&: err, func_addr, func_end);
1645 }
1646
1647 return err;
1648}
1649

source code of lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp