LLDB mainline
ClangExpressionParser.cpp
Go to the documentation of this file.
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"
60#include "ClangUserExpression.h"
61
62#include "ASTUtils.h"
63#include "ClangASTSource.h"
66#include "ClangHost.h"
69#include "IRDynamicChecks.h"
70#include "IRForTarget.h"
72
74#include "lldb/Core/Debugger.h"
76#include "lldb/Core/Module.h"
79#include "lldb/Host/File.h"
80#include "lldb/Host/HostInfo.h"
85#include "lldb/Target/Process.h"
86#include "lldb/Target/Target.h"
91#include "lldb/Utility/Log.h"
92#include "lldb/Utility/Stream.h"
95
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
115 clang::SourceManager &m_source_mgr;
117 bool m_has_errors = false;
118
119public:
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(import_location).getFilename();
133 return;
134
135 SourceModule module;
136
137 for (const IdentifierLoc &component : path)
138 module.path.push_back(
139 ConstString(component.getIdentifierInfo()->getName()));
140
141 StreamString error_stream;
142
144 if (!m_decl_vendor.AddModule(module, &exported_modules, 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(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>(m_output);
172 std::make_shared<clang::TextDiagnosticPrinter>(*m_os, 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.
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>(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.
206 if (log) {
207 llvm::SmallVector<char, 32> diag_str;
208 Info.FormatDiagnostic(diag_str);
209 diag_str.push_back('\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(DiagLevel, Info);
222
223 DiagnosticDetail detail;
224 switch (DiagLevel) {
225 case DiagnosticsEngine::Level::Fatal:
226 case DiagnosticsEngine::Level::Error:
228 break;
229 case DiagnosticsEngine::Level::Warning:
231 break;
232 case DiagnosticsEngine::Level::Remark:
233 case DiagnosticsEngine::Level::Ignored:
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(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()) {
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(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("<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(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(msg);
290 detail.message = msg.str();
291 detail.rendered = stripped_output;
292 auto new_diagnostic =
293 std::make_unique<ClangDiagnostic>(detail, 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(new_diagnostic.get(), Info);
301
302 m_manager->AddDiagnostic(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:
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
322static void SetupModuleHeaderPaths(CompilerInstance *compiler,
323 std::vector<std::string> include_directories,
324 lldb::TargetSP target_sp) {
326
327 HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
328
329 for (const std::string &dir : include_directories) {
330 search_opts.AddPath(dir, frontend::System, false, true);
331 LLDB_LOG(log, "Added user include dir: {0}", dir);
332 }
333
334 llvm::SmallString<128> module_cache;
335 const auto &props = ModuleList::GetGlobalModuleListProperties();
336 props.GetClangModulesCachePath().GetPath(module_cache);
337 search_opts.ModuleCachePath = std::string(module_cache.str());
338 LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
339
340 search_opts.ResourceDir = GetClangResourceDir().GetPath();
341
342 search_opts.ImplicitModuleMaps = true;
343}
344
345/// Iff the given identifier is a C++ keyword, remove it from the
346/// identifier table (i.e., make the token a normal identifier).
347static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) {
348 // FIXME: 'using' is used by LLDB for local variables, so we can't remove
349 // this keyword without breaking this functionality.
350 if (token == "using")
351 return;
352 // GCC's '__null' is used by LLDB to define NULL/Nil/nil.
353 if (token == "__null")
354 return;
355
356 LangOptions cpp_lang_opts;
357 cpp_lang_opts.CPlusPlus = true;
358 cpp_lang_opts.CPlusPlus11 = true;
359 cpp_lang_opts.CPlusPlus20 = true;
360
361 clang::IdentifierInfo &ii = idents.get(token);
362 // The identifier has to be a C++-exclusive keyword. if not, then there is
363 // nothing to do.
364 if (!ii.isCPlusPlusKeyword(cpp_lang_opts))
365 return;
366 // If the token is already an identifier, then there is nothing to do.
367 if (ii.getTokenID() == clang::tok::identifier)
368 return;
369 // Otherwise the token is a C++ keyword, so turn it back into a normal
370 // identifier.
371 ii.revertTokenIDToIdentifier();
372}
373
374/// Remove all C++ keywords from the given identifier table.
375static void RemoveAllCppKeywords(IdentifierTable &idents) {
376#define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME));
377#include "clang/Basic/TokenKinds.def"
378}
379
380/// Configures Clang diagnostics for the expression parser.
381static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) {
382 // List of Clang warning groups that are not useful when parsing expressions.
383 const std::vector<const char *> groupsToIgnore = {
384 "unused-value",
385 "odr",
386 "unused-getter-return-value",
387 };
388 for (const char *group : groupsToIgnore) {
389 compiler.getDiagnostics().setSeverityForGroup(
390 clang::diag::Flavor::WarningOrError, group,
391 clang::diag::Severity::Ignored, SourceLocation());
392 }
393}
394
395/// Returns a string representing current ABI.
396///
397/// \param[in] target_arch
398/// The target architecture.
399///
400/// \return
401/// A string representing target ABI for the current architecture.
402static std::string GetClangTargetABI(const ArchSpec &target_arch) {
403 if (target_arch.IsMIPS()) {
404 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
406 return "n64";
408 return "n32";
410 return "o32";
411 default:
412 return {};
413 }
414 }
415
416 if (target_arch.GetTriple().isRISCV64()) {
417 switch (target_arch.GetFlags() & ArchSpec::eRISCV_float_abi_mask) {
419 return "lp64";
421 return "lp64f";
423 return "lp64d";
425 return "lp64q";
426 default:
427 return {};
428 }
429 }
430
431 if (target_arch.GetTriple().isRISCV32()) {
432 switch (target_arch.GetFlags() & ArchSpec::eRISCV_float_abi_mask) {
434 return "ilp32";
436 return "ilp32f";
438 return "ilp32d";
440 return "ilp32e";
441 default:
442 return {};
443 }
444 }
445
446 if (target_arch.GetTriple().isLoongArch64()) {
447 switch (target_arch.GetFlags() & ArchSpec::eLoongArch_abi_mask) {
449 return "lp64s";
451 return "lp64f";
453 return "lp64d";
454 default:
455 return {};
456 }
457 }
458
459 return {};
460}
461
462static void SetupTargetOpts(CompilerInstance &compiler,
463 lldb_private::Target const &target) {
465 ArchSpec target_arch = target.GetArchitecture();
466
467 const auto target_machine = target_arch.GetMachine();
468 if (target_arch.IsValid()) {
469 std::string triple = target_arch.GetTriple().str();
470 compiler.getTargetOpts().Triple = triple;
471 LLDB_LOGF(log, "Using %s as the target triple",
472 compiler.getTargetOpts().Triple.c_str());
473 } else {
474 // If we get here we don't have a valid target and just have to guess.
475 // Sometimes this will be ok to just use the host target triple (when we
476 // evaluate say "2+3", but other expressions like breakpoint conditions and
477 // other things that _are_ target specific really shouldn't just be using
478 // the host triple. In such a case the language runtime should expose an
479 // overridden options set (3), below.
480 compiler.getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
481 LLDB_LOGF(log, "Using default target triple of %s",
482 compiler.getTargetOpts().Triple.c_str());
483 }
484 // Now add some special fixes for known architectures: Any arm32 iOS
485 // environment, but not on arm64
486 if (compiler.getTargetOpts().Triple.find("arm64") == std::string::npos &&
487 compiler.getTargetOpts().Triple.find("arm") != std::string::npos &&
488 compiler.getTargetOpts().Triple.find("ios") != std::string::npos) {
489 compiler.getTargetOpts().ABI = "apcs-gnu";
490 }
491 // Supported subsets of x86
492 if (target_machine == llvm::Triple::x86 ||
493 target_machine == llvm::Triple::x86_64) {
494 compiler.getTargetOpts().FeaturesAsWritten.push_back("+sse");
495 compiler.getTargetOpts().FeaturesAsWritten.push_back("+sse2");
496 }
497
498 // Set the target CPU to generate code for. This will be empty for any CPU
499 // that doesn't really need to make a special
500 // CPU string.
501 compiler.getTargetOpts().CPU = target_arch.GetClangTargetCPU();
502
503 // Set the target ABI
504 if (std::string abi = GetClangTargetABI(target_arch); !abi.empty())
505 compiler.getTargetOpts().ABI = std::move(abi);
506
507 if ((target_machine == llvm::Triple::riscv64 &&
508 compiler.getTargetOpts().ABI == "lp64f") ||
509 (target_machine == llvm::Triple::riscv32 &&
510 compiler.getTargetOpts().ABI == "ilp32f"))
511 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+f");
512
513 if ((target_machine == llvm::Triple::riscv64 &&
514 compiler.getTargetOpts().ABI == "lp64d") ||
515 (target_machine == llvm::Triple::riscv32 &&
516 compiler.getTargetOpts().ABI == "ilp32d"))
517 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+d");
518
519 if ((target_machine == llvm::Triple::loongarch64 &&
520 compiler.getTargetOpts().ABI == "lp64f"))
521 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+f");
522
523 if ((target_machine == llvm::Triple::loongarch64 &&
524 compiler.getTargetOpts().ABI == "lp64d"))
525 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+d");
526}
527
528static void SetupLangOpts(CompilerInstance &compiler,
529 ExecutionContextScope &exe_scope,
530 const Expression &expr) {
532
533 // If the expression is being evaluated in the context of an existing stack
534 // frame, we introspect to see if the language runtime is available.
535
536 lldb::StackFrameSP frame_sp = exe_scope.CalculateStackFrame();
537 lldb::ProcessSP process_sp = exe_scope.CalculateProcess();
538
539 lldb::LanguageType language = expr.Language().AsLanguageType();
540
541 if (process_sp)
542 LLDB_LOG(
543 log,
544 "Frame has language of type {0}\nPicked {1} for expression evaluation.",
546 frame_sp ? frame_sp->GetLanguage().AsLanguageType()
549
550 LangOptions &lang_opts = compiler.getLangOpts();
551
552 switch (language) {
557 // FIXME: the following language option is a temporary workaround,
558 // to "ask for C, get C++."
559 // For now, the expression parser must use C++ anytime the language is a C
560 // family language, because the expression parser uses features of C++ to
561 // capture values.
562 lang_opts.CPlusPlus = true;
563 break;
565 lang_opts.ObjC = true;
566 // FIXME: the following language option is a temporary workaround,
567 // to "ask for ObjC, get ObjC++" (see comment above).
568 lang_opts.CPlusPlus = true;
569
570 // Clang now sets as default C++14 as the default standard (with
571 // GNU extensions), so we do the same here to avoid mismatches that
572 // cause compiler error when evaluating expressions (e.g. nullptr not found
573 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
574 // two lines below) so we decide to be consistent with that, but this could
575 // be re-evaluated in the future.
576 lang_opts.CPlusPlus11 = true;
577 break;
579 lang_opts.CPlusPlus20 = true;
580 [[fallthrough]];
582 // FIXME: add a separate case for CPlusPlus14. Currently folded into C++17
583 // because C++14 is the default standard for Clang but enabling CPlusPlus14
584 // expression evaluatino doesn't pass the test-suite cleanly.
585 lang_opts.CPlusPlus14 = true;
586 lang_opts.CPlusPlus17 = true;
587 [[fallthrough]];
591 lang_opts.CPlusPlus11 = true;
592 compiler.getHeaderSearchOpts().UseLibcxx = true;
593 [[fallthrough]];
595 lang_opts.CPlusPlus = true;
596 if (process_sp
597 // We're stopped in a frame without debug-info. The user probably
598 // intends to make global queries (which should include Objective-C).
599 && !(frame_sp && frame_sp->HasDebugInformation()))
600 lang_opts.ObjC =
601 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
602 break;
605 default:
606 lang_opts.ObjC = true;
607 lang_opts.CPlusPlus = true;
608 lang_opts.CPlusPlus11 = true;
609 compiler.getHeaderSearchOpts().UseLibcxx = true;
610 break;
611 }
612
613 lang_opts.Bool = true;
614 lang_opts.WChar = true;
615 lang_opts.Blocks = true;
616 lang_opts.DebuggerSupport =
617 true; // Features specifically for debugger clients
619 lang_opts.DebuggerCastResultToId = true;
620
621 lang_opts.CharIsSigned =
622 ArchSpec(compiler.getTargetOpts().Triple.c_str()).CharIsSignedByDefault();
623
624 // Spell checking is a nice feature, but it ends up completing a lot of types
625 // that we didn't strictly speaking need to complete. As a result, we spend a
626 // long time parsing and importing debug information.
627 lang_opts.SpellChecking = false;
628
629 if (process_sp && lang_opts.ObjC) {
630 if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
631 switch (runtime->GetRuntimeVersion()) {
633 lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
634 break;
637 lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
638 VersionTuple(10, 7));
639 break;
641 lang_opts.ObjCRuntime.set(ObjCRuntime::GNUstep, VersionTuple(2, 0));
642 break;
643 }
644
645 if (runtime->HasNewLiteralsAndIndexing())
646 lang_opts.DebuggerObjCLiteral = true;
647 }
648 }
649
650 lang_opts.ThreadsafeStatics = false;
651 lang_opts.AccessControl = false; // Debuggers get universal access
652 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
653 // We enable all builtin functions beside the builtins from libc/libm (e.g.
654 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
655 // additionally enabling them as expandable builtins is breaking Clang.
656 lang_opts.NoBuiltin = true;
657}
658
659static void SetupImportStdModuleLangOpts(CompilerInstance &compiler,
660 lldb_private::Target &target) {
661 LangOptions &lang_opts = compiler.getLangOpts();
662 lang_opts.Modules = true;
663 // We want to implicitly build modules.
664 lang_opts.ImplicitModules = true;
665 // To automatically import all submodules when we import 'std'.
666 lang_opts.ModulesLocalVisibility = false;
667
668 // We use the @import statements, so we need this:
669 // FIXME: We could use the modules-ts, but that currently doesn't work.
670 lang_opts.ObjC = true;
671
672 // Options we need to parse libc++ code successfully.
673 // FIXME: We should ask the driver for the appropriate default flags.
674 lang_opts.GNUMode = true;
675 lang_opts.GNUKeywords = true;
676 lang_opts.CPlusPlus11 = true;
677
678 lang_opts.BuiltinHeadersInSystemModules = false;
679
680 // The Darwin libc expects this macro to be set.
681 lang_opts.GNUCVersion = 40201;
682}
683
684//===----------------------------------------------------------------------===//
685// Implementation of ClangExpressionParser
686//===----------------------------------------------------------------------===//
687
689 ExecutionContextScope *exe_scope, Expression &expr,
690 bool generate_debug_info, std::vector<std::string> include_directories,
691 std::string filename)
692 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
693 m_pp_callbacks(nullptr),
694 m_include_directories(std::move(include_directories)),
695 m_filename(std::move(filename)) {
697
698 // We can't compile expressions without a target. So if the exe_scope is
699 // null or doesn't have a target, then we just need to get out of here. I'll
700 // lldbassert and not make any of the compiler objects since
701 // I can't return errors directly from the constructor. Further calls will
702 // check if the compiler was made and
703 // bag out if it wasn't.
704
705 if (!exe_scope) {
706 lldbassert(exe_scope &&
707 "Can't make an expression parser with a null scope.");
708 return;
709 }
710
711 lldb::TargetSP target_sp;
712 target_sp = exe_scope->CalculateTarget();
713 if (!target_sp) {
714 lldbassert(target_sp.get() &&
715 "Can't make an expression parser with a null target.");
716 return;
717 }
718
719 // 1. Create a new compiler instance.
720 m_compiler = std::make_unique<CompilerInstance>();
721
722 // Make sure clang uses the same VFS as LLDB.
723 m_compiler->setVirtualFileSystem(
724 FileSystem::Instance().GetVirtualFileSystem());
725 m_compiler->createFileManager();
726
727 // 2. Configure the compiler with a set of default options that are
728 // appropriate for most situations.
729 SetupTargetOpts(*m_compiler, *target_sp);
730
731 // 3. Create and install the target on the compiler.
732 m_compiler->createDiagnostics();
733 // Limit the number of error diagnostics we emit.
734 // A value of 0 means no limit for both LLDB and Clang.
735 m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());
736
737 if (auto *target_info = TargetInfo::CreateTargetInfo(
738 m_compiler->getDiagnostics(),
739 m_compiler->getInvocation().getTargetOpts())) {
740 if (log) {
741 LLDB_LOGF(log, "Target datalayout string: '%s'",
742 target_info->getDataLayoutString());
743 LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
744 LLDB_LOGF(log, "Target vector alignment: %d",
745 target_info->getMaxVectorAlign());
746 }
747 m_compiler->setTarget(target_info);
748 } else {
749 if (log)
750 LLDB_LOGF(log, "Failed to create TargetInfo for '%s'",
751 m_compiler->getTargetOpts().Triple.c_str());
752
753 lldbassert(false && "Failed to create TargetInfo.");
754 }
755
756 // 4. Set language options.
757 SetupLangOpts(*m_compiler, *exe_scope, expr);
758 auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
759 if (clang_expr && clang_expr->DidImportCxxModules()) {
760 LLDB_LOG(log, "Adding lang options for importing C++ modules");
763 }
764
765 // Set CodeGen options
766 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
767 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
768 m_compiler->getCodeGenOpts().setFramePointer(
769 CodeGenOptions::FramePointerKind::All);
770 if (generate_debug_info)
771 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
772 else
773 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
774
775 // Disable some warnings.
777
778 // Inform the target of the language options
779 //
780 // FIXME: We shouldn't need to do this, the target should be immutable once
781 // created. This complexity should be lifted elsewhere.
782 m_compiler->getTarget().adjust(m_compiler->getDiagnostics(),
783 m_compiler->getLangOpts(),
784 /*AuxTarget=*/nullptr);
785
786 // 5. Set up the diagnostic buffer for reporting errors
787 auto diag_mgr = new ClangDiagnosticManagerAdapter(
788 m_compiler->getDiagnostics().getDiagnosticOptions(),
789 clang_expr ? clang_expr->GetFilename() : StringRef());
790 m_compiler->getDiagnostics().setClient(diag_mgr);
791
792 // 6. Set up the source management objects inside the compiler
793 m_compiler->createFileManager();
794 if (!m_compiler->hasSourceManager())
795 m_compiler->createSourceManager(m_compiler->getFileManager());
796 m_compiler->createPreprocessor(TU_Complete);
797
798 switch (expr.Language().AsLanguageType()) {
804 // This is not a C++ expression but we enabled C++ as explained above.
805 // Remove all C++ keywords from the PP so that the user can still use
806 // variables that have C++ keywords as names (e.g. 'int template;').
807 RemoveAllCppKeywords(m_compiler->getPreprocessor().getIdentifierTable());
808 break;
809 default:
810 break;
811 }
812
813 if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(
814 target_sp->GetPersistentExpressionStateForLanguage(
816 if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
817 clang_persistent_vars->GetClangModulesDeclVendor()) {
818 std::unique_ptr<PPCallbacks> pp_callbacks(
819 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,
820 m_compiler->getSourceManager()));
822 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
823 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
824 }
825 }
826
827 // 7. Most of this we get from the CompilerInstance, but we also want to give
828 // the context an ExternalASTSource.
829
830 auto &PP = m_compiler->getPreprocessor();
831 auto &builtin_context = PP.getBuiltinInfo();
832 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
833 m_compiler->getLangOpts());
834
835 m_compiler->createASTContext();
836 clang::ASTContext &ast_context = m_compiler->getASTContext();
837
838 m_ast_context = std::make_shared<TypeSystemClang>(
839 "Expression ASTContext for '" + m_filename + "'", ast_context);
840
841 std::string module_name("$__lldb_module");
842
843 m_llvm_context = std::make_unique<LLVMContext>();
844 m_code_generator.reset(CreateLLVMCodeGen(
845 m_compiler->getDiagnostics(), module_name,
846 m_compiler->getVirtualFileSystemPtr(), m_compiler->getHeaderSearchOpts(),
847 m_compiler->getPreprocessorOpts(), m_compiler->getCodeGenOpts(),
849}
850
852
853namespace {
854
855/// \class CodeComplete
856///
857/// A code completion consumer for the clang Sema that is responsible for
858/// creating the completion suggestions when a user requests completion
859/// of an incomplete `expr` invocation.
860class CodeComplete : public CodeCompleteConsumer {
861 CodeCompletionTUInfo m_info;
862
863 std::string m_expr;
864 unsigned m_position = 0;
865 /// The printing policy we use when printing declarations for our completion
866 /// descriptions.
867 clang::PrintingPolicy m_desc_policy;
868
869 struct CompletionWithPriority {
871 /// See CodeCompletionResult::Priority;
872 unsigned Priority;
873
874 /// Establishes a deterministic order in a list of CompletionWithPriority.
875 /// The order returned here is the order in which the completions are
876 /// displayed to the user.
877 bool operator<(const CompletionWithPriority &o) const {
878 // High priority results should come first.
879 if (Priority != o.Priority)
880 return Priority > o.Priority;
881
882 // Identical priority, so just make sure it's a deterministic order.
883 return completion.GetUniqueKey() < o.completion.GetUniqueKey();
884 }
885 };
886
887 /// The stored completions.
888 /// Warning: These are in a non-deterministic order until they are sorted
889 /// and returned back to the caller.
890 std::vector<CompletionWithPriority> m_completions;
891
892 /// Returns true if the given character can be used in an identifier.
893 /// This also returns true for numbers because for completion we usually
894 /// just iterate backwards over iterators.
895 ///
896 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
897 static bool IsIdChar(char c) {
898 return c == '_' || std::isalnum(c) || c == '$';
899 }
900
901 /// Returns true if the given character is used to separate arguments
902 /// in the command line of lldb.
903 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
904
905 /// Drops all tokens in front of the expression that are unrelated for
906 /// the completion of the cmd line. 'unrelated' means here that the token
907 /// is not interested for the lldb completion API result.
908 StringRef dropUnrelatedFrontTokens(StringRef cmd) const {
909 if (cmd.empty())
910 return cmd;
911
912 // If we are at the start of a word, then all tokens are unrelated to
913 // the current completion logic.
914 if (IsTokenSeparator(cmd.back()))
915 return StringRef();
916
917 // Remove all previous tokens from the string as they are unrelated
918 // to completing the current token.
919 StringRef to_remove = cmd;
920 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
921 to_remove = to_remove.drop_back();
922 }
923 cmd = cmd.drop_front(to_remove.size());
924
925 return cmd;
926 }
927
928 /// Removes the last identifier token from the given cmd line.
929 StringRef removeLastToken(StringRef cmd) const {
930 while (!cmd.empty() && IsIdChar(cmd.back())) {
931 cmd = cmd.drop_back();
932 }
933 return cmd;
934 }
935
936 /// Attempts to merge the given completion from the given position into the
937 /// existing command. Returns the completion string that can be returned to
938 /// the lldb completion API.
939 std::string mergeCompletion(StringRef existing, unsigned pos,
940 StringRef completion) const {
941 StringRef existing_command = existing.substr(0, pos);
942 // We rewrite the last token with the completion, so let's drop that
943 // token from the command.
944 existing_command = removeLastToken(existing_command);
945 // We also should remove all previous tokens from the command as they
946 // would otherwise be added to the completion that already has the
947 // completion.
948 existing_command = dropUnrelatedFrontTokens(existing_command);
949 return existing_command.str() + completion.str();
950 }
951
952public:
953 /// Constructs a CodeComplete consumer that can be attached to a Sema.
954 ///
955 /// \param[out] expr
956 /// The whole expression string that we are currently parsing. This
957 /// string needs to be equal to the input the user typed, and NOT the
958 /// final code that Clang is parsing.
959 /// \param[out] position
960 /// The character position of the user cursor in the `expr` parameter.
961 ///
962 CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)
963 : CodeCompleteConsumer(CodeCompleteOptions()),
964 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
965 m_position(position), m_desc_policy(ops) {
966
967 // Ensure that the printing policy is producing a description that is as
968 // short as possible.
969 m_desc_policy.SuppressScope = true;
970 m_desc_policy.SuppressTagKeyword = true;
971 m_desc_policy.FullyQualifiedName = false;
972 m_desc_policy.TerseOutput = true;
973 m_desc_policy.IncludeNewlines = false;
974 m_desc_policy.UseVoidForZeroParams = false;
975 m_desc_policy.Bool = true;
976 }
977
978 /// \name Code-completion filtering
979 /// Check if the result should be filtered out.
980 bool isResultFilteredOut(StringRef Filter,
981 CodeCompletionResult Result) override {
982 // This code is mostly copied from CodeCompleteConsumer.
983 switch (Result.Kind) {
984 case CodeCompletionResult::RK_Declaration:
985 return !(
986 Result.Declaration->getIdentifier() &&
987 Result.Declaration->getIdentifier()->getName().starts_with(Filter));
988 case CodeCompletionResult::RK_Keyword:
989 return !StringRef(Result.Keyword).starts_with(Filter);
990 case CodeCompletionResult::RK_Macro:
991 return !Result.Macro->getName().starts_with(Filter);
992 case CodeCompletionResult::RK_Pattern:
993 return !StringRef(Result.Pattern->getAsString()).starts_with(Filter);
994 }
995 // If we trigger this assert or the above switch yields a warning, then
996 // CodeCompletionResult has been enhanced with more kinds of completion
997 // results. Expand the switch above in this case.
998 assert(false && "Unknown completion result type?");
999 // If we reach this, then we should just ignore whatever kind of unknown
1000 // result we got back. We probably can't turn it into any kind of useful
1001 // completion suggestion with the existing code.
1002 return true;
1003 }
1004
1005private:
1006 /// Generate the completion strings for the given CodeCompletionResult.
1007 /// Note that this function has to process results that could come in
1008 /// non-deterministic order, so this function should have no side effects.
1009 /// To make this easier to enforce, this function and all its parameters
1010 /// should always be const-qualified.
1011 /// \return Returns std::nullopt if no completion should be provided for the
1012 /// given CodeCompletionResult.
1013 std::optional<CompletionWithPriority>
1014 getCompletionForResult(const CodeCompletionResult &R) const {
1015 std::string ToInsert;
1016 std::string Description;
1017 // Handle the different completion kinds that come from the Sema.
1018 switch (R.Kind) {
1019 case CodeCompletionResult::RK_Declaration: {
1020 const NamedDecl *D = R.Declaration;
1021 ToInsert = R.Declaration->getNameAsString();
1022 // If we have a function decl that has no arguments we want to
1023 // complete the empty parantheses for the user. If the function has
1024 // arguments, we at least complete the opening bracket.
1025 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
1026 if (F->getNumParams() == 0)
1027 ToInsert += "()";
1028 else
1029 ToInsert += "(";
1030 raw_string_ostream OS(Description);
1031 F->print(OS, m_desc_policy, false);
1032 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
1033 Description = V->getType().getAsString(m_desc_policy);
1034 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
1035 Description = F->getType().getAsString(m_desc_policy);
1036 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
1037 // If we try to complete a namespace, then we can directly append
1038 // the '::'.
1039 if (!N->isAnonymousNamespace())
1040 ToInsert += "::";
1041 }
1042 break;
1043 }
1044 case CodeCompletionResult::RK_Keyword:
1045 ToInsert = R.Keyword;
1046 break;
1047 case CodeCompletionResult::RK_Macro:
1048 ToInsert = R.Macro->getName().str();
1049 break;
1050 case CodeCompletionResult::RK_Pattern:
1051 ToInsert = R.Pattern->getTypedText();
1052 break;
1053 }
1054 // We also filter some internal lldb identifiers here. The user
1055 // shouldn't see these.
1056 if (llvm::StringRef(ToInsert).starts_with("$__lldb_"))
1057 return std::nullopt;
1058 if (ToInsert.empty())
1059 return std::nullopt;
1060 // Merge the suggested Token into the existing command line to comply
1061 // with the kind of result the lldb API expects.
1062 std::string CompletionSuggestion =
1063 mergeCompletion(m_expr, m_position, ToInsert);
1064
1065 CompletionResult::Completion completion(CompletionSuggestion, Description,
1066 CompletionMode::Normal);
1067 return {{completion, R.Priority}};
1068 }
1069
1070public:
1071 /// Adds the completions to the given CompletionRequest.
1072 void GetCompletions(CompletionRequest &request) {
1073 // Bring m_completions into a deterministic order and pass it on to the
1074 // CompletionRequest.
1075 llvm::sort(m_completions);
1076
1077 for (const CompletionWithPriority &C : m_completions)
1078 request.AddCompletion(C.completion.GetCompletion(),
1079 C.completion.GetDescription(),
1080 C.completion.GetMode());
1081 }
1082
1083 /// \name Code-completion callbacks
1084 /// Process the finalized code-completion results.
1085 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
1086 CodeCompletionResult *Results,
1087 unsigned NumResults) override {
1088
1089 // The Sema put the incomplete token we try to complete in here during
1090 // lexing, so we need to retrieve it here to know what we are completing.
1091 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
1092
1093 // Iterate over all the results. Filter out results we don't want and
1094 // process the rest.
1095 for (unsigned I = 0; I != NumResults; ++I) {
1096 // Filter the results with the information from the Sema.
1097 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
1098 continue;
1099
1100 CodeCompletionResult &R = Results[I];
1101 std::optional<CompletionWithPriority> CompletionAndPriority =
1102 getCompletionForResult(R);
1103 if (!CompletionAndPriority)
1104 continue;
1105 m_completions.push_back(*CompletionAndPriority);
1106 }
1107 }
1108
1109 /// \param S the semantic-analyzer object for which code-completion is being
1110 /// done.
1111 ///
1112 /// \param CurrentArg the index of the current argument.
1113 ///
1114 /// \param Candidates an array of overload candidates.
1115 ///
1116 /// \param NumCandidates the number of overload candidates
1117 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1118 OverloadCandidate *Candidates,
1119 unsigned NumCandidates,
1120 SourceLocation OpenParLoc,
1121 bool Braced) override {
1122 // At the moment we don't filter out any overloaded candidates.
1123 }
1124
1125 CodeCompletionAllocator &getAllocator() override {
1126 return m_info.getAllocator();
1127 }
1128
1129 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
1130};
1131} // namespace
1132
1134 unsigned pos, unsigned typed_pos) {
1136 // We need the raw user expression here because that's what the CodeComplete
1137 // class uses to provide completion suggestions.
1138 // However, the `Text` method only gives us the transformed expression here.
1139 // To actually get the raw user input here, we have to cast our expression to
1140 // the LLVMUserExpression which exposes the right API. This should never fail
1141 // as we always have a ClangUserExpression whenever we call this.
1142 ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
1143 CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(),
1144 typed_pos);
1145 // We don't need a code generator for parsing.
1146 m_code_generator.reset();
1147 // Start parsing the expression with our custom code completion consumer.
1148 ParseInternal(mgr, &CC, line, pos);
1149 CC.GetCompletions(request);
1150 return true;
1151}
1152
1154 return ParseInternal(diagnostic_manager);
1155}
1156
1157unsigned
1159 CodeCompleteConsumer *completion_consumer,
1160 unsigned completion_line,
1161 unsigned completion_column) {
1163 static_cast<ClangDiagnosticManagerAdapter *>(
1164 m_compiler->getDiagnostics().getClient());
1165
1166 adapter->ResetManager(&diagnostic_manager);
1167
1168 const char *expr_text = m_expr.Text();
1169
1170 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
1171 bool created_main_file = false;
1172
1173 // Clang wants to do completion on a real file known by Clang's file manager,
1174 // so we have to create one to make this work.
1175 // TODO: We probably could also simulate to Clang's file manager that there
1176 // is a real file that contains our code.
1177 bool should_create_file = completion_consumer != nullptr;
1178
1179 // We also want a real file on disk if we generate full debug info.
1180 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
1181 codegenoptions::FullDebugInfo;
1182
1183 if (should_create_file) {
1184 int temp_fd = -1;
1185 llvm::SmallString<128> result_path;
1186 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
1187 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
1188 std::string temp_source_path = tmpdir_file_spec.GetPath();
1189 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
1190 } else {
1191 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
1192 }
1193
1194 if (temp_fd != -1) {
1196 const size_t expr_text_len = strlen(expr_text);
1197 size_t bytes_written = expr_text_len;
1198 if (file.Write(expr_text, bytes_written).Success()) {
1199 if (bytes_written == expr_text_len) {
1200 file.Close();
1201 if (auto fileEntry = m_compiler->getFileManager().getOptionalFileRef(
1202 result_path)) {
1203 source_mgr.setMainFileID(source_mgr.createFileID(
1204 *fileEntry, SourceLocation(), SrcMgr::C_User));
1205 created_main_file = true;
1206 }
1207 }
1208 }
1209 }
1210 }
1211
1212 if (!created_main_file) {
1213 std::unique_ptr<MemoryBuffer> memory_buffer =
1214 MemoryBuffer::getMemBufferCopy(expr_text, m_filename);
1215 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
1216 }
1217
1218 adapter->BeginSourceFile(m_compiler->getLangOpts(),
1219 &m_compiler->getPreprocessor());
1220
1221 ClangExpressionHelper *type_system_helper =
1222 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1223
1224 // If we want to parse for code completion, we need to attach our code
1225 // completion consumer to the Sema and specify a completion position.
1226 // While parsing the Sema will call this consumer with the provided
1227 // completion suggestions.
1228 if (completion_consumer) {
1229 auto main_file =
1230 source_mgr.getFileEntryRefForID(source_mgr.getMainFileID());
1231 auto &PP = m_compiler->getPreprocessor();
1232 // Lines and columns start at 1 in Clang, but code completion positions are
1233 // indexed from 0, so we need to add 1 to the line and column here.
1234 ++completion_line;
1235 ++completion_column;
1236 PP.SetCodeCompletionPoint(*main_file, completion_line, completion_column);
1237 }
1238
1239 ASTConsumer *ast_transformer =
1240 type_system_helper->ASTTransformer(m_code_generator.get());
1241
1242 std::unique_ptr<clang::ASTConsumer> Consumer;
1243 if (ast_transformer) {
1244 Consumer = std::make_unique<ASTConsumerForwarder>(ast_transformer);
1245 } else if (m_code_generator) {
1246 Consumer = std::make_unique<ASTConsumerForwarder>(m_code_generator.get());
1247 } else {
1248 Consumer = std::make_unique<ASTConsumer>();
1249 }
1250
1251 clang::ASTContext &ast_context = m_compiler->getASTContext();
1252
1253 m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
1254 *Consumer, TU_Complete, completion_consumer));
1255 m_compiler->setASTConsumer(std::move(Consumer));
1256
1257 if (ast_context.getLangOpts().Modules) {
1258 m_compiler->createASTReader();
1259 m_ast_context->setSema(&m_compiler->getSema());
1260 }
1261
1262 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
1263 if (decl_map) {
1264 decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
1265 decl_map->InstallDiagnosticManager(diagnostic_manager);
1266
1267 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source =
1268 decl_map->CreateProxy();
1269
1270 auto ast_source_wrapper =
1271 llvm::makeIntrusiveRefCnt<ExternalASTSourceWrapper>(ast_source);
1272
1273 if (ast_context.getExternalSource()) {
1274 auto module_wrapper = llvm::makeIntrusiveRefCnt<ExternalASTSourceWrapper>(
1275 ast_context.getExternalSourcePtr());
1276
1277 auto multiplexer = llvm::makeIntrusiveRefCnt<SemaSourceWithPriorities>(
1278 module_wrapper, ast_source_wrapper);
1279
1280 ast_context.setExternalSource(multiplexer);
1281 } else {
1282 ast_context.setExternalSource(ast_source);
1283 }
1284 m_compiler->getSema().addExternalSource(ast_source_wrapper);
1285 decl_map->InstallASTContext(*m_ast_context);
1286 }
1287
1288 // Check that the ASTReader is properly attached to ASTContext and Sema.
1289 if (ast_context.getLangOpts().Modules) {
1290 assert(m_compiler->getASTContext().getExternalSource() &&
1291 "ASTContext doesn't know about the ASTReader?");
1292 assert(m_compiler->getSema().getExternalSource() &&
1293 "Sema doesn't know about the ASTReader?");
1294 }
1295
1296 {
1297 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1298 &m_compiler->getSema());
1299 ParseAST(m_compiler->getSema(), false, false);
1300 }
1301
1302 // Make sure we have no pointer to the Sema we are about to destroy.
1303 if (ast_context.getLangOpts().Modules)
1304 m_ast_context->setSema(nullptr);
1305 // Destroy the Sema. This is necessary because we want to emulate the
1306 // original behavior of ParseAST (which also destroys the Sema after parsing).
1307 m_compiler->setSema(nullptr);
1308
1309 adapter->EndSourceFile();
1310
1311 unsigned num_errors = adapter->getNumErrors();
1312
1313 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1314 num_errors++;
1315 diagnostic_manager.PutString(lldb::eSeverityError,
1316 "while importing modules:");
1317 diagnostic_manager.AppendMessageToDiagnostic(
1318 m_pp_callbacks->getErrorString());
1319 }
1320
1321 if (!num_errors) {
1322 type_system_helper->CommitPersistentDecls();
1323 }
1324
1325 adapter->ResetManager();
1326
1327 return num_errors;
1328}
1329
1330/// Applies the given Fix-It hint to the given commit.
1331static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) {
1332 // This is cobbed from clang::Rewrite::FixItRewriter.
1333 if (fixit.CodeToInsert.empty()) {
1334 if (fixit.InsertFromRange.isValid()) {
1335 commit.insertFromRange(fixit.RemoveRange.getBegin(),
1336 fixit.InsertFromRange, /*afterToken=*/false,
1337 fixit.BeforePreviousInsertions);
1338 return;
1339 }
1340 commit.remove(fixit.RemoveRange);
1341 return;
1342 }
1343 if (fixit.RemoveRange.isTokenRange() ||
1344 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) {
1345 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1346 return;
1347 }
1348 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1349 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1350}
1351
1353 DiagnosticManager &diagnostic_manager) {
1354 clang::SourceManager &source_manager = m_compiler->getSourceManager();
1355 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1356 nullptr);
1357 clang::edit::Commit commit(editor);
1358 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1359
1360 class RewritesReceiver : public edit::EditsReceiver {
1361 Rewriter &rewrite;
1362
1363 public:
1364 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1365
1366 void insert(SourceLocation loc, StringRef text) override {
1367 rewrite.InsertText(loc, text);
1368 }
1369 void replace(CharSourceRange range, StringRef text) override {
1370 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1371 }
1372 };
1373
1374 RewritesReceiver rewrites_receiver(rewriter);
1375
1376 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1377 size_t num_diags = diagnostics.size();
1378 if (num_diags == 0)
1379 return false;
1380
1381 for (const auto &diag : diagnostic_manager.Diagnostics()) {
1382 const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get());
1383 if (!diagnostic)
1384 continue;
1385 if (!diagnostic->HasFixIts())
1386 continue;
1387 for (const FixItHint &fixit : diagnostic->FixIts())
1388 ApplyFixIt(fixit, commit);
1389 }
1390
1391 // FIXME - do we want to try to propagate specific errors here?
1392 if (!commit.isCommitable())
1393 return false;
1394 else if (!editor.commit(commit))
1395 return false;
1396
1397 // Now play all the edits, and stash the result in the diagnostic manager.
1398 editor.applyRewrites(rewrites_receiver);
1399 RewriteBuffer &main_file_buffer =
1400 rewriter.getEditBuffer(source_manager.getMainFileID());
1401
1402 std::string fixed_expression;
1403 llvm::raw_string_ostream out_stream(fixed_expression);
1404
1405 main_file_buffer.write(out_stream);
1406 diagnostic_manager.SetFixedExpression(fixed_expression);
1407
1408 return true;
1409}
1410
1411static bool FindFunctionInModule(ConstString &mangled_name,
1412 llvm::Module *module, const char *orig_name) {
1413 for (const auto &func : module->getFunctionList()) {
1414 const StringRef &name = func.getName();
1415 if (name.contains(orig_name)) {
1416 mangled_name.SetString(name);
1417 return true;
1418 }
1419 }
1420
1421 return false;
1422}
1423
1425 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1426 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1427 bool &can_interpret, ExecutionPolicy execution_policy) {
1428 func_addr = LLDB_INVALID_ADDRESS;
1429 func_end = LLDB_INVALID_ADDRESS;
1431
1433
1434 std::unique_ptr<llvm::Module> llvm_module_up(
1435 m_code_generator->ReleaseModule());
1436
1437 if (!llvm_module_up) {
1438 err = Status::FromErrorString("IR doesn't contain a module");
1439 return err;
1440 }
1441
1442 ConstString function_name;
1443
1444 if (execution_policy != eExecutionPolicyTopLevel) {
1445 // Find the actual name of the function (it's often mangled somehow)
1446
1447 if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1448 m_expr.FunctionName())) {
1450 "Couldn't find %s() in the module", m_expr.FunctionName());
1451 return err;
1452 } else {
1453 LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(),
1454 m_expr.FunctionName());
1455 }
1456 }
1457
1458 SymbolContext sc;
1459
1460 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1461 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1462 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1463 sc.target_sp = target_sp;
1464 }
1465
1466 LLVMUserExpression::IRPasses custom_passes;
1467 {
1468 auto lang = m_expr.Language();
1469 LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,
1470 lang.GetDescription().data());
1471 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1472 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1473 auto runtime = process_sp->GetLanguageRuntime(lang.AsLanguageType());
1474 if (runtime)
1475 runtime->GetIRPasses(custom_passes);
1476 }
1477 }
1478
1479 if (custom_passes.EarlyPasses) {
1480 LLDB_LOGF(log,
1481 "%s - Running Early IR Passes from LanguageRuntime on "
1482 "expression module '%s'",
1483 __FUNCTION__, m_expr.FunctionName());
1484
1485 custom_passes.EarlyPasses->run(*llvm_module_up);
1486 }
1487
1488 execution_unit_sp = std::make_shared<IRExecutionUnit>(
1489 m_llvm_context, // handed off here
1490 llvm_module_up, // handed off here
1491 function_name, exe_ctx.GetTargetSP(), sc,
1492 m_compiler->getTargetOpts().Features);
1493
1494 if (auto *options = m_expr.GetOptions())
1495 execution_unit_sp->AppendPreferredSymbolContexts(
1496 options->GetPreferredSymbolContexts());
1497
1498 ClangExpressionHelper *type_system_helper =
1499 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1500 ClangExpressionDeclMap *decl_map =
1501 type_system_helper->DeclMap(); // result can be NULL
1502
1503 if (decl_map) {
1504 StreamString error_stream;
1505 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1506 *execution_unit_sp, error_stream,
1507 function_name.AsCString());
1508
1509 if (!ir_for_target.runOnModule(*execution_unit_sp->GetModule())) {
1510 err = Status(error_stream.GetString().str());
1511 return err;
1512 }
1513
1514 Process *process = exe_ctx.GetProcessPtr();
1515
1516 if (execution_policy != eExecutionPolicyAlways &&
1517 execution_policy != eExecutionPolicyTopLevel) {
1518 lldb_private::Status interpret_error;
1519
1520 bool interpret_function_calls =
1521 !process ? false : process->CanInterpretFunctionCalls();
1522 can_interpret = IRInterpreter::CanInterpret(
1523 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1524 interpret_error, interpret_function_calls);
1525
1526 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1528 "Can't evaluate the expression without a running target due to: %s",
1529 interpret_error.AsCString());
1530 return err;
1531 }
1532 }
1533
1534 if (!process && execution_policy == eExecutionPolicyAlways) {
1536 "Expression needed to run in the target, but the "
1537 "target can't be run");
1538 return err;
1539 }
1540
1541 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1543 "Top-level code needs to be inserted into a runnable "
1544 "target, but the target can't be run");
1545 return err;
1546 }
1547
1548 if (execution_policy == eExecutionPolicyAlways ||
1549 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1550 if (m_expr.NeedsValidation() && process) {
1551 if (!process->GetDynamicCheckers()) {
1552 ClangDynamicCheckerFunctions *dynamic_checkers =
1554
1555 DiagnosticManager install_diags;
1556 if (Error Err = dynamic_checkers->Install(install_diags, exe_ctx))
1557 return Status::FromError(install_diags.GetAsError(
1558 lldb::eExpressionSetupError, "couldn't install checkers:"));
1559
1560 process->SetDynamicCheckers(dynamic_checkers);
1561
1562 LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "
1563 "Finished installing dynamic checkers ==");
1564 }
1565
1566 if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1567 process->GetDynamicCheckers())) {
1568 IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1569 function_name.AsCString());
1570
1571 llvm::Module *module = execution_unit_sp->GetModule();
1572 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1574 "Couldn't add dynamic checks to the expression");
1575 return err;
1576 }
1577
1578 if (custom_passes.LatePasses) {
1579 LLDB_LOGF(log,
1580 "%s - Running Late IR Passes from LanguageRuntime on "
1581 "expression module '%s'",
1582 __FUNCTION__, m_expr.FunctionName());
1583
1584 custom_passes.LatePasses->run(*module);
1585 }
1586 }
1587 }
1588 }
1589
1590 if (execution_policy == eExecutionPolicyAlways ||
1591 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1592 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1593 }
1594 } else {
1595 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1596 }
1597
1598 return err;
1599}
static void SetupModuleHeaderPaths(CompilerInstance *compiler, std::vector< std::string > include_directories, lldb::TargetSP target_sp)
static void RemoveAllCppKeywords(IdentifierTable &idents)
Remove all C++ keywords from the given identifier table.
static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit)
Applies the given Fix-It hint to the given commit.
static void SetupImportStdModuleLangOpts(CompilerInstance &compiler, lldb_private::Target &target)
static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info)
static void SetupDefaultClangDiagnostics(CompilerInstance &compiler)
Configures Clang diagnostics for the expression parser.
static void SetupLangOpts(CompilerInstance &compiler, ExecutionContextScope &exe_scope, const Expression &expr)
static void SetupTargetOpts(CompilerInstance &compiler, lldb_private::Target const &target)
static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token)
Iff the given identifier is a C++ keyword, remove it from the identifier table (i....
static bool FindFunctionInModule(ConstString &mangled_name, llvm::Module *module, const char *orig_name)
static std::string GetClangTargetABI(const ArchSpec &target_arch)
Returns a string representing current ABI.
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override
std::shared_ptr< llvm::raw_string_ostream > m_os
Output stream of m_passthrough.
std::string m_output
Output string filled by m_os.
std::shared_ptr< clang::TextDiagnosticPrinter > m_passthrough
ClangDiagnosticManagerAdapter(DiagnosticOptions &opts, StringRef filename)
void ResetManager(DiagnosticManager *manager=nullptr)
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) override
ClangDiagnostic * MaybeGetLastClangDiag() const
Returns the last error ClangDiagnostic message that the DiagnosticManager received or a nullptr.
void moduleImport(SourceLocation import_location, clang::ModuleIdPath path, const clang::Module *) override
LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor, ClangPersistentVariables &persistent_vars, clang::SourceManager &source_mgr)
Transforms the IR for a function to run in the target.
Definition IRForTarget.h:61
bool runOnModule(llvm::Module &llvm_module)
Run this IR transformer on a single module.
static bool CanInterpret(llvm::Module &module, llvm::Function &function, lldb_private::Status &error, const bool support_function_calls)
An architecture specification class.
Definition ArchSpec.h:31
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:370
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:472
@ eLoongArch_abi_single_float
soft float
Definition ArchSpec.h:112
@ eLoongArch_abi_mask
double precision floating point, +d
Definition ArchSpec.h:116
@ eLoongArch_abi_double_float
single precision floating point, +f
Definition ArchSpec.h:114
bool IsMIPS() const
if MIPS architecture return true.
Definition ArchSpec.cpp:559
bool CharIsSignedByDefault() const
Returns true if 'char' is a signed type by default in the architecture false otherwise.
Definition ArchSpec.cpp:710
uint32_t GetFlags() const
Definition ArchSpec.h:543
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:681
@ eRISCV_float_abi_double
single precision floating point, +f
Definition ArchSpec.h:97
@ eRISCV_float_abi_soft
RVC, +c.
Definition ArchSpec.h:95
@ eRISCV_float_abi_quad
double precision floating point, +d
Definition ArchSpec.h:98
@ eRISCV_float_abi_mask
quad precision floating point, +q
Definition ArchSpec.h:99
@ eRISCV_float_abi_single
soft float
Definition ArchSpec.h:96
std::string GetClangTargetCPU() const
Returns a string representing current architecture as a target CPU for tools like compiler,...
Definition ArchSpec.cpp:599
llvm::IntrusiveRefCntPtr< clang::ExternalASTSource > CreateProxy()
void InstallASTContext(TypeSystemClang &ast_context)
void AddFixitHint(const clang::FixItHint &fixit)
llvm::Error Install(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) override
Install the utility functions into a process.
"lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are defined in LLDB's debug in...
void InstallDiagnosticManager(DiagnosticManager &diag_manager)
void InstallCodeGenerator(clang::ASTConsumer *code_gen)
virtual clang::ASTConsumer * ASTTransformer(clang::ASTConsumer *passthrough)=0
Return the object that the parser should allow to access ASTs.
virtual ClangExpressionDeclMap * DeclMap()=0
Return the object that the parser should use when resolving external values.
std::string m_filename
File name used for the user expression.
bool RewriteExpression(DiagnosticManager &diagnostic_manager) override
Try to use the FixIts in the diagnostic_manager to rewrite the expression.
unsigned ParseInternal(DiagnosticManager &diagnostic_manager, clang::CodeCompleteConsumer *completion=nullptr, unsigned completion_line=0, unsigned completion_column=0)
Parses the expression.
ClangExpressionParser(ExecutionContextScope *exe_scope, Expression &expr, bool generate_debug_info, std::vector< std::string > include_directories={}, std::string filename="<clang expression>")
Constructor.
std::unique_ptr< clang::CompilerInstance > m_compiler
The Clang compiler used to parse expressions into IR.
Status DoPrepareForExecution(lldb::addr_t &func_addr, lldb::addr_t &func_end, lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, bool &can_interpret, lldb_private::ExecutionPolicy execution_policy) override
Ready an already-parsed expression for execution, possibly evaluating it statically.
unsigned Parse(DiagnosticManager &diagnostic_manager)
Parse a single expression and convert it to IR using Clang.
bool Complete(CompletionRequest &request, unsigned line, unsigned pos, unsigned typed_pos) override
Attempts to find possible command line completions for the given expression.
~ClangExpressionParser() override
Destructor.
std::unique_ptr< llvm::LLVMContext > m_llvm_context
The LLVM context to generate IR into.
std::unique_ptr< clang::CodeGenerator > m_code_generator
The Clang object that generates IR.
LLDBPreprocessorCallbacks * m_pp_callbacks
Called when the preprocessor encounters module imports.
std::vector< std::string > m_include_directories
std::shared_ptr< TypeSystemClang > m_ast_context
static const llvm::StringRef g_prefix_file_name
The file name we use for the wrapper code that we inject before the user expression.
"lldb/Expression/ClangPersistentVariables.h" Manages persistent values that need to be preserved betw...
"lldb/Expression/ClangUserExpression.h" Encapsulates a single expression for use with Clang
"lldb/Utility/ArgCompletionRequest.h"
void AddCompletion(llvm::StringRef completion, llvm::StringRef description="", CompletionMode mode=CompletionMode::Normal)
Adds a possible completion string.
A single completion and all associated data.
std::string GetUniqueKey() const
Generates a string that uniquely identifies this completion result.
A uniqued constant string class.
Definition ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
void SetString(llvm::StringRef s)
size_t void PutString(lldb::Severity severity, llvm::StringRef str)
const DiagnosticList & Diagnostics() const
llvm::Error GetAsError(lldb::ExpressionResults result, llvm::Twine message={}) const
Returns an ExpressionError with arg as error code.
void SetFixedExpression(std::string fixed_expression)
void AppendMessageToDiagnostic(llvm::StringRef str)
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
virtual lldb::StackFrameSP CalculateStackFrame()=0
virtual lldb::ProcessSP CalculateProcess()=0
virtual lldb::TargetSP CalculateTarget()=0
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
ExpressionParser(ExecutionContextScope *exe_scope, Expression &expr, bool generate_debug_info)
Constructor.
Expression & m_expr
The expression to be parsed.
Encapsulates a single expression for use in lldb.
Definition Expression.h:32
virtual SourceLanguage Language() const
Return the language that should be used when parsing.
Definition Expression.h:52
virtual ResultType DesiredResultType() const
Return the desired result type of the function, or eResultTypeAny if indifferent.
Definition Expression.h:60
A file utility class.
Definition FileSpec.h:57
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
static FileSystem & Instance()
@ eOpenOptionWriteOnly
Definition File.h:52
"lldb/Expression/IRDynamicChecks.h" Adds dynamic checks to a user-entered expression to reduce its li...
bool runOnModule(llvm::Module &M) override
Run this IR transformer on a single module.
static const char * GetNameForLanguageType(lldb::LanguageType language)
Definition Language.cpp:266
static ModuleListProperties & GetGlobalModuleListProperties()
Status Close() override
Flush any buffers and release any resources owned by the file.
Definition File.cpp:346
Status Write(const void *buf, size_t &num_bytes) override
Write bytes from buf to a file at the current file position.
Definition File.cpp:613
static ObjCLanguageRuntime * Get(Process &process)
A plug-in interface definition class for debugging a process.
Definition Process.h:357
void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
Definition Process.cpp:1556
DynamicCheckerFunctions * GetDynamicCheckers()
Definition Process.h:2408
bool CanInterpretFunctionCalls()
Determines whether executing function calls using the interpreter is possible for this process.
Definition Process.h:2041
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:195
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:137
bool Success() const
Test for success condition.
Definition Status.cpp:304
llvm::StringRef GetString() const
Defines a symbol context baton that can be handed other debug core functions.
lldb::TargetSP target_sp
The Target for a given query.
const ArchSpec & GetArchitecture() const
Definition Target.h:1056
const char * GetUserText()
Return the string that the user typed.
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
FileSpec GetClangResourceDir()
ExecutionPolicy
Expression execution policies.
std::vector< std::unique_ptr< Diagnostic > > DiagnosticList
bool operator<(const Address &lhs, const Address &rhs)
Definition Address.cpp:980
std::shared_ptr< lldb_private::IRExecutionUnit > IRExecutionUnitSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
LanguageType
Programming language type.
@ eLanguageTypeC_plus_plus_20
ISO C++:2020.
@ eLanguageTypeC_plus_plus_14
ISO C++:2014.
@ eLanguageTypeC11
ISO C:2011.
@ eLanguageTypeC99
ISO C:1999.
@ eLanguageTypeC_plus_plus_03
ISO C++:2003.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC_plus_plus_17
ISO C++:2017.
@ eLanguageTypeObjC_plus_plus
Objective-C++.
@ eLanguageTypeC_plus_plus_11
ISO C++:2011.
@ eLanguageTypeC89
ISO C:1989.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
A source location consisting of a file name and position.
bool in_user_input
Whether this source location refers to something the user typed as part of the command,...
FileSpec file
"<user expression 0>" in the example above.
bool hidden
Whether this source location should be surfaced to the user.
A compiler-independent representation of an lldb_private::Diagnostic.
std::optional< SourceLocation > source_location
Contains this diagnostic's source location, if applicable.
lldb::Severity severity
Contains eSeverityError in the example above.
std::string rendered
Contains the fully rendered error message, without "error: ", but including the source context.
std::string message
Contains "use of undeclared identifier 'foo'" in the example above.
std::shared_ptr< llvm::legacy::PassManager > EarlyPasses
std::shared_ptr< llvm::legacy::PassManager > LatePasses
lldb::LanguageType AsLanguageType() const
Definition Language.cpp:554
Information needed to import a source-language module.