clang 22.0.0git
ASTUnit.cpp
Go to the documentation of this file.
1//===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
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// ASTUnit Implementation.
10//
11//===----------------------------------------------------------------------===//
12
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclGroup.h"
21#include "clang/AST/DeclObjC.h"
26#include "clang/AST/Type.h"
31#include "clang/Basic/LLVM.h"
34#include "clang/Basic/Module.h"
50#include "clang/Lex/Lexer.h"
55#include "clang/Lex/Token.h"
58#include "clang/Sema/Sema.h"
65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/IntrusiveRefCntPtr.h"
68#include "llvm/ADT/STLExtras.h"
69#include "llvm/ADT/ScopeExit.h"
70#include "llvm/ADT/SmallVector.h"
71#include "llvm/ADT/StringMap.h"
72#include "llvm/ADT/StringRef.h"
73#include "llvm/ADT/StringSet.h"
74#include "llvm/ADT/Twine.h"
75#include "llvm/ADT/iterator_range.h"
76#include "llvm/Bitstream/BitstreamWriter.h"
77#include "llvm/Support/Allocator.h"
78#include "llvm/Support/CrashRecoveryContext.h"
79#include "llvm/Support/DJB.h"
80#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/ErrorOr.h"
82#include "llvm/Support/MemoryBuffer.h"
83#include "llvm/Support/SaveAndRestore.h"
84#include "llvm/Support/Timer.h"
85#include "llvm/Support/VirtualFileSystem.h"
86#include "llvm/Support/raw_ostream.h"
87#include <algorithm>
88#include <atomic>
89#include <cassert>
90#include <cstdint>
91#include <cstdio>
92#include <cstdlib>
93#include <memory>
94#include <mutex>
95#include <optional>
96#include <string>
97#include <tuple>
98#include <utility>
99#include <vector>
100
101using namespace clang;
102
103using llvm::TimeRecord;
104
105namespace {
106
107 class SimpleTimer {
108 bool WantTiming;
109 TimeRecord Start;
110 std::string Output;
111
112 public:
113 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
114 if (WantTiming)
115 Start = TimeRecord::getCurrentTime();
116 }
117
118 ~SimpleTimer() {
119 if (WantTiming) {
120 TimeRecord Elapsed = TimeRecord::getCurrentTime();
121 Elapsed -= Start;
122 llvm::errs() << Output << ':';
123 Elapsed.print(Elapsed, llvm::errs());
124 llvm::errs() << '\n';
125 }
126 }
127
128 void setOutput(const Twine &Output) {
129 if (WantTiming)
130 this->Output = Output.str();
131 }
132 };
133
134} // namespace
135
136template <class T>
137static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
138 if (!Val)
139 return nullptr;
140 return std::move(*Val);
141}
142
143template <class T>
144static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
145 if (!Val)
146 return false;
147 Output = std::move(*Val);
148 return true;
149}
150
151/// Get a source buffer for \p MainFilePath, handling all file-to-file
152/// and file-to-buffer remappings inside \p Invocation.
153static std::unique_ptr<llvm::MemoryBuffer>
155 llvm::vfs::FileSystem *VFS,
156 StringRef FilePath, bool isVolatile) {
157 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
158
159 // Try to determine if the main file has been remapped, either from the
160 // command line (to another file) or directly through the compiler
161 // invocation (to a memory buffer).
162 llvm::MemoryBuffer *Buffer = nullptr;
163 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
164 auto FileStatus = VFS->status(FilePath);
165 if (FileStatus) {
166 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
167
168 // Check whether there is a file-file remapping of the main file
169 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
170 std::string MPath(RF.first);
171 auto MPathStatus = VFS->status(MPath);
172 if (MPathStatus) {
173 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
174 if (MainFileID == MID) {
175 // We found a remapping. Try to load the resulting, remapped source.
176 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
177 if (!BufferOwner)
178 return nullptr;
179 }
180 }
181 }
182
183 // Check whether there is a file-buffer remapping. It supercedes the
184 // file-file remapping.
185 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
186 std::string MPath(RB.first);
187 auto MPathStatus = VFS->status(MPath);
188 if (MPathStatus) {
189 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
190 if (MainFileID == MID) {
191 // We found a remapping.
192 BufferOwner.reset();
193 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
194 }
195 }
196 }
197 }
198
199 // If the main source file was not remapped, load it now.
200 if (!Buffer && !BufferOwner) {
201 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
202 if (!BufferOwner)
203 return nullptr;
204 }
205
206 if (BufferOwner)
207 return BufferOwner;
208 if (!Buffer)
209 return nullptr;
210 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
211}
212
215 llvm::BitstreamWriter Stream;
217
218 ASTWriterData(ModuleCache &ModCache, const CodeGenOptions &CGOpts)
219 : Stream(Buffer), Writer(Stream, Buffer, ModCache, CGOpts, {}) {}
220};
221
222void ASTUnit::clearFileLevelDecls() {
223 FileDecls.clear();
224}
225
226/// After failing to build a precompiled preamble (due to
227/// errors in the source that occurs in the preamble), the number of
228/// reparses during which we'll skip even trying to precompile the
229/// preamble.
231
232/// Tracks the number of ASTUnit objects that are currently active.
233///
234/// Used for debugging purposes only.
235static std::atomic<unsigned> ActiveASTUnitObjects;
236
237ASTUnit::ASTUnit(bool _MainFileIsAST)
238 : CodeGenOpts(std::make_unique<CodeGenOptions>()),
239 MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
240 ShouldCacheCodeCompletionResults(false),
241 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
242 UnsafeToFree(false) {
243 if (getenv("LIBCLANG_OBJTRACKING"))
244 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
245}
246
248 // If we loaded from an AST file, balance out the BeginSourceFile call.
249 if (MainFileIsAST && getDiagnostics().getClient()) {
251 }
252
253 clearFileLevelDecls();
254
255 // Free the buffers associated with remapped files. We are required to
256 // perform this operation here because we explicitly request that the
257 // compiler instance *not* free these buffers for each invocation of the
258 // parser.
259 if (Invocation && OwnsRemappedFileBuffers) {
260 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
261 for (const auto &RB : PPOpts.RemappedFileBuffers)
262 delete RB.second;
263 }
264
265 ClearCachedCompletionResults();
266
267 if (getenv("LIBCLANG_OBJTRACKING"))
268 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
269}
270
271void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
272 this->PP = std::move(PP);
273}
274
276 assert(getDiagnostics().getClient() && Ctx &&
277 "Bad context for source file");
278 getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
279}
280
281/// Determine the set of code-completion contexts in which this
282/// declaration should be shown.
283static uint64_t getDeclShowContexts(const NamedDecl *ND,
284 const LangOptions &LangOpts,
285 bool &IsNestedNameSpecifier) {
286 IsNestedNameSpecifier = false;
287
288 if (isa<UsingShadowDecl>(ND))
289 ND = ND->getUnderlyingDecl();
290 if (!ND)
291 return 0;
292
293 uint64_t Contexts = 0;
294 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
295 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
296 isa<TypeAliasTemplateDecl>(ND)) {
297 // Types can appear in these contexts.
298 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
299 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
305
306 // In C++, types can appear in expressions contexts (for functional casts).
307 if (LangOpts.CPlusPlus)
308 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
309
310 // In Objective-C, message sends can send interfaces. In Objective-C++,
311 // all types are available due to functional casts.
312 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
314
315 // In Objective-C, you can only be a subclass of another Objective-C class
316 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
317 // Objective-C interfaces can be used in a class property expression.
318 if (ID->getDefinition())
319 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
322 }
323
324 // Deal with tag names.
325 if (isa<EnumDecl>(ND)) {
326 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
327
328 // Part of the nested-name-specifier in C++0x.
329 if (LangOpts.CPlusPlus11)
330 IsNestedNameSpecifier = true;
331 } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
332 if (Record->isUnion())
333 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
334 else
336
337 if (LangOpts.CPlusPlus)
338 IsNestedNameSpecifier = true;
339 } else if (isa<ClassTemplateDecl>(ND))
340 IsNestedNameSpecifier = true;
341 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
342 // Values can appear in these contexts.
343 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
347 } else if (isa<ObjCProtocolDecl>(ND)) {
349 } else if (isa<ObjCCategoryDecl>(ND)) {
351 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
352 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
353
354 // Part of the nested-name-specifier.
355 IsNestedNameSpecifier = true;
356 }
357
358 return Contexts;
359}
360
361void ASTUnit::CacheCodeCompletionResults() {
362 if (!TheSema)
363 return;
364
365 SimpleTimer Timer(WantTiming);
366 Timer.setOutput("Cache global code completions for " + getMainFileName());
367
368 // Clear out the previous results.
369 ClearCachedCompletionResults();
370
371 // Gather the set of global code completions.
374 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
375 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
376 TheSema->CodeCompletion().GatherGlobalCodeCompletions(
377 *CachedCompletionAllocator, CCTUInfo, Results);
378
379 // Translate global code completions into cached completions.
380 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
382
383 for (auto &R : Results) {
384 switch (R.Kind) {
385 case Result::RK_Declaration: {
386 bool IsNestedNameSpecifier = false;
387 CachedCodeCompletionResult CachedResult;
388 CachedResult.Completion = R.CreateCodeCompletionString(
389 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
390 IncludeBriefCommentsInCodeCompletion);
391 CachedResult.ShowInContexts = getDeclShowContexts(
392 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
393 CachedResult.Priority = R.Priority;
394 CachedResult.Kind = R.CursorKind;
395 CachedResult.Availability = R.Availability;
396
397 // Keep track of the type of this completion in an ASTContext-agnostic
398 // way.
399 QualType UsageType = getDeclUsageType(*Ctx, R.Qualifier, R.Declaration);
400 if (UsageType.isNull()) {
401 CachedResult.TypeClass = STC_Void;
402 CachedResult.Type = 0;
403 } else {
404 CanQualType CanUsageType
405 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
406 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
407
408 // Determine whether we have already seen this type. If so, we save
409 // ourselves the work of formatting the type string by using the
410 // temporary, CanQualType-based hash table to find the associated value.
411 unsigned &TypeValue = CompletionTypes[CanUsageType];
412 if (TypeValue == 0) {
413 TypeValue = CompletionTypes.size();
414 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
415 = TypeValue;
416 }
417
418 CachedResult.Type = TypeValue;
419 }
420
421 CachedCompletionResults.push_back(CachedResult);
422
423 /// Handle nested-name-specifiers in C++.
424 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
425 !R.StartsNestedNameSpecifier) {
426 // The contexts in which a nested-name-specifier can appear in C++.
427 uint64_t NNSContexts
440
441 if (isa<NamespaceDecl>(R.Declaration) ||
442 isa<NamespaceAliasDecl>(R.Declaration))
443 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
444
445 if (uint64_t RemainingContexts
446 = NNSContexts & ~CachedResult.ShowInContexts) {
447 // If there any contexts where this completion can be a
448 // nested-name-specifier but isn't already an option, create a
449 // nested-name-specifier completion.
450 R.StartsNestedNameSpecifier = true;
451 CachedResult.Completion = R.CreateCodeCompletionString(
452 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
453 IncludeBriefCommentsInCodeCompletion);
454 CachedResult.ShowInContexts = RemainingContexts;
455 CachedResult.Priority = CCP_NestedNameSpecifier;
456 CachedResult.TypeClass = STC_Void;
457 CachedResult.Type = 0;
458 CachedCompletionResults.push_back(CachedResult);
459 }
460 }
461 break;
462 }
463
464 case Result::RK_Keyword:
465 case Result::RK_Pattern:
466 // Ignore keywords and patterns; we don't care, since they are so
467 // easily regenerated.
468 break;
469
470 case Result::RK_Macro: {
471 CachedCodeCompletionResult CachedResult;
472 CachedResult.Completion = R.CreateCodeCompletionString(
473 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
474 IncludeBriefCommentsInCodeCompletion);
475 CachedResult.ShowInContexts
488
489 CachedResult.Priority = R.Priority;
490 CachedResult.Kind = R.CursorKind;
491 CachedResult.Availability = R.Availability;
492 CachedResult.TypeClass = STC_Void;
493 CachedResult.Type = 0;
494 CachedCompletionResults.push_back(CachedResult);
495 break;
496 }
497 }
498 }
499
500 // Save the current top-level hash value.
501 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
502}
503
504void ASTUnit::ClearCachedCompletionResults() {
505 CachedCompletionResults.clear();
506 CachedCompletionTypes.clear();
507 CachedCompletionAllocator = nullptr;
508}
509
510namespace {
511
512/// Gathers information from ASTReader that will be used to initialize
513/// a Preprocessor.
514class ASTInfoCollector : public ASTReaderListener {
515 Preprocessor &PP;
516 ASTContext *Context;
517 HeaderSearchOptions &HSOpts;
518 PreprocessorOptions &PPOpts;
519 LangOptions &LangOpt;
520 CodeGenOptions &CodeGenOpts;
521 std::shared_ptr<TargetOptions> &TargetOpts;
523 unsigned &Counter;
524 bool InitializedLanguage = false;
525 bool InitializedHeaderSearchPaths = false;
526
527public:
528 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
530 LangOptions &LangOpt, CodeGenOptions &CodeGenOpts,
531 std::shared_ptr<TargetOptions> &TargetOpts,
532 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
533 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
534 LangOpt(LangOpt), CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts),
535 Target(Target), Counter(Counter) {}
536
537 bool ReadLanguageOptions(const LangOptions &LangOpts,
538 StringRef ModuleFilename, bool Complain,
539 bool AllowCompatibleDifferences) override {
540 if (InitializedLanguage)
541 return false;
542
543 // FIXME: We did similar things in ReadHeaderSearchOptions too. But such
544 // style is not scaling. Probably we need to invite some mechanism to
545 // handle such patterns generally.
546 auto PICLevel = LangOpt.PICLevel;
547 auto PIE = LangOpt.PIE;
548
549 LangOpt = LangOpts;
550
551 LangOpt.PICLevel = PICLevel;
552 LangOpt.PIE = PIE;
553
554 InitializedLanguage = true;
555
556 updated();
557 return false;
558 }
559
560 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
561 StringRef ModuleFilename, bool Complain,
562 bool AllowCompatibleDifferences) override {
563 this->CodeGenOpts = CGOpts;
564 return false;
565 }
566
567 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
568 StringRef ModuleFilename,
569 StringRef SpecificModuleCachePath,
570 bool Complain) override {
571 // llvm::SaveAndRestore doesn't support bit field.
572 auto ForceCheckCXX20ModulesInputFiles =
574 llvm::SaveAndRestore X(this->HSOpts.UserEntries);
577
578 this->HSOpts = HSOpts;
580 ForceCheckCXX20ModulesInputFiles;
581
582 return false;
583 }
584
585 bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts,
586 bool Complain) override {
587 if (InitializedHeaderSearchPaths)
588 return false;
589
590 this->HSOpts.UserEntries = HSOpts.UserEntries;
591 this->HSOpts.SystemHeaderPrefixes = HSOpts.SystemHeaderPrefixes;
592 this->HSOpts.VFSOverlayFiles = HSOpts.VFSOverlayFiles;
593
594 // Initialize the FileManager. We can't do this in update(), since that
595 // performs the initialization too late (once both target and language
596 // options are read).
598 HSOpts.VFSOverlayFiles, PP.getDiagnostics(),
600
601 InitializedHeaderSearchPaths = true;
602
603 return false;
604 }
605
606 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
607 StringRef ModuleFilename, bool ReadMacros,
608 bool Complain,
609 std::string &SuggestedPredefines) override {
610 this->PPOpts = PPOpts;
611 return false;
612 }
613
614 bool ReadTargetOptions(const TargetOptions &TargetOpts,
615 StringRef ModuleFilename, bool Complain,
616 bool AllowCompatibleDifferences) override {
617 // If we've already initialized the target, don't do it again.
618 if (Target)
619 return false;
620
621 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
622 Target =
623 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), *this->TargetOpts);
624
625 updated();
626 return false;
627 }
628
629 void ReadCounter(const serialization::ModuleFile &M,
630 unsigned Value) override {
631 Counter = Value;
632 }
633
634private:
635 void updated() {
636 if (!Target || !InitializedLanguage)
637 return;
638
639 // Inform the target of the language options.
640 //
641 // FIXME: We shouldn't need to do this, the target should be immutable once
642 // created. This complexity should be lifted elsewhere.
643 Target->adjust(PP.getDiagnostics(), LangOpt, /*AuxTarget=*/nullptr);
644
645 // Initialize the preprocessor.
646 PP.Initialize(*Target);
647
648 if (!Context)
649 return;
650
651 // Initialize the ASTContext
652 Context->InitBuiltinTypes(*Target);
653
654 // Adjust printing policy based on language options.
655 Context->setPrintingPolicy(PrintingPolicy(LangOpt));
656
657 // We didn't have access to the comment options when the ASTContext was
658 // constructed, so register them now.
660 LangOpt.CommentOpts);
661 }
662};
663
664/// Diagnostic consumer that saves each diagnostic it is given.
665class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer {
668 bool CaptureNonErrorsFromIncludes = true;
669 const LangOptions *LangOpts = nullptr;
670 SourceManager *SourceMgr = nullptr;
671
672public:
673 FilterAndStoreDiagnosticConsumer(
676 bool CaptureNonErrorsFromIncludes)
677 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
678 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
679 assert((StoredDiags || StandaloneDiags) &&
680 "No output collections were passed to StoredDiagnosticConsumer.");
681 }
682
683 void BeginSourceFile(const LangOptions &LangOpts,
684 const Preprocessor *PP = nullptr) override {
685 this->LangOpts = &LangOpts;
686 if (PP)
687 SourceMgr = &PP->getSourceManager();
688 }
689
690 void HandleDiagnostic(DiagnosticsEngine::Level Level,
691 const Diagnostic &Info) override;
692};
693
694/// RAII object that optionally captures and filters diagnostics, if
695/// there is no diagnostic client to capture them already.
696class CaptureDroppedDiagnostics {
697 DiagnosticsEngine &Diags;
698 FilterAndStoreDiagnosticConsumer Client;
699 DiagnosticConsumer *PreviousClient = nullptr;
700 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
701
702public:
703 CaptureDroppedDiagnostics(
704 CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags,
707 : Diags(Diags),
708 Client(StoredDiags, StandaloneDiags,
709 CaptureDiagnostics !=
711 if (CaptureDiagnostics != CaptureDiagsKind::None ||
712 Diags.getClient() == nullptr) {
713 OwningPreviousClient = Diags.takeClient();
714 PreviousClient = Diags.getClient();
715 Diags.setClient(&Client, false);
716 }
717 }
718
719 ~CaptureDroppedDiagnostics() {
720 if (Diags.getClient() == &Client)
721 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
722 }
723};
724
725} // namespace
726
729 const StoredDiagnostic &InDiag);
730
731static bool isInMainFile(const clang::Diagnostic &D) {
732 if (!D.hasSourceManager() || !D.getLocation().isValid())
733 return false;
734
735 auto &M = D.getSourceManager();
736 return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation()));
737}
738
739void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
740 DiagnosticsEngine::Level Level, const Diagnostic &Info) {
741 // Default implementation (Warnings/errors count).
743
744 // Only record the diagnostic if it's part of the source manager we know
745 // about. This effectively drops diagnostics from modules we're building.
746 // FIXME: In the long run, ee don't want to drop source managers from modules.
747 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
748 if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning &&
749 !isInMainFile(Info)) {
750 return;
751 }
752
753 StoredDiagnostic *ResultDiag = nullptr;
754 if (StoredDiags) {
755 StoredDiags->emplace_back(Level, Info);
756 ResultDiag = &StoredDiags->back();
757 }
758
759 if (StandaloneDiags) {
760 std::optional<StoredDiagnostic> StoredDiag;
761 if (!ResultDiag) {
762 StoredDiag.emplace(Level, Info);
763 ResultDiag = &*StoredDiag;
764 }
765 StandaloneDiags->push_back(
766 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
767 }
768 }
769}
770
772 return Reader;
773}
774
776 if (WriterData)
777 return &WriterData->Writer;
778 return nullptr;
779}
780
782 if (WriterData)
783 return &WriterData->Writer;
784 return nullptr;
785}
786
787std::unique_ptr<llvm::MemoryBuffer>
788ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
789 assert(FileMgr);
790 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
791 if (Buffer)
792 return std::move(*Buffer);
793 if (ErrorStr)
794 *ErrorStr = Buffer.getError().message();
795 return nullptr;
796}
797
798/// Configure the diagnostics object for use with ASTUnit.
799void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
800 ASTUnit &AST,
801 CaptureDiagsKind CaptureDiagnostics) {
802 assert(Diags.get() && "no DiagnosticsEngine was provided");
803 if (CaptureDiagnostics != CaptureDiagsKind::None)
804 Diags->setClient(new FilterAndStoreDiagnosticConsumer(
805 &AST.StoredDiagnostics, nullptr,
807}
808
809std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
810 StringRef Filename, const PCHContainerReader &PCHContainerRdr,
811 WhatToLoad ToLoad, std::shared_ptr<DiagnosticOptions> DiagOpts,
813 const FileSystemOptions &FileSystemOpts, const HeaderSearchOptions &HSOpts,
814 const LangOptions *LangOpts, bool OnlyLocalDecls,
815 CaptureDiagsKind CaptureDiagnostics, bool AllowASTWithCompilerErrors,
816 bool UserFilesAreVolatile, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
817 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
818
819 // Recover resources if we crash before exiting this method.
820 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
821 ASTUnitCleanup(AST.get());
822 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
823 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
824 DiagCleanup(Diags.get());
825
826 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
827
828 AST->LangOpts = LangOpts ? std::make_unique<LangOptions>(*LangOpts)
829 : std::make_unique<LangOptions>();
830 AST->OnlyLocalDecls = OnlyLocalDecls;
831 AST->CaptureDiagnostics = CaptureDiagnostics;
832 AST->DiagOpts = DiagOpts;
833 AST->Diagnostics = Diags;
834 AST->FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOpts, VFS);
835 AST->UserFilesAreVolatile = UserFilesAreVolatile;
836 AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
837 AST->getDiagnostics(), AST->getFileManager(), UserFilesAreVolatile);
838 AST->ModCache = createCrossProcessModuleCache();
839 AST->HSOpts = std::make_unique<HeaderSearchOptions>(HSOpts);
840 AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormats().front());
841 AST->HeaderInfo.reset(new HeaderSearch(AST->getHeaderSearchOpts(),
842 AST->getSourceManager(),
843 AST->getDiagnostics(),
844 AST->getLangOpts(),
845 /*Target=*/nullptr));
846 AST->PPOpts = std::make_shared<PreprocessorOptions>();
847
848 // Gather Info for preprocessor construction later on.
849
850 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
851
852 AST->PP = std::make_shared<Preprocessor>(
853 *AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
854 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
855 /*IILookup=*/nullptr,
856 /*OwnsHeaderSearch=*/false);
857 Preprocessor &PP = *AST->PP;
858
859 if (ToLoad >= LoadASTOnly)
860 AST->Ctx = llvm::makeIntrusiveRefCnt<ASTContext>(
861 *AST->LangOpts, AST->getSourceManager(), PP.getIdentifierTable(),
863 AST->getTranslationUnitKind());
864
865 DisableValidationForModuleKind disableValid =
867 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
869 AST->Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
870 PP, *AST->ModCache, AST->Ctx.get(), PCHContainerRdr, *AST->CodeGenOpts,
871 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
872 /*isysroot=*/"",
873 /*DisableValidationKind=*/disableValid, AllowASTWithCompilerErrors);
874
875 unsigned Counter = 0;
876 AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
877 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
878 *AST->CodeGenOpts, AST->TargetOpts, AST->Target, Counter));
879
880 // Attach the AST reader to the AST context as an external AST
881 // source, so that declarations will be deserialized from the
882 // AST file as needed.
883 // We need the external source to be set up before we read the AST, because
884 // eagerly-deserialized declarations may use it.
885 if (AST->Ctx)
886 AST->Ctx->setExternalSource(AST->Reader);
887
888 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
891 break;
892
899 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
900 return nullptr;
901 }
902
903 AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
904
905 PP.setCounterValue(Counter);
906
907 Module *M = HeaderInfo.lookupModule(AST->getLangOpts().CurrentModule);
908 if (M && AST->getLangOpts().isCompilingModule() && M->isNamedModule())
909 AST->Ctx->setCurrentNamedModule(M);
910
911 // Create an AST consumer, even though it isn't used.
912 if (ToLoad >= LoadASTOnly)
913 AST->Consumer.reset(new ASTConsumer);
914
915 // Create a semantic analysis object and tell the AST reader about it.
916 if (ToLoad >= LoadEverything) {
917 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
918 AST->TheSema->Initialize();
919 AST->Reader->InitializeSema(*AST->TheSema);
920 }
921
922 // Tell the diagnostic client that we have started a source file.
923 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
924
925 return AST;
926}
927
928/// Add the given macro to the hash of all top-level entities.
929static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
930 Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
931}
932
933namespace {
934
935/// Preprocessor callback class that updates a hash value with the names
936/// of all macros that have been defined by the translation unit.
937class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
938 unsigned &Hash;
939
940public:
941 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
942
943 void MacroDefined(const Token &MacroNameTok,
944 const MacroDirective *MD) override {
945 AddDefinedMacroToHash(MacroNameTok, Hash);
946 }
947};
948
949} // namespace
950
951/// Add the given declaration to the hash of all top-level entities.
952static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
953 if (!D)
954 return;
955
957 if (!DC)
958 return;
959
960 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
961 return;
962
963 if (const auto *ND = dyn_cast<NamedDecl>(D)) {
964 if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
965 // For an unscoped enum include the enumerators in the hash since they
966 // enter the top-level namespace.
967 if (!EnumD->isScoped()) {
968 for (const auto *EI : EnumD->enumerators()) {
969 if (EI->getIdentifier())
970 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
971 }
972 }
973 }
974
975 if (ND->getIdentifier())
976 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
977 else if (DeclarationName Name = ND->getDeclName()) {
978 std::string NameStr = Name.getAsString();
979 Hash = llvm::djbHash(NameStr, Hash);
980 }
981 return;
982 }
983
984 if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
985 if (const Module *Mod = ImportD->getImportedModule()) {
986 std::string ModName = Mod->getFullModuleName();
987 Hash = llvm::djbHash(ModName, Hash);
988 }
989 return;
990 }
991}
992
993namespace {
994
995class TopLevelDeclTrackerConsumer : public ASTConsumer {
996 ASTUnit &Unit;
997 unsigned &Hash;
998
999public:
1000 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
1001 : Unit(_Unit), Hash(Hash) {
1002 Hash = 0;
1003 }
1004
1005 void handleTopLevelDecl(Decl *D) {
1006 if (!D)
1007 return;
1008
1009 // FIXME: Currently ObjC method declarations are incorrectly being
1010 // reported as top-level declarations, even though their DeclContext
1011 // is the containing ObjC @interface/@implementation. This is a
1012 // fundamental problem in the parser right now.
1013 if (isa<ObjCMethodDecl>(D))
1014 return;
1015
1017 Unit.addTopLevelDecl(D);
1018
1019 handleFileLevelDecl(D);
1020 }
1021
1022 void handleFileLevelDecl(Decl *D) {
1023 Unit.addFileLevelDecl(D);
1024 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
1025 for (auto *I : NSD->decls())
1026 handleFileLevelDecl(I);
1027 }
1028 }
1029
1030 bool HandleTopLevelDecl(DeclGroupRef D) override {
1031 for (auto *TopLevelDecl : D)
1032 handleTopLevelDecl(TopLevelDecl);
1033 return true;
1034 }
1035
1036 // We're not interested in "interesting" decls.
1037 void HandleInterestingDecl(DeclGroupRef) override {}
1038
1039 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
1040 for (auto *TopLevelDecl : D)
1041 handleTopLevelDecl(TopLevelDecl);
1042 }
1043
1044 ASTMutationListener *GetASTMutationListener() override {
1045 return Unit.getASTMutationListener();
1046 }
1047
1048 ASTDeserializationListener *GetASTDeserializationListener() override {
1049 return Unit.getDeserializationListener();
1050 }
1051};
1052
1053class TopLevelDeclTrackerAction : public ASTFrontendAction {
1054public:
1055 ASTUnit &Unit;
1056
1057 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
1058 StringRef InFile) override {
1060 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1062 return std::make_unique<TopLevelDeclTrackerConsumer>(
1063 Unit, Unit.getCurrentTopLevelHashValue());
1064 }
1065
1066public:
1067 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
1068
1069 bool hasCodeCompletionSupport() const override { return false; }
1070
1071 TranslationUnitKind getTranslationUnitKind() override {
1072 return Unit.getTranslationUnitKind();
1073 }
1074};
1075
1076class ASTUnitPreambleCallbacks : public PreambleCallbacks {
1077public:
1078 unsigned getHash() const { return Hash; }
1079
1080 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
1081
1082 std::vector<LocalDeclID> takeTopLevelDeclIDs() {
1083 return std::move(TopLevelDeclIDs);
1084 }
1085
1086 void AfterPCHEmitted(ASTWriter &Writer) override {
1087 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1088 for (const auto *D : TopLevelDecls) {
1089 // Invalid top-level decls may not have been serialized.
1090 if (D->isInvalidDecl())
1091 continue;
1092 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1093 }
1094 }
1095
1096 void HandleTopLevelDecl(DeclGroupRef DG) override {
1097 for (auto *D : DG) {
1098 // FIXME: Currently ObjC method declarations are incorrectly being
1099 // reported as top-level declarations, even though their DeclContext
1100 // is the containing ObjC @interface/@implementation. This is a
1101 // fundamental problem in the parser right now.
1102 if (isa<ObjCMethodDecl>(D))
1103 continue;
1105 TopLevelDecls.push_back(D);
1106 }
1107 }
1108
1109 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1110 return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1111 }
1112
1113private:
1114 unsigned Hash = 0;
1115 std::vector<Decl *> TopLevelDecls;
1116 std::vector<LocalDeclID> TopLevelDeclIDs;
1118};
1119
1120} // namespace
1121
1122static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1123 return StoredDiag.getLocation().isValid();
1124}
1125
1126static void
1128 // Get rid of stored diagnostics except the ones from the driver which do not
1129 // have a source location.
1130 llvm::erase_if(StoredDiags, isNonDriverDiag);
1131}
1132
1134 StoredDiagnostics,
1135 SourceManager &SM) {
1136 // The stored diagnostic has the old source manager in it; update
1137 // the locations to refer into the new source manager. Since we've
1138 // been careful to make sure that the source manager's state
1139 // before and after are identical, so that we can reuse the source
1140 // location itself.
1141 for (auto &SD : StoredDiagnostics) {
1142 if (SD.getLocation().isValid()) {
1143 FullSourceLoc Loc(SD.getLocation(), SM);
1144 SD.setLocation(Loc);
1145 }
1146 }
1147}
1148
1149/// Parse the source file into a translation unit using the given compiler
1150/// invocation, replacing the current translation unit.
1151///
1152/// \returns True if a failure occurred that causes the ASTUnit not to
1153/// contain any translation-unit information, false otherwise.
1154bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1155 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1157 if (!Invocation)
1158 return true;
1159
1160 if (VFS && FileMgr)
1161 assert(VFS == &FileMgr->getVirtualFileSystem() &&
1162 "VFS passed to Parse and VFS in FileMgr are different");
1163
1164 CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1165 if (OverrideMainBuffer) {
1166 assert(Preamble &&
1167 "No preamble was built, but OverrideMainBuffer is not null");
1168 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1169 // VFS may have changed...
1170 }
1171
1172 // Create the compiler instance to use for building the AST.
1173 auto Clang = std::make_unique<CompilerInstance>(CCInvocation,
1174 std::move(PCHContainerOps));
1175
1176 // Clean up on error, disengage it if the function returns successfully.
1177 auto CleanOnError = llvm::make_scope_exit([&]() {
1178 // Remove the overridden buffer we used for the preamble.
1179 SavedMainFileBuffer = nullptr;
1180
1181 // Keep the ownership of the data in the ASTUnit because the client may
1182 // want to see the diagnostics.
1183 transferASTDataFromCompilerInstance(*Clang);
1184 FailedParseDiagnostics.swap(StoredDiagnostics);
1185 StoredDiagnostics.clear();
1186 NumStoredDiagnosticsFromDriver = 0;
1187 });
1188
1189 // Ensure that Clang has a FileManager with the right VFS, which may have
1190 // changed above in AddImplicitPreamble. If VFS is nullptr, rely on
1191 // createFileManager to create one.
1192 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
1193 Clang->setFileManager(FileMgr);
1194 else {
1195 Clang->createFileManager(std::move(VFS));
1196 FileMgr = Clang->getFileManagerPtr();
1197 }
1198
1199 // Recover resources if we crash before exiting this method.
1200 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1201 CICleanup(Clang.get());
1202
1203 OriginalSourceFile =
1204 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1205
1206 // Set up diagnostics, capturing any diagnostics that would
1207 // otherwise be dropped.
1208 Clang->setDiagnostics(getDiagnosticsPtr());
1209
1210 // Create the target instance.
1211 if (!Clang->createTarget())
1212 return true;
1213
1214 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1215 "Invocation must have exactly one source file!");
1216 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1218 "FIXME: AST inputs not yet supported here!");
1219 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1221 "IR inputs not support here!");
1222
1223 // Configure the various subsystems.
1224 LangOpts =
1225 std::make_unique<LangOptions>(Clang->getInvocation().getLangOpts());
1226 FileSystemOpts = Clang->getFileSystemOpts();
1227
1228 ResetForParse();
1229
1230 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
1231 getDiagnostics(), *FileMgr, +UserFilesAreVolatile);
1232 if (!OverrideMainBuffer) {
1233 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1234 TopLevelDeclsInPreamble.clear();
1235 }
1236
1237 // Create the source manager.
1238 Clang->setSourceManager(getSourceManagerPtr());
1239
1240 // If the main file has been overridden due to the use of a preamble,
1241 // make that override happen and introduce the preamble.
1242 if (OverrideMainBuffer) {
1243 // The stored diagnostic has the old source manager in it; update
1244 // the locations to refer into the new source manager. Since we've
1245 // been careful to make sure that the source manager's state
1246 // before and after are identical, so that we can reuse the source
1247 // location itself.
1248 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1249
1250 // Keep track of the override buffer;
1251 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1252 }
1253
1254 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1255 new TopLevelDeclTrackerAction(*this));
1256
1257 // Recover resources if we crash before exiting this method.
1258 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1259 ActCleanup(Act.get());
1260
1261 if (!Act->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
1262 return true;
1263
1264 if (SavedMainFileBuffer)
1265 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1266 PreambleDiagnostics, StoredDiagnostics);
1267 else
1268 PreambleSrcLocCache.clear();
1269
1270 if (llvm::Error Err = Act->Execute()) {
1271 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1272 return true;
1273 }
1274
1275 transferASTDataFromCompilerInstance(*Clang);
1276
1277 Act->EndSourceFile();
1278
1279 FailedParseDiagnostics.clear();
1280
1281 CleanOnError.release();
1282
1283 return false;
1284}
1285
1286static std::pair<unsigned, unsigned>
1288 const LangOptions &LangOpts) {
1289 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1290 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1291 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1292 return std::make_pair(Offset, EndOffset);
1293}
1294
1296 const LangOptions &LangOpts,
1297 const FixItHint &InFix) {
1299 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1301 LangOpts);
1302 OutFix.CodeToInsert = InFix.CodeToInsert;
1304 return OutFix;
1305}
1306
1309 const StoredDiagnostic &InDiag) {
1311 OutDiag.ID = InDiag.getID();
1312 OutDiag.Level = InDiag.getLevel();
1313 OutDiag.Message = std::string(InDiag.getMessage());
1314 OutDiag.LocOffset = 0;
1315 if (InDiag.getLocation().isInvalid())
1316 return OutDiag;
1317 const SourceManager &SM = InDiag.getLocation().getManager();
1318 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1319 OutDiag.Filename = std::string(SM.getFilename(FileLoc));
1320 if (OutDiag.Filename.empty())
1321 return OutDiag;
1322 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1323 for (const auto &Range : InDiag.getRanges())
1324 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1325 for (const auto &FixIt : InDiag.getFixIts())
1326 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1327
1328 return OutDiag;
1329}
1330
1331/// Attempt to build or re-use a precompiled preamble when (re-)parsing
1332/// the source file.
1333///
1334/// This routine will compute the preamble of the main source file. If a
1335/// non-trivial preamble is found, it will precompile that preamble into a
1336/// precompiled header so that the precompiled preamble can be used to reduce
1337/// reparsing time. If a precompiled preamble has already been constructed,
1338/// this routine will determine if it is still valid and, if so, avoid
1339/// rebuilding the precompiled preamble.
1340///
1341/// \param AllowRebuild When true (the default), this routine is
1342/// allowed to rebuild the precompiled preamble if it is found to be
1343/// out-of-date.
1344///
1345/// \param MaxLines When non-zero, the maximum number of lines that
1346/// can occur within the preamble.
1347///
1348/// \returns If the precompiled preamble can be used, returns a newly-allocated
1349/// buffer that should be used in place of the main file when doing so.
1350/// Otherwise, returns a NULL pointer.
1351std::unique_ptr<llvm::MemoryBuffer>
1352ASTUnit::getMainBufferWithPrecompiledPreamble(
1353 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1354 CompilerInvocation &PreambleInvocationIn,
1355 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
1356 unsigned MaxLines) {
1357 auto MainFilePath =
1358 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1359 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1360 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1361 MainFilePath, UserFilesAreVolatile);
1362 if (!MainFileBuffer)
1363 return nullptr;
1364
1366 PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines);
1367 if (!Bounds.Size)
1368 return nullptr;
1369
1370 if (Preamble) {
1371 if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
1372 *VFS)) {
1373 // Okay! We can re-use the precompiled preamble.
1374
1375 // Set the state of the diagnostic object to mimic its state
1376 // after parsing the preamble.
1379 PreambleInvocationIn.getDiagnosticOpts(), *VFS);
1380 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1381
1382 PreambleRebuildCountdown = 1;
1383 return MainFileBuffer;
1384 } else {
1385 Preamble.reset();
1386 PreambleDiagnostics.clear();
1387 TopLevelDeclsInPreamble.clear();
1388 PreambleSrcLocCache.clear();
1389 PreambleRebuildCountdown = 1;
1390 }
1391 }
1392
1393 // If the preamble rebuild counter > 1, it's because we previously
1394 // failed to build a preamble and we're not yet ready to try
1395 // again. Decrement the counter and return a failure.
1396 if (PreambleRebuildCountdown > 1) {
1397 --PreambleRebuildCountdown;
1398 return nullptr;
1399 }
1400
1401 assert(!Preamble && "No Preamble should be stored at that point");
1402 // If we aren't allowed to rebuild the precompiled preamble, just
1403 // return now.
1404 if (!AllowRebuild)
1405 return nullptr;
1406
1407 ++PreambleCounter;
1408
1409 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1410 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1411 ASTUnitPreambleCallbacks Callbacks;
1412 {
1413 std::optional<CaptureDroppedDiagnostics> Capture;
1414 if (CaptureDiagnostics != CaptureDiagsKind::None)
1415 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1416 &NewPreambleDiagsStandalone);
1417
1418 // We did not previously compute a preamble, or it can't be reused anyway.
1419 SimpleTimer PreambleTimer(WantTiming);
1420 PreambleTimer.setOutput("Precompiling preamble");
1421
1422 const bool PreviousSkipFunctionBodies =
1423 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1424 if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1425 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1426
1427 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1428 PreambleInvocationIn, MainFileBuffer.get(), Bounds, Diagnostics, VFS,
1429 PCHContainerOps, StorePreamblesInMemory, PreambleStoragePath,
1430 Callbacks);
1431
1432 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1433 PreviousSkipFunctionBodies;
1434
1435 if (NewPreamble) {
1436 Preamble = std::move(*NewPreamble);
1437 PreambleRebuildCountdown = 1;
1438 } else {
1439 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1441 // Try again next time.
1442 PreambleRebuildCountdown = 1;
1443 return nullptr;
1448 // These erros are more likely to repeat, retry after some period.
1449 PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
1450 return nullptr;
1451 }
1452 llvm_unreachable("unexpected BuildPreambleError");
1453 }
1454 }
1455
1456 assert(Preamble && "Preamble wasn't built");
1457
1458 TopLevelDecls.clear();
1459 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1460 PreambleTopLevelHashValue = Callbacks.getHash();
1461
1462 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1463
1464 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1465 StoredDiagnostics = std::move(NewPreambleDiags);
1466 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1467
1468 // If the hash of top-level entities differs from the hash of the top-level
1469 // entities the last time we rebuilt the preamble, clear out the completion
1470 // cache.
1471 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1472 CompletionCacheTopLevelHashValue = 0;
1473 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1474 }
1475
1476 return MainFileBuffer;
1477}
1478
1479void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1480 assert(Preamble && "Should only be called when preamble was built");
1481
1482 std::vector<Decl *> Resolved;
1483 Resolved.reserve(TopLevelDeclsInPreamble.size());
1484 // The module file of the preamble.
1485 serialization::ModuleFile &MF = Reader->getModuleManager().getPrimaryModule();
1486 for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1487 // Resolve the declaration ID to an actual declaration, possibly
1488 // deserializing the declaration in the process.
1489 if (Decl *D = Reader->GetLocalDecl(MF, TopLevelDecl))
1490 Resolved.push_back(D);
1491 }
1492 TopLevelDeclsInPreamble.clear();
1493 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1494}
1495
1496void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1497 // Steal the created target, context, and preprocessor if they have been
1498 // created.
1499 LangOpts = std::make_unique<LangOptions>(CI.getInvocation().getLangOpts());
1500 TheSema = CI.takeSema();
1501 Consumer = CI.takeASTConsumer();
1502 if (CI.hasASTContext())
1503 Ctx = CI.getASTContextPtr();
1504 if (CI.hasPreprocessor())
1505 PP = CI.getPreprocessorPtr();
1506 CI.setSourceManager(nullptr);
1507 CI.setFileManager(nullptr);
1508 if (CI.hasTarget())
1509 Target = CI.getTargetPtr();
1510 Reader = CI.getASTReader();
1511 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1512 if (Invocation != CI.getInvocationPtr()) {
1513 // This happens when Parse creates a copy of \c Invocation to modify.
1514 ModifiedInvocation = CI.getInvocationPtr();
1515 }
1516}
1517
1518StringRef ASTUnit::getMainFileName() const {
1519 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1520 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1521 if (Input.isFile())
1522 return Input.getFile();
1523 else
1524 return Input.getBuffer().getBufferIdentifier();
1525 }
1526
1527 if (SourceMgr) {
1528 if (OptionalFileEntryRef FE =
1529 SourceMgr->getFileEntryRefForID(SourceMgr->getMainFileID()))
1530 return FE->getName();
1531 }
1532
1533 return {};
1534}
1535
1536StringRef ASTUnit::getASTFileName() const {
1537 if (!isMainFileAST())
1538 return {};
1539
1541 Mod = Reader->getModuleManager().getPrimaryModule();
1542 return Mod.FileName;
1543}
1544
1545std::unique_ptr<ASTUnit>
1546ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1547 std::shared_ptr<DiagnosticOptions> DiagOpts,
1549 CaptureDiagsKind CaptureDiagnostics,
1550 bool UserFilesAreVolatile) {
1551 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1552 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1555 AST->DiagOpts = DiagOpts;
1556 AST->Diagnostics = Diags;
1557 AST->FileSystemOpts = CI->getFileSystemOpts();
1558 AST->Invocation = std::move(CI);
1559 AST->FileMgr =
1560 llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS);
1561 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1562 AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
1563 AST->getDiagnostics(), *AST->FileMgr, UserFilesAreVolatile);
1564 AST->ModCache = createCrossProcessModuleCache();
1565
1566 return AST;
1567}
1568
1570 std::shared_ptr<CompilerInvocation> CI,
1571 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1572 std::shared_ptr<DiagnosticOptions> DiagOpts,
1574 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1575 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1576 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1577 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1578 assert(CI && "A CompilerInvocation is required");
1579
1580 std::unique_ptr<ASTUnit> OwnAST;
1581 ASTUnit *AST = Unit;
1582 if (!AST) {
1583 // Create the AST unit.
1584 OwnAST =
1585 create(CI, DiagOpts, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1586 AST = OwnAST.get();
1587 if (!AST)
1588 return nullptr;
1589 }
1590
1591 if (!ResourceFilesPath.empty()) {
1592 // Override the resources path.
1593 CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1594 }
1595 AST->OnlyLocalDecls = OnlyLocalDecls;
1596 AST->CaptureDiagnostics = CaptureDiagnostics;
1597 if (PrecompilePreambleAfterNParses > 0)
1598 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1599 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1600 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1601 AST->IncludeBriefCommentsInCodeCompletion = false;
1602
1603 // Recover resources if we crash before exiting this method.
1604 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1605 ASTUnitCleanup(OwnAST.get());
1606 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1607 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1608 DiagCleanup(Diags.get());
1609
1610 // We'll manage file buffers ourselves.
1611 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1612 CI->getFrontendOpts().DisableFree = false;
1613 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts(),
1615
1616 // Create the compiler instance to use for building the AST.
1617 auto Clang = std::make_unique<CompilerInstance>(std::move(CI),
1618 std::move(PCHContainerOps));
1619
1620 // Recover resources if we crash before exiting this method.
1621 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1622 CICleanup(Clang.get());
1623
1624 AST->OriginalSourceFile =
1625 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1626
1627 // Set up diagnostics, capturing any diagnostics that would
1628 // otherwise be dropped.
1629 Clang->setDiagnostics(AST->getDiagnosticsPtr());
1630
1631 // Create the target instance.
1632 if (!Clang->createTarget())
1633 return nullptr;
1634
1635 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1636 "Invocation must have exactly one source file!");
1637 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1639 "FIXME: AST inputs not yet supported here!");
1640 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1642 "IR inputs not support here!");
1643
1644 // Configure the various subsystems.
1645 AST->TheSema.reset();
1646 AST->Ctx = nullptr;
1647 AST->PP = nullptr;
1648 AST->Reader = nullptr;
1649
1650 // Create a file manager object to provide access to and cache the filesystem.
1651 Clang->setFileManager(AST->getFileManagerPtr());
1652
1653 // Create the source manager.
1654 Clang->setSourceManager(AST->getSourceManagerPtr());
1655
1656 FrontendAction *Act = Action;
1657
1658 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1659 if (!Act) {
1660 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1661 Act = TrackerAct.get();
1662 }
1663
1664 // Recover resources if we crash before exiting this method.
1665 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1666 ActCleanup(TrackerAct.get());
1667
1668 if (!Act->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1669 AST->transferASTDataFromCompilerInstance(*Clang);
1670 if (OwnAST && ErrAST)
1671 ErrAST->swap(OwnAST);
1672
1673 return nullptr;
1674 }
1675
1676 if (Persistent && !TrackerAct) {
1677 Clang->getPreprocessor().addPPCallbacks(
1678 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1680 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1681 if (Clang->hasASTConsumer())
1682 Consumers.push_back(Clang->takeASTConsumer());
1683 Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1684 *AST, AST->getCurrentTopLevelHashValue()));
1685 Clang->setASTConsumer(
1686 std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1687 }
1688 if (llvm::Error Err = Act->Execute()) {
1689 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1690 AST->transferASTDataFromCompilerInstance(*Clang);
1691 if (OwnAST && ErrAST)
1692 ErrAST->swap(OwnAST);
1693
1694 return nullptr;
1695 }
1696
1697 // Steal the created target, context, and preprocessor.
1698 AST->transferASTDataFromCompilerInstance(*Clang);
1699
1700 Act->EndSourceFile();
1701
1702 if (OwnAST)
1703 return OwnAST.release();
1704 else
1705 return AST;
1706}
1707
1708bool ASTUnit::LoadFromCompilerInvocation(
1709 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1710 unsigned PrecompilePreambleAfterNParses,
1712 if (!Invocation)
1713 return true;
1714
1715 assert(VFS && "VFS is null");
1716
1717 // We'll manage file buffers ourselves.
1718 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1719 Invocation->getFrontendOpts().DisableFree = false;
1721 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts(),
1722 *VFS);
1723
1724 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1725 if (PrecompilePreambleAfterNParses > 0) {
1726 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1727 OverrideMainBuffer =
1728 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1730 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts(),
1731 *VFS);
1732 }
1733
1734 SimpleTimer ParsingTimer(WantTiming);
1735 ParsingTimer.setOutput("Parsing " + getMainFileName());
1736
1737 // Recover resources if we crash before exiting this method.
1738 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1739 MemBufferCleanup(OverrideMainBuffer.get());
1740
1741 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1742}
1743
1744std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1745 std::shared_ptr<CompilerInvocation> CI,
1746 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1747 std::shared_ptr<DiagnosticOptions> DiagOpts,
1749 IntrusiveRefCntPtr<FileManager> FileMgr, bool OnlyLocalDecls,
1750 CaptureDiagsKind CaptureDiagnostics,
1751 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1752 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1753 bool UserFilesAreVolatile) {
1754 // Create the AST unit.
1755 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1756 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1757 AST->DiagOpts = DiagOpts;
1758 AST->Diagnostics = Diags;
1759 AST->OnlyLocalDecls = OnlyLocalDecls;
1760 AST->CaptureDiagnostics = CaptureDiagnostics;
1761 AST->TUKind = TUKind;
1762 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1763 AST->IncludeBriefCommentsInCodeCompletion
1764 = IncludeBriefCommentsInCodeCompletion;
1765 AST->Invocation = std::move(CI);
1766 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1767 AST->FileMgr = FileMgr;
1768 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1769
1770 // Recover resources if we crash before exiting this method.
1771 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1772 ASTUnitCleanup(AST.get());
1773 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1774 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1775 DiagCleanup(Diags.get());
1776
1777 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1778 PrecompilePreambleAfterNParses,
1779 AST->FileMgr->getVirtualFileSystemPtr()))
1780 return nullptr;
1781 return AST;
1782}
1783
1784std::unique_ptr<ASTUnit> ASTUnit::LoadFromCommandLine(
1785 const char **ArgBegin, const char **ArgEnd,
1786 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1787 std::shared_ptr<DiagnosticOptions> DiagOpts,
1788 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1789 bool StorePreamblesInMemory, StringRef PreambleStoragePath,
1790 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1791 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1792 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1793 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1794 bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
1795 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1796 bool RetainExcludedConditionalBlocks, std::optional<StringRef> ModuleFormat,
1797 std::unique_ptr<ASTUnit> *ErrAST,
1799 assert(Diags.get() && "no DiagnosticsEngine was provided");
1800
1801 // If no VFS was provided, create one that tracks the physical file system.
1802 // If '-working-directory' was passed as an argument, 'createInvocation' will
1803 // set this as the current working directory of the VFS.
1804 if (!VFS)
1805 VFS = llvm::vfs::createPhysicalFileSystem();
1806
1807 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1808
1809 std::shared_ptr<CompilerInvocation> CI;
1810
1811 {
1812 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1813 &StoredDiagnostics, nullptr);
1814
1816 CIOpts.VFS = VFS;
1817 CIOpts.Diags = Diags;
1818 CIOpts.ProbePrecompiled = true; // FIXME: historical default. Needed?
1819 CI = createInvocation(llvm::ArrayRef(ArgBegin, ArgEnd), std::move(CIOpts));
1820 if (!CI)
1821 return nullptr;
1822 }
1823
1824 // Override any files that need remapping
1825 for (const auto &RemappedFile : RemappedFiles) {
1826 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1827 RemappedFile.second);
1828 }
1829 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1830 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1831 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1832 PPOpts.SingleFileParseMode = SingleFileParse;
1833 PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
1834
1835 // Override the resources path.
1836 CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1837
1838 CI->getFrontendOpts().SkipFunctionBodies =
1840
1841 if (ModuleFormat)
1842 CI->getHeaderSearchOpts().ModuleFormat = std::string(*ModuleFormat);
1843
1844 // Create the AST unit.
1845 std::unique_ptr<ASTUnit> AST;
1846 AST.reset(new ASTUnit(false));
1847 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1848 AST->StoredDiagnostics.swap(StoredDiagnostics);
1849 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1850 AST->DiagOpts = DiagOpts;
1851 AST->Diagnostics = Diags;
1852 AST->FileSystemOpts = CI->getFileSystemOpts();
1853 AST->CodeGenOpts = std::make_unique<CodeGenOptions>(CI->getCodeGenOpts());
1854 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1855 AST->FileMgr =
1856 llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS);
1857 AST->StorePreamblesInMemory = StorePreamblesInMemory;
1858 AST->PreambleStoragePath = PreambleStoragePath;
1859 AST->ModCache = createCrossProcessModuleCache();
1860 AST->OnlyLocalDecls = OnlyLocalDecls;
1861 AST->CaptureDiagnostics = CaptureDiagnostics;
1862 AST->TUKind = TUKind;
1863 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1864 AST->IncludeBriefCommentsInCodeCompletion
1865 = IncludeBriefCommentsInCodeCompletion;
1866 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1867 AST->Invocation = CI;
1868 AST->SkipFunctionBodies = SkipFunctionBodies;
1869 if (ForSerialization)
1870 AST->WriterData.reset(new ASTWriterData(*AST->ModCache, *AST->CodeGenOpts));
1871 // Zero out now to ease cleanup during crash recovery.
1872 CI = nullptr;
1873 Diags = nullptr;
1874
1875 // Recover resources if we crash before exiting this method.
1876 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1877 ASTUnitCleanup(AST.get());
1878
1879 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1880 PrecompilePreambleAfterNParses,
1881 VFS)) {
1882 // Some error occurred, if caller wants to examine diagnostics, pass it the
1883 // ASTUnit.
1884 if (ErrAST) {
1885 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1886 ErrAST->swap(AST);
1887 }
1888 return nullptr;
1889 }
1890
1891 return AST;
1892}
1893
1894bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1895 ArrayRef<RemappedFile> RemappedFiles,
1897 if (!Invocation)
1898 return true;
1899
1900 if (!VFS) {
1901 assert(FileMgr && "FileMgr is null on Reparse call");
1902 VFS = FileMgr->getVirtualFileSystemPtr();
1903 }
1904
1905 clearFileLevelDecls();
1906
1907 SimpleTimer ParsingTimer(WantTiming);
1908 ParsingTimer.setOutput("Reparsing " + getMainFileName());
1909
1910 // Remap files.
1911 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1912 for (const auto &RB : PPOpts.RemappedFileBuffers)
1913 delete RB.second;
1914
1915 Invocation->getPreprocessorOpts().clearRemappedFiles();
1916 for (const auto &RemappedFile : RemappedFiles) {
1917 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1918 RemappedFile.second);
1919 }
1920
1921 // If we have a preamble file lying around, or if we might try to
1922 // build a precompiled preamble, do so now.
1923 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1924 if (Preamble || PreambleRebuildCountdown > 0)
1925 OverrideMainBuffer =
1926 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1927
1928 // Clear out the diagnostics state.
1929 FileMgr.reset();
1931 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts(),
1932 *VFS);
1933 if (OverrideMainBuffer)
1934 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1935
1936 // Parse the sources
1937 bool Result =
1938 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1939
1940 // If we're caching global code-completion results, and the top-level
1941 // declarations have changed, clear out the code-completion cache.
1942 if (!Result && ShouldCacheCodeCompletionResults &&
1943 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1944 CacheCodeCompletionResults();
1945
1946 // We now need to clear out the completion info related to this translation
1947 // unit; it'll be recreated if necessary.
1948 CCTUInfo.reset();
1949
1950 return Result;
1951}
1952
1954 SavedMainFileBuffer.reset();
1955
1956 SourceMgr.reset();
1957 TheSema.reset();
1958 Ctx.reset();
1959 PP.reset();
1960 Reader.reset();
1961
1962 TopLevelDecls.clear();
1963 clearFileLevelDecls();
1964}
1965
1966//----------------------------------------------------------------------------//
1967// Code completion
1968//----------------------------------------------------------------------------//
1969
1970namespace {
1971
1972 /// Code completion consumer that combines the cached code-completion
1973 /// results from an ASTUnit with the code-completion results provided to it,
1974 /// then passes the result on to
1975 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1976 uint64_t NormalContexts;
1977 ASTUnit &AST;
1979
1980 public:
1981 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1982 const CodeCompleteOptions &CodeCompleteOpts)
1983 : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
1984 // Compute the set of contexts in which we will look when we don't have
1985 // any information about the specific context.
1986 NormalContexts
2000
2001 if (AST.getASTContext().getLangOpts().CPlusPlus)
2002 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2005 }
2006
2007 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2008 CodeCompletionResult *Results,
2009 unsigned NumResults) override;
2010
2011 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2012 OverloadCandidate *Candidates,
2013 unsigned NumCandidates,
2014 SourceLocation OpenParLoc,
2015 bool Braced) override {
2016 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
2017 OpenParLoc, Braced);
2018 }
2019
2020 CodeCompletionAllocator &getAllocator() override {
2021 return Next.getAllocator();
2022 }
2023
2024 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2025 return Next.getCodeCompletionTUInfo();
2026 }
2027 };
2028
2029} // namespace
2030
2031/// Helper function that computes which global names are hidden by the
2032/// local code-completion results.
2034 CodeCompletionResult *Results,
2035 unsigned NumResults,
2036 ASTContext &Ctx,
2037 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2038 bool OnlyTagNames = false;
2039 switch (Context.getKind()) {
2059 break;
2060
2064 OnlyTagNames = true;
2065 break;
2066
2084 // We're looking for nothing, or we're looking for names that cannot
2085 // be hidden.
2086 return;
2087 }
2088
2090 for (unsigned I = 0; I != NumResults; ++I) {
2091 if (Results[I].Kind != Result::RK_Declaration)
2092 continue;
2093
2094 unsigned IDNS
2095 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2096
2097 bool Hiding = false;
2098 if (OnlyTagNames)
2099 Hiding = (IDNS & Decl::IDNS_Tag);
2100 else {
2101 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2104 if (Ctx.getLangOpts().CPlusPlus)
2105 HiddenIDNS |= Decl::IDNS_Tag;
2106 Hiding = (IDNS & HiddenIDNS);
2107 }
2108
2109 if (!Hiding)
2110 continue;
2111
2112 DeclarationName Name = Results[I].Declaration->getDeclName();
2113 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2114 HiddenNames.insert(Identifier->getName());
2115 else
2116 HiddenNames.insert(Name.getAsString());
2117 }
2118}
2119
2120void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2121 CodeCompletionContext Context,
2122 CodeCompletionResult *Results,
2123 unsigned NumResults) {
2124 // Merge the results we were given with the results we cached.
2125 bool AddedResult = false;
2126 uint64_t InContexts =
2127 Context.getKind() == CodeCompletionContext::CCC_Recovery
2128 ? NormalContexts : (1LL << Context.getKind());
2129 // Contains the set of names that are hidden by "local" completion results.
2130 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2132 SmallVector<Result, 8> AllResults;
2134 C = AST.cached_completion_begin(),
2135 CEnd = AST.cached_completion_end();
2136 C != CEnd; ++C) {
2137 // If the context we are in matches any of the contexts we are
2138 // interested in, we'll add this result.
2139 if ((C->ShowInContexts & InContexts) == 0)
2140 continue;
2141
2142 // If we haven't added any results previously, do so now.
2143 if (!AddedResult) {
2144 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2145 HiddenNames);
2146 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2147 AddedResult = true;
2148 }
2149
2150 // Determine whether this global completion result is hidden by a local
2151 // completion result. If so, skip it.
2152 if (C->Kind != CXCursor_MacroDefinition &&
2153 HiddenNames.count(C->Completion->getTypedText()))
2154 continue;
2155
2156 // Adjust priority based on similar type classes.
2157 unsigned Priority = C->Priority;
2158 CodeCompletionString *Completion = C->Completion;
2159 if (!Context.getPreferredType().isNull()) {
2160 if (C->Kind == CXCursor_MacroDefinition) {
2161 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2162 S.getLangOpts(),
2163 Context.getPreferredType()->isAnyPointerType());
2164 } else if (C->Type) {
2167 Context.getPreferredType().getUnqualifiedType());
2169 if (ExpectedSTC == C->TypeClass) {
2170 // We know this type is similar; check for an exact match.
2171 llvm::StringMap<unsigned> &CachedCompletionTypes
2173 llvm::StringMap<unsigned>::iterator Pos
2174 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2175 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2177 else
2179 }
2180 }
2181 }
2182
2183 // Adjust the completion string, if required.
2184 if (C->Kind == CXCursor_MacroDefinition &&
2185 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2186 // Create a new code-completion string that just contains the
2187 // macro name, without its arguments.
2188 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2189 CCP_CodePattern, C->Availability);
2190 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2192 Completion = Builder.TakeString();
2193 }
2194
2195 AllResults.push_back(Result(Completion, Priority, C->Kind,
2196 C->Availability));
2197 }
2198
2199 // If we did not add any cached completion results, just forward the
2200 // results we were given to the next consumer.
2201 if (!AddedResult) {
2202 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2203 return;
2204 }
2205
2206 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2207 AllResults.size());
2208}
2209
2211 StringRef File, unsigned Line, unsigned Column,
2212 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2213 bool IncludeCodePatterns, bool IncludeBriefComments,
2214 CodeCompleteConsumer &Consumer,
2215 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2219 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2221 std::unique_ptr<SyntaxOnlyAction> Act) {
2222 if (!Invocation)
2223 return;
2224
2225 SimpleTimer CompletionTimer(WantTiming);
2226 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2227 Twine(Line) + ":" + Twine(Column));
2228
2229 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2230
2231 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2232 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2233 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2234
2235 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2236 CachedCompletionResults.empty();
2237 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2238 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2239 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2240 CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
2241 CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
2242
2243 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2244
2245 FrontendOpts.CodeCompletionAt.FileName = std::string(File);
2246 FrontendOpts.CodeCompletionAt.Line = Line;
2247 FrontendOpts.CodeCompletionAt.Column = Column;
2248
2249 // Set the language options appropriately.
2250 LangOpts = CCInvocation->getLangOpts();
2251
2252 // Spell-checking and warnings are wasteful during code-completion.
2253 LangOpts.SpellChecking = false;
2254 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2255
2256 auto Clang = std::make_unique<CompilerInstance>(std::move(CCInvocation),
2257 PCHContainerOps);
2258
2259 // Recover resources if we crash before exiting this method.
2260 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2261 CICleanup(Clang.get());
2262
2263 auto &Inv = Clang->getInvocation();
2264 OriginalSourceFile =
2265 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2266
2267 // Set up diagnostics, capturing any diagnostics produced.
2268 Clang->setDiagnostics(Diag);
2269 CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
2270 Clang->getDiagnostics(),
2271 &StoredDiagnostics, nullptr);
2272 ProcessWarningOptions(*Diag, Inv.getDiagnosticOpts(),
2273 FileMgr->getVirtualFileSystem());
2274
2275 // Create the target instance.
2276 if (!Clang->createTarget()) {
2277 return;
2278 }
2279
2280 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2281 "Invocation must have exactly one source file!");
2282 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2284 "FIXME: AST inputs not yet supported here!");
2285 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2287 "IR inputs not support here!");
2288
2289 // Use the source and file managers that we were given.
2290 Clang->setFileManager(FileMgr);
2291 Clang->setSourceManager(SourceMgr);
2292
2293 // Remap files.
2294 PreprocessorOpts.clearRemappedFiles();
2295 PreprocessorOpts.RetainRemappedFileBuffers = true;
2296 for (const auto &RemappedFile : RemappedFiles) {
2297 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2298 OwnedBuffers.push_back(RemappedFile.second);
2299 }
2300
2301 // Use the code completion consumer we were given, but adding any cached
2302 // code-completion results.
2303 AugmentedCodeCompleteConsumer *AugmentedConsumer
2304 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2305 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2306
2307 auto getUniqueID =
2308 [&FileMgr](StringRef Filename) -> std::optional<llvm::sys::fs::UniqueID> {
2309 if (auto Status = FileMgr->getVirtualFileSystem().status(Filename))
2310 return Status->getUniqueID();
2311 return std::nullopt;
2312 };
2313
2314 auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
2315 if (LHS == RHS)
2316 return true;
2317 if (auto LHSID = getUniqueID(LHS))
2318 if (auto RHSID = getUniqueID(RHS))
2319 return *LHSID == *RHSID;
2320 return false;
2321 };
2322
2323 // If we have a precompiled preamble, try to use it. We only allow
2324 // the use of the precompiled preamble if we're if the completion
2325 // point is within the main file, after the end of the precompiled
2326 // preamble.
2327 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2328 if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) {
2329 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2330 PCHContainerOps, Inv, FileMgr->getVirtualFileSystemPtr(), false,
2331 Line - 1);
2332 }
2333
2334 // If the main file has been overridden due to the use of a preamble,
2335 // make that override happen and introduce the preamble.
2336 if (OverrideMainBuffer) {
2337 assert(Preamble &&
2338 "No preamble was built, but OverrideMainBuffer is not null");
2339
2341 FileMgr->getVirtualFileSystemPtr();
2342 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2343 OverrideMainBuffer.get());
2344 // FIXME: there is no way to update VFS if it was changed by
2345 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2346 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2347 // PCH files are always readable.
2348 OwnedBuffers.push_back(OverrideMainBuffer.release());
2349 } else {
2350 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2351 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2352 }
2353
2354 // Disable the preprocessing record if modules are not enabled.
2355 if (!Clang->getLangOpts().Modules)
2356 PreprocessorOpts.DetailedRecord = false;
2357
2358 if (!Act)
2359 Act.reset(new SyntaxOnlyAction);
2360
2361 if (Act->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
2362 if (llvm::Error Err = Act->Execute()) {
2363 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
2364 }
2365 Act->EndSourceFile();
2366 }
2367}
2368
2369bool ASTUnit::Save(StringRef File) {
2370 if (HadModuleLoaderFatalFailure)
2371 return true;
2372
2373 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2374 // unconditionally create a stat cache when we parse the file?
2375
2376 if (llvm::Error Err = llvm::writeToOutput(
2377 File, [this](llvm::raw_ostream &Out) {
2378 return serialize(Out) ? llvm::make_error<llvm::StringError>(
2379 "ASTUnit serialization failed",
2380 llvm::inconvertibleErrorCode())
2381 : llvm::Error::success();
2382 })) {
2383 consumeError(std::move(Err));
2384 return true;
2385 }
2386 return false;
2387}
2388
2389static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl<char> &Buffer,
2390 Sema &S, raw_ostream &OS) {
2391 Writer.WriteAST(&S, std::string(), nullptr, "");
2392
2393 // Write the generated bitstream to "Out".
2394 if (!Buffer.empty())
2395 OS.write(Buffer.data(), Buffer.size());
2396
2397 return false;
2398}
2399
2400bool ASTUnit::serialize(raw_ostream &OS) {
2401 if (WriterData)
2402 return serializeUnit(WriterData->Writer, WriterData->Buffer, getSema(), OS);
2403
2404 SmallString<128> Buffer;
2405 llvm::BitstreamWriter Stream(Buffer);
2407 ASTWriter Writer(Stream, Buffer, *ModCache, *CodeGenOpts, {});
2408 return serializeUnit(Writer, Buffer, getSema(), OS);
2409}
2410
2411void ASTUnit::TranslateStoredDiagnostics(
2412 FileManager &FileMgr,
2413 SourceManager &SrcMgr,
2416 // Map the standalone diagnostic into the new source manager. We also need to
2417 // remap all the locations to the new view. This includes the diag location,
2418 // any associated source ranges, and the source ranges of associated fix-its.
2419 // FIXME: There should be a cleaner way to do this.
2421 Result.reserve(Diags.size());
2422
2423 for (const auto &SD : Diags) {
2424 // Rebuild the StoredDiagnostic.
2425 if (SD.Filename.empty())
2426 continue;
2427 auto FE = FileMgr.getOptionalFileRef(SD.Filename);
2428 if (!FE)
2429 continue;
2430 SourceLocation FileLoc;
2431 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2432 if (ItFileID == PreambleSrcLocCache.end()) {
2433 FileID FID = SrcMgr.translateFile(*FE);
2434 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2435 PreambleSrcLocCache[SD.Filename] = FileLoc;
2436 } else {
2437 FileLoc = ItFileID->getValue();
2438 }
2439
2440 if (FileLoc.isInvalid())
2441 continue;
2442 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2443 FullSourceLoc Loc(L, SrcMgr);
2444
2446 Ranges.reserve(SD.Ranges.size());
2447 for (const auto &Range : SD.Ranges) {
2448 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2449 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2450 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2451 }
2452
2454 FixIts.reserve(SD.FixIts.size());
2455 for (const auto &FixIt : SD.FixIts) {
2456 FixIts.push_back(FixItHint());
2457 FixItHint &FH = FixIts.back();
2458 FH.CodeToInsert = FixIt.CodeToInsert;
2459 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2460 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2462 }
2463
2464 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2465 SD.Message, Loc, Ranges, FixIts));
2466 }
2467 Result.swap(Out);
2468}
2469
2471 assert(D);
2472
2473 // We only care about local declarations.
2474 if (D->isFromASTFile())
2475 return;
2476
2477 SourceManager &SM = *SourceMgr;
2479 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2480 return;
2481
2482 // We only keep track of the file-level declarations of each file.
2484 return;
2485
2486 SourceLocation FileLoc = SM.getFileLoc(Loc);
2487 assert(SM.isLocalSourceLocation(FileLoc));
2488 auto [FID, Offset] = SM.getDecomposedLoc(FileLoc);
2489 if (FID.isInvalid())
2490 return;
2491
2492 std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2493 if (!Decls)
2494 Decls = std::make_unique<LocDeclsTy>();
2495
2496 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2497
2498 if (Decls->empty() || Decls->back().first <= Offset) {
2499 Decls->push_back(LocDecl);
2500 return;
2501 }
2502
2503 LocDeclsTy::iterator I =
2504 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2505
2506 Decls->insert(I, LocDecl);
2507}
2508
2509void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2510 SmallVectorImpl<Decl *> &Decls) {
2511 if (File.isInvalid())
2512 return;
2513
2514 if (SourceMgr->isLoadedFileID(File)) {
2515 assert(Ctx->getExternalSource() && "No external source!");
2516 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2517 Decls);
2518 }
2519
2520 FileDeclsTy::iterator I = FileDecls.find(File);
2521 if (I == FileDecls.end())
2522 return;
2523
2524 LocDeclsTy &LocDecls = *I->second;
2525 if (LocDecls.empty())
2526 return;
2527
2528 LocDeclsTy::iterator BeginIt =
2529 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2530 return LD.first < Offset;
2531 });
2532 if (BeginIt != LocDecls.begin())
2533 --BeginIt;
2534
2535 // If we are pointing at a top-level decl inside an objc container, we need
2536 // to backtrack until we find it otherwise we will fail to report that the
2537 // region overlaps with an objc container.
2538 while (BeginIt != LocDecls.begin() &&
2539 BeginIt->second->isTopLevelDeclInObjCContainer())
2540 --BeginIt;
2541
2542 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2543 LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
2544 llvm::less_first());
2545 if (EndIt != LocDecls.end())
2546 ++EndIt;
2547
2548 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2549 Decls.push_back(DIt->second);
2550}
2551
2553 unsigned Line, unsigned Col) const {
2555 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2556 return SM.getMacroArgExpandedLocation(Loc);
2557}
2558
2560 unsigned Offset) const {
2562 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2563 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2564}
2565
2566/// If \arg Loc is a loaded location from the preamble, returns
2567/// the corresponding local location of the main file, otherwise it returns
2568/// \arg Loc.
2570 FileID PreambleID;
2571 if (SourceMgr)
2572 PreambleID = SourceMgr->getPreambleFileID();
2573
2574 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2575 return Loc;
2576
2577 unsigned Offs;
2578 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2579 SourceLocation FileLoc
2580 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2581 return FileLoc.getLocWithOffset(Offs);
2582 }
2583
2584 return Loc;
2585}
2586
2587/// If \arg Loc is a local location of the main file but inside the
2588/// preamble chunk, returns the corresponding loaded location from the
2589/// preamble, otherwise it returns \arg Loc.
2591 FileID PreambleID;
2592 if (SourceMgr)
2593 PreambleID = SourceMgr->getPreambleFileID();
2594
2595 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2596 return Loc;
2597
2598 unsigned Offs;
2599 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2600 Offs < Preamble->getBounds().Size) {
2601 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2602 return FileLoc.getLocWithOffset(Offs);
2603 }
2604
2605 return Loc;
2606}
2607
2609 FileID FID;
2610 if (SourceMgr)
2611 FID = SourceMgr->getPreambleFileID();
2612
2613 if (Loc.isInvalid() || FID.isInvalid())
2614 return false;
2615
2616 return SourceMgr->isInFileID(Loc, FID);
2617}
2618
2620 FileID FID;
2621 if (SourceMgr)
2622 FID = SourceMgr->getMainFileID();
2623
2624 if (Loc.isInvalid() || FID.isInvalid())
2625 return false;
2626
2627 return SourceMgr->isInFileID(Loc, FID);
2628}
2629
2631 FileID FID;
2632 if (SourceMgr)
2633 FID = SourceMgr->getPreambleFileID();
2634
2635 if (FID.isInvalid())
2636 return {};
2637
2638 return SourceMgr->getLocForEndOfFile(FID);
2639}
2640
2642 FileID FID;
2643 if (SourceMgr)
2644 FID = SourceMgr->getMainFileID();
2645
2646 if (FID.isInvalid())
2647 return {};
2648
2649 return SourceMgr->getLocForStartOfFile(FID);
2650}
2651
2652llvm::iterator_range<PreprocessingRecord::iterator>
2654 if (isMainFileAST()) {
2656 Mod = Reader->getModuleManager().getPrimaryModule();
2657 return Reader->getModulePreprocessedEntities(Mod);
2658 }
2659
2661 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2662
2663 return llvm::make_range(PreprocessingRecord::iterator(),
2665}
2666
2668 if (isMainFileAST()) {
2670 Mod = Reader->getModuleManager().getPrimaryModule();
2671 for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2672 if (!Fn(context, D))
2673 return false;
2674 }
2675
2676 return true;
2677 }
2678
2680 TLEnd = top_level_end();
2681 TL != TLEnd; ++TL) {
2682 if (!Fn(context, *TL))
2683 return false;
2684 }
2685
2686 return true;
2687}
2688
2690 if (!Reader)
2691 return std::nullopt;
2692
2693 serialization::ModuleFile *Mod = nullptr;
2694 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2695 switch (M.Kind) {
2696 case serialization::MK_ImplicitModule:
2697 case serialization::MK_ExplicitModule:
2698 case serialization::MK_PrebuiltModule:
2699 return true; // skip dependencies.
2700 case serialization::MK_PCH:
2701 Mod = &M;
2702 return true; // found it.
2703 case serialization::MK_Preamble:
2704 return false; // look in dependencies.
2705 case serialization::MK_MainFile:
2706 return false; // look in dependencies.
2707 }
2708
2709 return true;
2710 });
2711 if (Mod)
2712 return Mod->File;
2713
2714 return std::nullopt;
2715}
2716
2719}
2720
2722 auto &LangOpts = getLangOpts();
2723
2724 Language Lang;
2725 if (LangOpts.OpenCL)
2726 Lang = Language::OpenCL;
2727 else if (LangOpts.CUDA)
2728 Lang = Language::CUDA;
2729 else if (LangOpts.CPlusPlus)
2730 Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
2731 else
2732 Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
2733
2735 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2737
2738 // We don't know if input was preprocessed. Assume not.
2739 bool PP = false;
2740
2741 return InputKind(Lang, Fmt, PP);
2742}
2743
2744#ifndef NDEBUG
2745ASTUnit::ConcurrencyState::ConcurrencyState() {
2746 Mutex = new std::recursive_mutex;
2747}
2748
2749ASTUnit::ConcurrencyState::~ConcurrencyState() {
2750 delete static_cast<std::recursive_mutex *>(Mutex);
2751}
2752
2753void ASTUnit::ConcurrencyState::start() {
2754 bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
2755 assert(acquired && "Concurrent access to ASTUnit!");
2756}
2757
2758void ASTUnit::ConcurrencyState::finish() {
2759 static_cast<std::recursive_mutex *>(Mutex)->unlock();
2760}
2761
2762#else // NDEBUG
2763
2764ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2765ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2766void ASTUnit::ConcurrencyState::start() {}
2767void ASTUnit::ConcurrencyState::finish() {}
2768
2769#endif // NDEBUG
Defines the clang::ASTContext interface.
static void checkAndSanitizeDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SourceManager &SM)
Definition: ASTUnit.cpp:1133
static void CalculateHiddenNames(const CodeCompletionContext &Context, CodeCompletionResult *Results, unsigned NumResults, ASTContext &Ctx, llvm::StringSet< llvm::BumpPtrAllocator > &HiddenNames)
Helper function that computes which global names are hidden by the local code-completion results.
Definition: ASTUnit.cpp:2033
static uint64_t getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier)
Determine the set of code-completion contexts in which this declaration should be shown.
Definition: ASTUnit.cpp:283
static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash)
Add the given declaration to the hash of all top-level entities.
Definition: ASTUnit.cpp:952
static bool moveOnNoError(llvm::ErrorOr< T > Val, T &Output)
Definition: ASTUnit.cpp:144
static std::unique_ptr< T > valueOrNull(llvm::ErrorOr< std::unique_ptr< T > > Val)
Definition: ASTUnit.cpp:137
static std::pair< unsigned, unsigned > makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Definition: ASTUnit.cpp:1287
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl< char > &Buffer, Sema &S, raw_ostream &OS)
Definition: ASTUnit.cpp:2389
static std::unique_ptr< llvm::MemoryBuffer > getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, llvm::vfs::FileSystem *VFS, StringRef FilePath, bool isVolatile)
Get a source buffer for MainFilePath, handling all file-to-file and file-to-buffer remappings inside ...
Definition: ASTUnit.cpp:154
const unsigned DefaultPreambleRebuildInterval
After failing to build a precompiled preamble (due to errors in the source that occurs in the preambl...
Definition: ASTUnit.cpp:230
static void checkAndRemoveNonDriverDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiags)
Definition: ASTUnit.cpp:1127
static bool isInMainFile(const clang::Diagnostic &D)
Definition: ASTUnit.cpp:731
static ASTUnit::StandaloneDiagnostic makeStandaloneDiagnostic(const LangOptions &LangOpts, const StoredDiagnostic &InDiag)
Definition: ASTUnit.cpp:1308
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag)
Definition: ASTUnit.cpp:1122
static std::atomic< unsigned > ActiveASTUnitObjects
Tracks the number of ASTUnit objects that are currently active.
Definition: ASTUnit.cpp:235
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, const LangOptions &LangOpts, const FixItHint &InFix)
Definition: ASTUnit.cpp:1295
static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash)
Add the given macro to the hash of all top-level entities.
Definition: ASTUnit.cpp:929
Defines the Diagnostic-related interfaces.
const Decl * D
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::FileManager interface and associated types.
int Priority
Definition: Format.cpp:3181
StringRef Filename
Definition: Format.cpp:3177
StringRef Identifier
Definition: Format.cpp:3185
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
#define X(type, name)
Definition: Value.h:145
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
#define SM(sm)
Definition: OffloadArch.cpp:16
Defines the PPCallbacks interface.
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TargetOptions class.
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
comments::CommandTraits & getCommentCommandTraits() const
Definition: ASTContext.h:1058
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Definition: ASTContext.h:797
Abstract base class to use for AST consumer-based frontend actions.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:117
@ ARR_None
The client can't handle any AST loading failures.
Definition: ASTReader.h:1828
@ Success
The control block was read successfully.
Definition: ASTReader.h:452
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:469
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:462
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:455
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:465
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:472
@ Missing
The AST file was missing.
Definition: ASTReader.h:458
Utility class for loading a ASTContext from an AST file.
Definition: ASTUnit.h:90
unsigned & getCurrentTopLevelHashValue()
Retrieve a reference to the current top-level name hash value.
Definition: ASTUnit.h:570
void enableSourceFileDiagnostics()
Enable source-range based diagnostic messages.
Definition: ASTUnit.cpp:275
void addFileLevelDecl(Decl *D)
Add a new local file-level declaration.
Definition: ASTUnit.cpp:2470
const FileManager & getFileManager() const
Definition: ASTUnit.h:502
void CodeComplete(StringRef File, unsigned Line, unsigned Column, ArrayRef< RemappedFile > RemappedFiles, bool IncludeMacros, bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr< PCHContainerOperations > PCHContainerOps, llvm::IntrusiveRefCntPtr< DiagnosticsEngine > Diag, LangOptions &LangOpts, llvm::IntrusiveRefCntPtr< SourceManager > SourceMgr, llvm::IntrusiveRefCntPtr< FileManager > FileMgr, SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SmallVectorImpl< const llvm::MemoryBuffer * > &OwnedBuffers, std::unique_ptr< SyntaxOnlyAction > Act)
Perform code completion at the given file, line, and column within this translation unit.
Definition: ASTUnit.cpp:2210
cached_completion_iterator cached_completion_end()
Definition: ASTUnit.h:658
bool serialize(raw_ostream &OS)
Serialize this translation unit with the given output stream.
Definition: ASTUnit.cpp:2400
ASTDeserializationListener * getDeserializationListener()
Definition: ASTUnit.cpp:781
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles={}, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Reparse the source files using the same command-line options that were originally used to produce thi...
Definition: ASTUnit.cpp:1894
std::unique_ptr< llvm::MemoryBuffer > getBufferForFile(StringRef Filename, std::string *ErrorStr=nullptr)
Definition: ASTUnit.cpp:788
llvm::StringMap< unsigned > & getCachedCompletionTypes()
Retrieve the mapping from formatted type names to unique type identifiers.
Definition: ASTUnit.h:322
const DiagnosticsEngine & getDiagnostics() const
Definition: ASTUnit.h:446
SourceLocation getLocation(const FileEntry *File, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
Definition: ASTUnit.cpp:2552
void ResetForParse()
Free data that will be re-generated on the next parse.
Definition: ASTUnit.cpp:1953
llvm::IntrusiveRefCntPtr< SourceManager > getSourceManagerPtr()
Definition: ASTUnit.h:454
InputKind getInputKind() const
Determine the input kind this AST unit represents.
Definition: ASTUnit.cpp:2721
OptionalFileEntryRef getPCHFile()
Get the PCH file if one was included.
Definition: ASTUnit.cpp:2689
StringRef getMainFileName() const
Definition: ASTUnit.cpp:1518
Sema & getSema() const
Definition: ASTUnit.h:482
static std::unique_ptr< ASTUnit > LoadFromASTFile(StringRef Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, const HeaderSearchOptions &HSOpts, const LangOptions *LangOpts=nullptr, bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, bool AllowASTWithCompilerErrors=false, bool UserFilesAreVolatile=false, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=llvm::vfs::getRealFileSystem())
Create a ASTUnit from an AST file.
Definition: ASTUnit.cpp:809
SourceLocation mapLocationToPreamble(SourceLocation Loc) const
If Loc is a local location of the main file but inside the preamble chunk, returns the corresponding ...
Definition: ASTUnit.cpp:2590
cached_completion_iterator cached_completion_begin()
Definition: ASTUnit.h:654
const LangOptions & getLangOpts() const
Definition: ASTUnit.h:487
bool isMainFileAST() const
Definition: ASTUnit.h:441
std::vector< Decl * >::iterator top_level_iterator
Definition: ASTUnit.h:527
const SourceManager & getSourceManager() const
Definition: ASTUnit.h:452
SourceLocation getEndOfPreambleFileID() const
Definition: ASTUnit.cpp:2630
llvm::IntrusiveRefCntPtr< DiagnosticsEngine > getDiagnosticsPtr()
Definition: ASTUnit.h:448
static ASTUnit * LoadFromCompilerInvocationAction(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, FrontendAction *Action=nullptr, ASTUnit *Unit=nullptr, bool Persistent=true, StringRef ResourceFilesPath=StringRef(), bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, unsigned PrecompilePreambleAfterNParses=0, bool CacheCodeCompletionResults=false, bool UserFilesAreVolatile=false, std::unique_ptr< ASTUnit > *ErrAST=nullptr)
Create an ASTUnit from a source file, via a CompilerInvocation object, by invoking the optionally pro...
Definition: ASTUnit.cpp:1569
@ LoadASTOnly
Load the AST, but do not restore Sema state.
Definition: ASTUnit.h:714
@ LoadEverything
Load everything, including Sema.
Definition: ASTUnit.h:717
top_level_iterator top_level_end()
Definition: ASTUnit.h:536
SourceLocation getStartOfMainFileID() const
Definition: ASTUnit.cpp:2641
IntrusiveRefCntPtr< ASTReader > getASTReader() const
Definition: ASTUnit.cpp:771
IntrusiveRefCntPtr< FileManager > getFileManagerPtr()
Definition: ASTUnit.h:504
bool(*)(void *context, const Decl *D) DeclVisitorFn
Type for a function iterating over a number of declarations.
Definition: ASTUnit.h:674
bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn)
Iterate over local declarations (locally parsed if this is a parsed source file or the loaded declara...
Definition: ASTUnit.cpp:2667
llvm::iterator_range< PreprocessingRecord::iterator > getLocalPreprocessingEntities() const
Returns an iterator range for the local preprocessing entities of the local Preprocessor,...
Definition: ASTUnit.cpp:2653
top_level_iterator top_level_begin()
Definition: ASTUnit.h:529
std::vector< CachedCodeCompletionResult >::iterator cached_completion_iterator
Definition: ASTUnit.h:652
ASTMutationListener * getASTMutationListener()
Definition: ASTUnit.cpp:775
TranslationUnitKind getTranslationUnitKind() const
Determine what kind of translation unit this AST represents.
Definition: ASTUnit.h:693
static std::unique_ptr< ASTUnit > LoadFromCommandLine(const char **ArgBegin, const char **ArgEnd, std::shared_ptr< PCHContainerOperations > PCHContainerOps, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, StringRef ResourceFilesPath, bool StorePreamblesInMemory=false, StringRef PreambleStoragePath=StringRef(), bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, ArrayRef< RemappedFile > RemappedFiles={}, bool RemappedFilesKeepOriginalName=true, unsigned PrecompilePreambleAfterNParses=0, TranslationUnitKind TUKind=TU_Complete, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=false, bool AllowPCHWithCompilerErrors=false, SkipFunctionBodiesScope SkipFunctionBodies=SkipFunctionBodiesScope::None, bool SingleFileParse=false, bool UserFilesAreVolatile=false, bool ForSerialization=false, bool RetainExcludedConditionalBlocks=false, std::optional< StringRef > ModuleFormat=std::nullopt, std::unique_ptr< ASTUnit > *ErrAST=nullptr, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
LoadFromCommandLine - Create an ASTUnit from a vector of command line arguments, which must specify e...
Definition: ASTUnit.cpp:1784
void setPreprocessor(std::shared_ptr< Preprocessor > pp)
Definition: ASTUnit.cpp:271
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
Definition: ASTUnit.cpp:1536
bool Save(StringRef File)
Save this translation unit to a file with the given name.
Definition: ASTUnit.cpp:2369
const HeaderSearchOptions & getHeaderSearchOpts() const
Definition: ASTUnit.h:492
static std::unique_ptr< ASTUnit > create(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, CaptureDiagsKind CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
Definition: ASTUnit.cpp:1546
void addTopLevelDecl(Decl *D)
Add a new top-level declaration.
Definition: ASTUnit.h:554
bool isInMainFileID(SourceLocation Loc) const
Definition: ASTUnit.cpp:2619
bool isModuleFile() const
Returns true if the ASTUnit was constructed from a serialized module file.
Definition: ASTUnit.cpp:2717
void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls)
Get the decls that are contained in a file in the Offset/Length range.
Definition: ASTUnit.cpp:2509
const ASTContext & getASTContext() const
Definition: ASTUnit.h:462
bool isInPreambleFileID(SourceLocation Loc) const
Definition: ASTUnit.cpp:2608
SourceLocation mapLocationFromPreamble(SourceLocation Loc) const
If Loc is a loaded location from the preamble, returns the corresponding local location of the main f...
Definition: ASTUnit.cpp:2569
std::pair< std::string, llvm::MemoryBuffer * > RemappedFile
A mapping from a file name to the memory buffer that stores the remapped contents of that file.
Definition: ASTUnit.h:700
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:97
LocalDeclID getDeclID(const Decl *D)
Determine the local declaration ID of an already-emitted declaration.
Definition: ASTWriter.cpp:6954
ASTFileSignature WriteAST(llvm::PointerUnion< Sema *, Preprocessor * > Subject, StringRef OutputFile, Module *WritingModule, StringRef isysroot, bool ShouldCacheASTInMemory=false)
Write a precompiled header or a module with the AST produced by the Sema object, or a dependency scan...
Definition: ASTWriter.cpp:5448
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
SourceLocation getEnd() const
SourceLocation getBegin() const
Abstract interface for a consumer of code-completion information.
bool includeFixIts() const
Whether to include completion items with small fix-its, e.g.
bool loadExternal() const
Hint whether to load data from the external AST in order to provide full results.
Options controlling the behavior of code completion.
unsigned IncludeCodePatterns
Show code patterns in code completion results.
unsigned IncludeFixIts
Include results after corrections (small fix-its), e.g.
unsigned LoadExternal
Hint whether to load data from the external AST to provide full results.
unsigned IncludeMacros
Show macros in code completion results.
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
unsigned IncludeGlobals
Show top-level decls in code completion results.
An allocator used specifically for the purpose of code completion.
A builder class used to construct new code-completion strings.
The context in which code completion occurred, so that the code-completion consumer can process the r...
@ CCC_TypeQualifiers
Code completion within a type-qualifier list.
@ CCC_ObjCMessageReceiver
Code completion occurred where an Objective-C message receiver is expected.
@ CCC_PreprocessorExpression
Code completion occurred within a preprocessor expression.
@ CCC_ObjCCategoryName
Code completion where an Objective-C category name is expected.
@ CCC_ObjCIvarList
Code completion occurred within the instance variable list of an Objective-C interface,...
@ CCC_Statement
Code completion occurred where a statement (or declaration) is expected in a function,...
@ CCC_Type
Code completion occurred where a type name is expected.
@ CCC_ArrowMemberAccess
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
@ CCC_ClassStructUnion
Code completion occurred within a class, struct, or union.
@ CCC_ObjCInterface
Code completion occurred within an Objective-C interface, protocol, or category interface.
@ CCC_ObjCPropertyAccess
Code completion occurred on the right-hand side of an Objective-C property access expression.
@ CCC_Expression
Code completion occurred where an expression is expected.
@ CCC_SelectorName
Code completion for a selector, as in an @selector expression.
@ CCC_TopLevelOrExpression
Code completion at a top level, i.e.
@ CCC_EnumTag
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
@ CCC_UnionTag
Code completion occurred after the "union" keyword, to indicate a union name.
@ CCC_ParenthesizedExpression
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
@ CCC_TopLevel
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope.
@ CCC_ClassOrStructTag
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name.
@ CCC_ObjCClassMessage
Code completion where an Objective-C class message is expected.
@ CCC_ObjCImplementation
Code completion occurred within an Objective-C implementation or category implementation.
@ CCC_IncludedFile
Code completion inside the filename part of a #include directive.
@ CCC_ObjCInstanceMessage
Code completion where an Objective-C instance message is expected.
@ CCC_SymbolOrNewName
Code completion occurred where both a new name and an existing symbol is permissible.
@ CCC_Recovery
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
@ CCC_ObjCProtocolName
Code completion occurred where a protocol name is expected.
@ CCC_OtherWithMacros
An unspecified code-completion context where we should also add macro completions.
@ CCC_NewName
Code completion occurred where a new name is expected.
@ CCC_MacroNameUse
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
@ CCC_Symbol
Code completion occurred where an existing name(such as type, function or variable) is expected.
@ CCC_Attribute
Code completion of an attribute name.
@ CCC_Other
An unspecified code-completion context.
@ CCC_DotMemberAccess
Code completion occurred on the right-hand side of a member access expression using the dot operator.
@ CCC_MacroName
Code completion occurred where an macro is being defined.
@ CCC_Namespace
Code completion occurred where a namespace or namespace alias is expected.
@ CCC_PreprocessorDirective
Code completion occurred where a preprocessor directive is expected.
@ CCC_NaturalLanguage
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
@ CCC_ObjCInterfaceName
Code completion where the name of an Objective-C class is expected.
Captures a result of code completion.
A "string" used to describe how code completion can be performed for an entity.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
std::shared_ptr< Preprocessor > getPreprocessorPtr()
std::unique_ptr< Sema > takeSema()
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
std::shared_ptr< CompilerInvocation > getInvocationPtr()
bool hadModuleLoaderFatalFailure() const
void setSourceManager(llvm::IntrusiveRefCntPtr< SourceManager > Value)
setSourceManager - Replace the current source manager.
CompilerInvocation & getInvocation()
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager and virtual file system.
Helper class for holding the data necessary to invoke the compiler.
PreprocessorOptions & getPreprocessorOpts()
LangOptions & getLangOpts()
Mutable getters.
FrontendOptions & getFrontendOpts()
DiagnosticOptions & getDiagnosticOpts()
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
bool isFileContext() const
Definition: DeclBase.h:2180
bool isTranslationUnit() const
Definition: DeclBase.h:2185
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1309
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:793
bool isInvalidDecl() const
Definition: DeclBase.h:588
SourceLocation getLocation() const
Definition: DeclBase.h:439
@ IDNS_NonMemberOperator
This declaration is a C++ operator declared in a non-class context.
Definition: DeclBase.h:168
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
@ IDNS_Type
Types, declared with 'struct foo', typedefs, etc.
Definition: DeclBase.h:130
@ IDNS_Member
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:136
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
Definition: DeclBase.h:140
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
DeclContext * getDeclContext()
Definition: DeclBase.h:448
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
The name of a declaration.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1722
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
Definition: Diagnostic.h:1754
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
Definition: Diagnostic.cpp:812
virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr)
Callback to inform the diagnostic client that processing of a source file is beginning.
Definition: Diagnostic.h:1746
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Definition: Diagnostic.h:1548
SourceManager & getSourceManager() const
Definition: Diagnostic.h:1566
bool hasSourceManager() const
Definition: Diagnostic.h:1565
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
void setNumWarnings(unsigned NumWarnings)
Definition: Diagnostic.h:888
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:100
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition: Diagnostic.h:614
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:236
DiagnosticConsumer * getClient()
Definition: Diagnostic.h:606
unsigned getNumWarnings() const
Definition: Diagnostic.h:886
void Reset(bool soft=false)
Reset the state of the diagnostic object to its initial configuration.
Definition: Diagnostic.cpp:124
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:306
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:219
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:208
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
Definition: FileManager.h:221
void setVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Definition: FileManager.h:229
Keeps track of options that affect how file operations are performed.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:78
bool BeforePreviousInsertions
Definition: Diagnostic.h:92
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
Definition: Diagnostic.h:82
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
Definition: Diagnostic.h:86
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
Definition: Diagnostic.h:90
Abstract base class for actions which can be performed by the frontend.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
llvm::Error Execute()
Set the source manager's main input file, and run the action.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
An input file for the front end.
llvm::MemoryBufferRef getBuffer() const
StringRef getFile() const
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned SkipFunctionBodies
Skip over function bodies to speed up parsing in cases you do not need them (e.g.
CodeCompleteOptions CodeCompleteOpts
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
A SourceLocation and its associated SourceManager.
const SourceManager & getManager() const
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:237
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
The kind of a file that we've been handed as an input.
Format
The input file format.
@ CMK_ModuleMap
Compiling a module from a module map.
Definition: LangOptions.h:121
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:498
bool isCompilingModule() const
Are we compiling a module?
Definition: LangOptions.h:596
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Definition: Lexer.cpp:951
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition: MacroInfo.h:313
The module cache used for compiling modules implicitly.
Definition: ModuleCache.h:26
Describes a module or submodule.
Definition: Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:224
This represents a decl that may have a name.
Definition: Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:486
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual llvm::ArrayRef< llvm::StringRef > getFormats() const =0
Equivalent to the format passed to -fmodule-format=.
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:37
A set of callbacks to gather useful information while building a preamble.
static llvm::ErrorOr< PrecompiledPreamble > Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, IntrusiveRefCntPtr< DiagnosticsEngine > Diagnostics, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHContainerOps, bool StoreInMemory, StringRef StoragePath, PreambleCallbacks &Callbacks)
Try to build PrecompiledPreamble for Invocation.
Iteration over the preprocessed entities.
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
bool SingleFileParseMode
When enabled, preprocessor is in a mode for parsing a single file only.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
bool RetainExcludedConditionalBlocks
When enabled, excluded conditional blocks retain in the main file.
void addRemappedFile(StringRef From, StringRef To)
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
std::vector< std::pair< std::string, llvm::MemoryBuffer * > > RemappedFileBuffers
The set of file-to-buffer remappings, which take existing files on the system (the first part of each...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
SourceManager & getSourceManager() const
FileManager & getFileManager() const
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
IdentifierTable & getIdentifierTable()
Builtin::Context & getBuiltinInfo()
const LangOptions & getLangOpts() const
void setCounterValue(unsigned V)
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
DiagnosticsEngine & getDiagnostics() const
SelectorTable & getSelectorTable()
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: TypeBase.h:1332
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
ASTContext & Context
Definition: Sema.h:1276
const LangOptions & getLangOpts() const
Definition: Sema.h:911
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
SourceLocation getLocForEndOfFile(FileID FID) const
Return the source location corresponding to the last byte of the specified file.
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isInFileID(SourceLocation Loc, FileID FID, unsigned *RelativeOffset=nullptr) const
Given a specific FileID, returns true if Loc is inside that FileID chunk and sets relative offset (of...
FileID getPreambleFileID() const
Get the file ID for the precompiled preamble if there is one.
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
Definition: Diagnostic.h:1672
unsigned getID() const
Definition: Diagnostic.h:1693
ArrayRef< FixItHint > getFixIts() const
Definition: Diagnostic.h:1714
ArrayRef< CharSourceRange > getRanges() const
Definition: Diagnostic.h:1706
DiagnosticsEngine::Level getLevel() const
Definition: Diagnostic.h:1694
const FullSourceLoc & getLocation() const
Definition: Diagnostic.h:1695
StringRef getMessage() const
Definition: Diagnostic.h:1696
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Definition: Targets.cpp:777
Options for controlling the target.
Definition: TargetOptions.h:26
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:189
void registerCommentOptions(const CommentOptions &CommentOptions)
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:130
FileEntryRef File
The file entry for the module file.
Definition: ModuleFile.h:185
std::string FileName
The file name of the module file.
Definition: ModuleFile.h:145
ModuleKind Kind
The type of this module.
Definition: ModuleFile.h:142
@ CXCursor_MacroDefinition
Definition: Index.h:2284
Defines the clang::TargetInfo interface.
@ FixIt
Parse and apply any fixits to the source.
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition: ModuleFile.h:57
@ VFS
Remove unused -ivfsoverlay arguments.
The JSON file list parser is used to communicate input to InstallAPI.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromOverlayFiles(ArrayRef< std::string > VFSOverlayFiles, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
SkipFunctionBodiesScope
Enumerates the available scopes for skipping function bodies.
Definition: ASTUnit.h:84
@ CCF_ExactTypeMatch
Divide by this factor when a code-completion result's type exactly matches the type we expect.
@ CCF_SimilarTypeMatch
Divide by this factor when a code-completion result's type is similar to the type we expect (e....
@ Parse
Parse the block; this code is always used.
std::unique_ptr< CompilerInvocation > createInvocation(ArrayRef< const char * > Args, CreateInvocationOptions Opts={})
Interpret clang arguments in preparation to parse a file.
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion.
CaptureDiagsKind
Enumerates the available kinds for capturing diagnostics.
Definition: ASTUnit.h:87
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
IntrusiveRefCntPtr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
Definition: ModuleCache.cpp:63
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition: Warnings.cpp:46
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1097
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1099
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
const FunctionProtoType * T
@ CCP_NestedNameSpecifier
Priority for a nested-name-specifier.
@ CCP_CodePattern
Priority for a code pattern.
unsigned getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer=false)
Determine the priority to be given to a macro code completion result with the given name.
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ All
Disable validation for all kinds.
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts, const llvm::MemoryBufferRef &Buffer, unsigned MaxLines)
Runs lexer to compute suggested preamble bounds.
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:60
QualType getDeclUsageType(ASTContext &C, NestedNameSpecifier Qualifier, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression.
unsigned long uint64_t
#define false
Definition: stdbool.h:26
llvm::BitstreamWriter Stream
Definition: ASTUnit.cpp:215
SmallString< 128 > Buffer
Definition: ASTUnit.cpp:214
ASTWriterData(ModuleCache &ModCache, const CodeGenOptions &CGOpts)
Definition: ASTUnit.cpp:218
DiagnosticsEngine::Level Level
Definition: ASTUnit.h:101
std::vector< std::pair< unsigned, unsigned > > Ranges
Definition: ASTUnit.h:105
std::vector< StandaloneFixIt > FixIts
Definition: ASTUnit.h:106
std::pair< unsigned, unsigned > InsertFromRange
Definition: ASTUnit.h:94
std::pair< unsigned, unsigned > RemoveRange
Definition: ASTUnit.h:93
Optional inputs to createInvocation.
Definition: Utils.h:195
IntrusiveRefCntPtr< DiagnosticsEngine > Diags
Receives diagnostics encountered while parsing command-line flags.
Definition: Utils.h:198
bool ProbePrecompiled
Allow the driver to probe the filesystem for PCH files.
Definition: Utils.h:211
IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS
Used e.g.
Definition: Utils.h:202
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:926
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
Definition: Lexer.h:60
unsigned Size
Size of the preamble in bytes.
Definition: Lexer.h:62
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57