37 #include "llvm/ADT/ArrayRef.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/ADT/StringSet.h" 40 #include "llvm/Support/CrashRecoveryContext.h" 41 #include "llvm/Support/Host.h" 42 #include "llvm/Support/MemoryBuffer.h" 43 #include "llvm/Support/Mutex.h" 44 #include "llvm/Support/MutexGuard.h" 45 #include "llvm/Support/Timer.h" 46 #include "llvm/Support/raw_ostream.h" 51 using namespace clang;
53 using llvm::TimeRecord;
62 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
64 Start = TimeRecord::getCurrentTime();
67 void setOutput(
const Twine &Output) {
69 this->Output = Output.str();
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 llvm::errs() << Output <<
':';
77 Elapsed.print(Elapsed, llvm::errs());
84 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
87 return std::move(*Val);
91 bool moveOnNoError(llvm::ErrorOr<T> Val,
T &Output) {
94 Output = std::move(*Val);
100 static std::unique_ptr<llvm::MemoryBuffer>
103 StringRef FilePath) {
109 llvm::MemoryBuffer *Buffer =
nullptr;
110 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
111 auto FileStatus = VFS->
status(FilePath);
113 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
116 for (
const auto &RF : PreprocessorOpts.RemappedFiles) {
117 std::string MPath(RF.first);
118 auto MPathStatus = VFS->
status(MPath);
120 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
121 if (MainFileID == MID) {
132 for (
const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
133 std::string MPath(RB.first);
134 auto MPathStatus = VFS->
status(MPath);
136 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
137 if (MainFileID == MID) {
140 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
147 if (!Buffer && !BufferOwner) {
157 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
167 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
170 void ASTUnit::clearFileLevelDecls() {
171 llvm::DeleteContainerSeconds(FileDecls);
185 ASTUnit::ASTUnit(
bool _MainFileIsAST)
186 : Reader(nullptr), HadModuleLoaderFatalFailure(
false),
187 OnlyLocalDecls(
false), CaptureDiagnostics(
false),
188 MainFileIsAST(_MainFileIsAST),
189 TUKind(
TU_Complete), WantTiming(getenv(
"LIBCLANG_TIMING")),
190 OwnsRemappedFileBuffers(
true),
191 NumStoredDiagnosticsFromDriver(0),
192 PreambleRebuildCounter(0),
193 NumWarningsInPreamble(0),
194 ShouldCacheCodeCompletionResults(
false),
195 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
196 CompletionCacheTopLevelHashValue(0),
197 PreambleTopLevelHashValue(0),
198 CurrentTopLevelHashValue(0),
199 UnsafeToFree(
false) {
200 if (getenv(
"LIBCLANG_OBJTRACKING"))
201 fprintf(stderr,
"+++ %u translation units\n", ++ActiveASTUnitObjects);
204 ASTUnit::~ASTUnit() {
210 clearFileLevelDecls();
216 if (Invocation && OwnsRemappedFileBuffers) {
222 ClearCachedCompletionResults();
224 if (getenv(
"LIBCLANG_OBJTRACKING"))
225 fprintf(stderr,
"--- %u translation units\n", --ActiveASTUnitObjects);
229 this->PP = std::move(PP);
236 bool &IsNestedNameSpecifier) {
237 IsNestedNameSpecifier =
false;
239 if (isa<UsingShadowDecl>(ND))
244 uint64_t Contexts = 0;
245 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
246 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
247 isa<TypeAliasTemplateDecl>(ND)) {
249 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
258 if (LangOpts.CPlusPlus)
263 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
267 if (
const auto *
ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
269 if (
ID->getDefinition())
275 if (isa<EnumDecl>(ND)) {
279 if (LangOpts.CPlusPlus11)
280 IsNestedNameSpecifier =
true;
281 }
else if (
const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
282 if (Record->isUnion())
287 if (LangOpts.CPlusPlus)
288 IsNestedNameSpecifier =
true;
289 }
else if (isa<ClassTemplateDecl>(ND))
290 IsNestedNameSpecifier =
true;
291 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
297 }
else if (isa<ObjCProtocolDecl>(ND)) {
299 }
else if (isa<ObjCCategoryDecl>(ND)) {
301 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
305 IsNestedNameSpecifier =
true;
311 void ASTUnit::CacheCodeCompletionResults() {
315 SimpleTimer Timer(WantTiming);
316 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
319 ClearCachedCompletionResults();
324 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
326 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
330 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
333 for (Result &R : Results) {
335 case Result::RK_Declaration: {
336 bool IsNestedNameSpecifier =
false;
337 CachedCodeCompletionResult CachedResult;
338 CachedResult.Completion = R.CreateCodeCompletionString(
339 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
340 IncludeBriefCommentsInCodeCompletion);
342 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
343 CachedResult.Priority = R.Priority;
344 CachedResult.Kind = R.CursorKind;
345 CachedResult.Availability = R.Availability;
352 CachedResult.Type = 0;
361 unsigned &TypeValue = CompletionTypes[CanUsageType];
362 if (TypeValue == 0) {
363 TypeValue = CompletionTypes.size();
368 CachedResult.Type = TypeValue;
371 CachedCompletionResults.push_back(CachedResult);
374 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
375 !R.StartsNestedNameSpecifier) {
391 if (isa<NamespaceDecl>(R.Declaration) ||
392 isa<NamespaceAliasDecl>(R.Declaration))
395 if (
unsigned RemainingContexts
396 = NNSContexts & ~CachedResult.ShowInContexts) {
400 R.StartsNestedNameSpecifier =
true;
401 CachedResult.Completion = R.CreateCodeCompletionString(
402 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
403 IncludeBriefCommentsInCodeCompletion);
404 CachedResult.ShowInContexts = RemainingContexts;
407 CachedResult.Type = 0;
408 CachedCompletionResults.push_back(CachedResult);
414 case Result::RK_Keyword:
415 case Result::RK_Pattern:
420 case Result::RK_Macro: {
421 CachedCodeCompletionResult CachedResult;
422 CachedResult.Completion = R.CreateCodeCompletionString(
423 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
424 IncludeBriefCommentsInCodeCompletion);
425 CachedResult.ShowInContexts
439 CachedResult.Priority = R.Priority;
440 CachedResult.Kind = R.CursorKind;
441 CachedResult.Availability = R.Availability;
443 CachedResult.Type = 0;
444 CachedCompletionResults.push_back(CachedResult);
451 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
454 void ASTUnit::ClearCachedCompletionResults() {
455 CachedCompletionResults.clear();
456 CachedCompletionTypes.clear();
457 CachedCompletionAllocator =
nullptr;
470 std::shared_ptr<TargetOptions> &TargetOpts;
471 IntrusiveRefCntPtr<TargetInfo> &Target;
474 bool InitializedLanguage;
479 std::shared_ptr<TargetOptions> &TargetOpts,
480 IntrusiveRefCntPtr<TargetInfo> &Target,
unsigned &Counter)
481 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
482 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
483 Counter(Counter), InitializedLanguage(
false) {}
485 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
486 bool AllowCompatibleDifferences)
override {
487 if (InitializedLanguage)
491 InitializedLanguage =
true;
498 StringRef SpecificModuleCachePath,
499 bool Complain)
override {
500 this->HSOpts = HSOpts;
506 std::string &SuggestedPredefines)
override {
507 this->PPOpts = PPOpts;
511 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
512 bool AllowCompatibleDifferences)
override {
517 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
526 unsigned Value)
override {
532 if (!Target || !InitializedLanguage)
539 Target->adjust(LangOpt);
568 StoredDiagnosticConsumer(
571 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
572 LangOpts(
nullptr), SourceMgr(
nullptr) {
573 assert((StoredDiags || StandaloneDiags) &&
574 "No output collections were passed to StoredDiagnosticConsumer.");
579 this->LangOpts = &LangOpts;
581 SourceMgr = &PP->getSourceManager();
590 class CaptureDroppedDiagnostics {
592 StoredDiagnosticConsumer Client;
594 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
600 : Diags(Diags), Client(StoredDiags, StandaloneDiags), PreviousClient(
nullptr)
602 if (RequestCapture || Diags.
getClient() ==
nullptr) {
609 ~CaptureDroppedDiagnostics() {
611 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
632 StoredDiags->emplace_back(Level, Info);
633 ResultDiag = &StoredDiags->back();
636 if (StandaloneDiags) {
639 StoredDiag.emplace(Level, Info);
640 ResultDiag = StoredDiag.getPointer();
642 StandaloneDiags->push_back(
654 return &WriterData->Writer;
660 return &WriterData->Writer;
664 std::unique_ptr<llvm::MemoryBuffer>
667 auto Buffer = FileMgr->getBufferForFile(Filename);
669 return std::move(*Buffer);
671 *ErrorStr = Buffer.getError().message();
677 ASTUnit &AST,
bool CaptureDiagnostics) {
678 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
679 if (CaptureDiagnostics)
680 Diags->setClient(
new StoredDiagnosticConsumer(&AST.StoredDiagnostics,
nullptr));
688 bool CaptureDiagnostics,
bool AllowPCHWithCompilerErrors,
689 bool UserFilesAreVolatile) {
690 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
693 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
694 ASTUnitCleanup(AST.get());
696 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
697 DiagCleanup(Diags.get());
699 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
701 AST->LangOpts = std::make_shared<LangOptions>();
702 AST->OnlyLocalDecls = OnlyLocalDecls;
703 AST->CaptureDiagnostics = CaptureDiagnostics;
704 AST->Diagnostics = Diags;
706 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
707 AST->UserFilesAreVolatile = UserFilesAreVolatile;
709 AST->getFileManager(),
710 UserFilesAreVolatile);
712 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
713 AST->HSOpts->ModuleFormat = PCHContainerRdr.
getFormat();
715 AST->getSourceManager(),
716 AST->getDiagnostics(),
719 AST->PPOpts = std::make_shared<PreprocessorOptions>();
729 AST->PP = std::make_shared<Preprocessor>(
730 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
731 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
737 AST->Ctx =
new ASTContext(*AST->LangOpts, AST->getSourceManager(),
738 PP.getIdentifierTable(), PP.getSelectorTable(),
739 PP.getBuiltinInfo());
741 bool disableValid =
false;
742 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
744 AST->Reader =
new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { },
747 AllowPCHWithCompilerErrors);
749 AST->Reader->
setListener(llvm::make_unique<ASTInfoCollector>(
750 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
751 AST->TargetOpts, AST->Target, Counter));
759 AST->Ctx->setExternalSource(AST->Reader);
772 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
776 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
778 PP.setCounterValue(Counter);
786 AST->TheSema.reset(
new Sema(PP, *AST->Ctx, *AST->Consumer));
787 AST->TheSema->Initialize();
788 AST->Reader->InitializeSema(*AST->TheSema);
792 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
800 void AddDefinedMacroToHash(
const Token &MacroNameTok,
unsigned &Hash) {
806 class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
810 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) { }
812 void MacroDefined(
const Token &MacroNameTok,
814 AddDefinedMacroToHash(MacroNameTok, Hash);
819 void AddTopLevelDeclarationToHash(
Decl *D,
unsigned &Hash) {
830 if (
NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
831 if (
EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
834 if (!EnumD->isScoped()) {
835 for (
const auto *EI : EnumD->enumerators()) {
836 if (EI->getIdentifier())
837 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
842 if (ND->getIdentifier())
843 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
845 std::string NameStr = Name.getAsString();
846 Hash = llvm::HashString(NameStr, Hash);
851 if (
ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
852 if (
Module *Mod = ImportD->getImportedModule()) {
853 std::string ModName = Mod->getFullModuleName();
854 Hash = llvm::HashString(ModName, Hash);
860 class TopLevelDeclTrackerConsumer :
public ASTConsumer {
865 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
866 : Unit(_Unit), Hash(Hash) {
870 void handleTopLevelDecl(
Decl *D) {
878 if (isa<ObjCMethodDecl>(D))
881 AddTopLevelDeclarationToHash(D, Hash);
884 handleFileLevelDecl(D);
887 void handleFileLevelDecl(
Decl *D) {
890 for (
auto *I : NSD->decls())
891 handleFileLevelDecl(I);
896 for (
Decl *TopLevelDecl : D)
897 handleTopLevelDecl(TopLevelDecl);
904 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
905 for (
Decl *TopLevelDecl : D)
906 handleTopLevelDecl(TopLevelDecl);
923 StringRef InFile)
override {
925 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
927 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
932 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
934 bool hasCodeCompletionSupport()
const override {
return false; }
942 unsigned getHash()
const {
return Hash; }
944 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
946 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
947 return std::move(TopLevelDeclIDs);
950 void AfterPCHEmitted(
ASTWriter &Writer)
override {
951 TopLevelDeclIDs.reserve(TopLevelDecls.size());
952 for (
Decl *D : TopLevelDecls) {
956 TopLevelDeclIDs.push_back(Writer.
getDeclID(D));
966 if (isa<ObjCMethodDecl>(D))
968 AddTopLevelDeclarationToHash(D, Hash);
969 TopLevelDecls.push_back(D);
973 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
974 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
979 std::vector<Decl *> TopLevelDecls;
980 std::vector<serialization::DeclID> TopLevelDeclIDs;
995 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1008 if (SD.getLocation().isValid()) {
1010 SD.setLocation(Loc);
1020 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1021 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1022 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1026 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1027 if (OverrideMainBuffer) {
1029 "No preamble was built, but OverrideMainBuffer is not null");
1030 IntrusiveRefCntPtr<vfs::FileSystem> OldVFS = VFS;
1031 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1032 if (OldVFS != VFS && FileMgr) {
1033 assert(OldVFS == FileMgr->getVirtualFileSystem() &&
1034 "VFS passed to Parse and VFS in FileMgr are different");
1035 FileMgr =
new FileManager(FileMgr->getFileSystemOpts(), VFS);
1040 std::unique_ptr<CompilerInstance> Clang(
1042 if (FileMgr && VFS) {
1043 assert(VFS == FileMgr->getVirtualFileSystem() &&
1044 "VFS passed to Parse and VFS in FileMgr are different");
1046 Clang->setVirtualFileSystem(VFS);
1050 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1051 CICleanup(Clang.get());
1053 Clang->setInvocation(CCInvocation);
1054 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1062 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1063 if (!Clang->hasTarget())
1070 Clang->getTarget().adjust(Clang->getLangOpts());
1072 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1073 "Invocation must have exactly one source file!");
1074 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1076 "FIXME: AST inputs not yet supported here!");
1077 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1079 "IR inputs not support here!");
1082 LangOpts = Clang->getInvocation().LangOpts;
1083 FileSystemOpts = Clang->getFileSystemOpts();
1085 Clang->createFileManager();
1086 FileMgr = &Clang->getFileManager();
1092 UserFilesAreVolatile);
1093 if (!OverrideMainBuffer) {
1095 TopLevelDeclsInPreamble.clear();
1106 if (OverrideMainBuffer) {
1115 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1118 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1119 new TopLevelDeclTrackerAction(*
this));
1122 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1123 ActCleanup(Act.get());
1125 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1128 if (SavedMainFileBuffer)
1130 PreambleDiagnostics, StoredDiagnostics);
1132 PreambleSrcLocCache.clear();
1134 if (!Act->Execute())
1137 transferASTDataFromCompilerInstance(*Clang);
1139 Act->EndSourceFile();
1141 FailedParseDiagnostics.clear();
1147 SavedMainFileBuffer =
nullptr;
1151 transferASTDataFromCompilerInstance(*Clang);
1152 FailedParseDiagnostics.swap(StoredDiagnostics);
1153 StoredDiagnostics.clear();
1154 NumStoredDiagnosticsFromDriver = 0;
1158 static std::pair<unsigned, unsigned>
1164 return std::make_pair(Offset, EndOffset);
1223 std::unique_ptr<llvm::MemoryBuffer>
1224 ASTUnit::getMainBufferWithPrecompiledPreamble(
1225 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1227 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
bool AllowRebuild,
1228 unsigned MaxLines) {
1232 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1233 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1235 if (!MainFileBuffer)
1240 MainFileBuffer.get(), MaxLines);
1245 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1256 PreambleRebuildCounter = 1;
1257 return MainFileBuffer;
1260 PreambleDiagnostics.clear();
1261 TopLevelDeclsInPreamble.clear();
1262 PreambleRebuildCounter = 1;
1269 if (PreambleRebuildCounter > 1) {
1270 --PreambleRebuildCounter;
1274 assert(!Preamble &&
"No Preamble should be stored at that point");
1282 ASTUnitPreambleCallbacks Callbacks;
1285 if (CaptureDiagnostics)
1286 Capture.emplace(
true, *Diagnostics, &NewPreambleDiags,
1287 &NewPreambleDiagsStandalone);
1290 SimpleTimer PreambleTimer(WantTiming);
1291 PreambleTimer.setOutput(
"Precompiling preamble");
1294 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1295 PCHContainerOps,
false, Callbacks);
1297 Preamble = std::move(*NewPreamble);
1298 PreambleRebuildCounter = 1;
1300 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1304 PreambleRebuildCounter = 1;
1314 llvm_unreachable(
"unexpected BuildPreambleError");
1318 assert(Preamble &&
"Preamble wasn't built");
1320 TopLevelDecls.clear();
1321 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1322 PreambleTopLevelHashValue = Callbacks.getHash();
1327 StoredDiagnostics = std::move(NewPreambleDiags);
1328 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1333 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1334 CompletionCacheTopLevelHashValue = 0;
1335 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1338 return MainFileBuffer;
1341 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1342 assert(Preamble &&
"Should only be called when preamble was built");
1344 std::vector<Decl *> Resolved;
1345 Resolved.reserve(TopLevelDeclsInPreamble.size());
1351 Resolved.push_back(D);
1353 TopLevelDeclsInPreamble.clear();
1354 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1382 return Input.
getBuffer()->getBufferIdentifier();
1387 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1388 return FE->getName();
1399 Mod = Reader->getModuleManager().getPrimaryModule();
1403 std::unique_ptr<ASTUnit>
1406 bool CaptureDiagnostics,
bool UserFilesAreVolatile) {
1407 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1408 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1413 AST->Diagnostics = Diags;
1414 AST->FileSystemOpts = CI->getFileSystemOpts();
1415 AST->Invocation = std::move(CI);
1416 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1417 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1418 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1419 UserFilesAreVolatile);
1426 std::shared_ptr<CompilerInvocation> CI,
1427 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1429 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1430 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1431 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1432 bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile,
1433 std::unique_ptr<ASTUnit> *ErrAST) {
1434 assert(CI &&
"A CompilerInvocation is required");
1436 std::unique_ptr<ASTUnit> OwnAST;
1440 OwnAST =
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1446 if (!ResourceFilesPath.empty()) {
1450 AST->OnlyLocalDecls = OnlyLocalDecls;
1451 AST->CaptureDiagnostics = CaptureDiagnostics;
1452 if (PrecompilePreambleAfterNParses > 0)
1453 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1455 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1456 AST->IncludeBriefCommentsInCodeCompletion
1457 = IncludeBriefCommentsInCodeCompletion;
1460 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1461 ASTUnitCleanup(OwnAST.get());
1463 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1464 DiagCleanup(Diags.get());
1467 CI->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1468 CI->getFrontendOpts().DisableFree =
false;
1472 std::unique_ptr<CompilerInstance> Clang(
1476 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1477 CICleanup(Clang.get());
1479 Clang->setInvocation(std::move(CI));
1480 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1488 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1489 if (!Clang->hasTarget())
1496 Clang->getTarget().adjust(Clang->getLangOpts());
1498 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1499 "Invocation must have exactly one source file!");
1500 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1502 "FIXME: AST inputs not yet supported here!");
1503 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1505 "IR inputs not support here!");
1508 AST->TheSema.reset();
1511 AST->Reader =
nullptr;
1521 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1523 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1524 Act = TrackerAct.get();
1528 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1529 ActCleanup(TrackerAct.get());
1531 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1532 AST->transferASTDataFromCompilerInstance(*Clang);
1533 if (OwnAST && ErrAST)
1534 ErrAST->swap(OwnAST);
1539 if (Persistent && !TrackerAct) {
1540 Clang->getPreprocessor().addPPCallbacks(
1541 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1543 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1544 if (Clang->hasASTConsumer())
1545 Consumers.push_back(Clang->takeASTConsumer());
1546 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1548 Clang->setASTConsumer(
1549 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1552 AST->transferASTDataFromCompilerInstance(*Clang);
1553 if (OwnAST && ErrAST)
1554 ErrAST->swap(OwnAST);
1560 AST->transferASTDataFromCompilerInstance(*Clang);
1565 return OwnAST.release();
1570 bool ASTUnit::LoadFromCompilerInvocation(
1571 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1572 unsigned PrecompilePreambleAfterNParses,
1577 assert(VFS &&
"VFS is null");
1585 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1586 if (PrecompilePreambleAfterNParses > 0) {
1587 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1588 OverrideMainBuffer =
1589 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1594 SimpleTimer ParsingTimer(WantTiming);
1598 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1599 MemBufferCleanup(OverrideMainBuffer.get());
1601 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1604 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1605 std::shared_ptr<CompilerInvocation> CI,
1606 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1608 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1610 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1611 bool UserFilesAreVolatile) {
1613 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1614 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1615 AST->Diagnostics = Diags;
1616 AST->OnlyLocalDecls = OnlyLocalDecls;
1617 AST->CaptureDiagnostics = CaptureDiagnostics;
1618 AST->TUKind = TUKind;
1619 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1620 AST->IncludeBriefCommentsInCodeCompletion
1621 = IncludeBriefCommentsInCodeCompletion;
1622 AST->Invocation = std::move(CI);
1624 AST->FileMgr = FileMgr;
1625 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1628 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1629 ASTUnitCleanup(AST.get());
1631 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1632 DiagCleanup(Diags.get());
1634 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1635 PrecompilePreambleAfterNParses,
1636 AST->FileMgr->getVirtualFileSystem()))
1642 const char **ArgBegin,
const char **ArgEnd,
1643 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1645 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1648 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1649 bool AllowPCHWithCompilerErrors,
bool SkipFunctionBodies,
1650 bool SingleFileParse,
bool UserFilesAreVolatile,
bool ForSerialization,
1653 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1657 std::shared_ptr<CompilerInvocation> CI;
1661 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1662 &StoredDiagnostics,
nullptr);
1665 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1672 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1681 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1683 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1686 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1689 std::unique_ptr<ASTUnit> AST;
1690 AST.reset(
new ASTUnit(
false));
1691 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1692 AST->Diagnostics = Diags;
1693 AST->FileSystemOpts = CI->getFileSystemOpts();
1699 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1701 AST->OnlyLocalDecls = OnlyLocalDecls;
1702 AST->CaptureDiagnostics = CaptureDiagnostics;
1703 AST->TUKind = TUKind;
1704 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1705 AST->IncludeBriefCommentsInCodeCompletion
1706 = IncludeBriefCommentsInCodeCompletion;
1707 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1708 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1709 AST->StoredDiagnostics.swap(StoredDiagnostics);
1710 AST->Invocation = CI;
1711 if (ForSerialization)
1718 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1719 ASTUnitCleanup(AST.get());
1721 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1722 PrecompilePreambleAfterNParses,
1727 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1733 return AST.release();
1743 assert(FileMgr &&
"FileMgr is null on Reparse call");
1744 VFS = FileMgr->getVirtualFileSystem();
1747 clearFileLevelDecls();
1749 SimpleTimer ParsingTimer(WantTiming);
1765 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1766 if (Preamble || PreambleRebuildCounter > 0)
1767 OverrideMainBuffer =
1768 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1775 if (OverrideMainBuffer)
1780 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1784 if (!Result && ShouldCacheCodeCompletionResults &&
1785 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1786 CacheCodeCompletionResults();
1796 SavedMainFileBuffer.reset();
1804 TopLevelDecls.clear();
1805 clearFileLevelDecls();
1817 uint64_t NormalContexts;
1825 AST(AST), Next(Next)
1852 unsigned NumResults)
override;
1854 void ProcessOverloadCandidates(
Sema &S,
unsigned CurrentArg,
1856 unsigned NumCandidates)
override {
1874 unsigned NumResults,
1876 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1877 bool OnlyTagNames =
false;
1902 OnlyTagNames =
true;
1924 for (
unsigned I = 0; I != NumResults; ++I) {
1925 if (Results[I].
Kind != Result::RK_Declaration)
1931 bool Hiding =
false;
1940 Hiding = (IDNS & HiddenIDNS);
1948 HiddenNames.insert(Identifier->getName());
1954 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
1957 unsigned NumResults) {
1959 bool AddedResult =
false;
1960 uint64_t InContexts =
1962 ? NormalContexts : (1LL << Context.
getKind());
1964 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
1973 if ((
C->ShowInContexts & InContexts) == 0)
1980 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1987 HiddenNames.count(
C->Completion->getTypedText()))
1991 unsigned Priority =
C->Priority;
1998 }
else if (
C->Type) {
2003 if (ExpectedSTC ==
C->TypeClass) {
2005 llvm::StringMap<unsigned> &CachedCompletionTypes
2007 llvm::StringMap<unsigned>::iterator Pos
2009 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2029 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2036 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2040 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2045 StringRef File,
unsigned Line,
unsigned Column,
2047 bool IncludeCodePatterns,
bool IncludeBriefComments,
2049 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2056 SimpleTimer CompletionTimer(WantTiming);
2057 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2058 Twine(Line) +
":" + Twine(Column));
2060 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2067 CachedCompletionResults.empty();
2069 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2072 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2079 LangOpts = *CCInvocation->getLangOpts();
2082 LangOpts.SpellChecking =
false;
2083 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2085 std::unique_ptr<CompilerInstance> Clang(
2089 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2090 CICleanup(Clang.get());
2092 auto &Inv = *CCInvocation;
2093 Clang->setInvocation(std::move(CCInvocation));
2094 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2097 Clang->setDiagnostics(&Diag);
2098 CaptureDroppedDiagnostics Capture(
true,
2099 Clang->getDiagnostics(),
2100 &StoredDiagnostics,
nullptr);
2105 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2106 if (!Clang->hasTarget()) {
2107 Clang->setInvocation(
nullptr);
2115 Clang->getTarget().adjust(Clang->getLangOpts());
2117 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2118 "Invocation must have exactly one source file!");
2119 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2121 "FIXME: AST inputs not yet supported here!");
2122 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2124 "IR inputs not support here!");
2127 Clang->setFileManager(&FileMgr);
2128 Clang->setSourceManager(&SourceMgr);
2140 AugmentedCodeCompleteConsumer *AugmentedConsumer
2141 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2142 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2148 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2150 std::string CompleteFilePath(File);
2153 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2154 if (CompleteFileStatus) {
2155 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2157 std::string MainPath(OriginalSourceFile);
2158 auto MainStatus = VFS->status(MainPath);
2160 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2161 if (CompleteFileID == MainID && Line > 1)
2162 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2163 PCHContainerOps, Inv, VFS,
false, Line - 1);
2170 if (OverrideMainBuffer) {
2172 "No preamble was built, but OverrideMainBuffer is not null");
2175 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2176 OverrideMainBuffer.get());
2181 OwnedBuffers.push_back(OverrideMainBuffer.release());
2188 if (!Clang->getLangOpts().Modules)
2191 std::unique_ptr<SyntaxOnlyAction> Act;
2193 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2195 Act->EndSourceFile();
2200 if (HadModuleLoaderFatalFailure)
2207 TempPath +=
"-%%%%%%%%";
2209 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2214 llvm::raw_fd_ostream Out(fd,
true);
2218 if (Out.has_error()) {
2223 if (llvm::sys::fs::rename(TempPath, File)) {
2224 llvm::sys::fs::remove(TempPath);
2236 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2239 if (!Buffer.empty())
2240 OS.write(Buffer.data(), Buffer.size());
2250 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2254 llvm::BitstreamWriter Stream(Buffer);
2256 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2262 void ASTUnit::TranslateStoredDiagnostics(
2272 Result.reserve(Diags.size());
2274 for (
const StandaloneDiagnostic &SD : Diags) {
2276 if (SD.Filename.empty())
2282 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2283 if (ItFileID == PreambleSrcLocCache.end()) {
2286 PreambleSrcLocCache[SD.Filename] = FileLoc;
2288 FileLoc = ItFileID->getValue();
2297 Ranges.reserve(SD.Ranges.size());
2298 for (
const auto &Range : SD.Ranges) {
2305 FixIts.reserve(SD.FixIts.size());
2306 for (
const StandaloneFixIt &
FixIt : SD.FixIts) {
2316 SD.Message, Loc, Ranges, FixIts));
2342 if (FID.isInvalid())
2349 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2351 if (Decls->empty() || Decls->back().first <=
Offset) {
2352 Decls->push_back(LocDecl);
2356 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2357 LocDecl, llvm::less_first());
2359 Decls->insert(I, LocDecl);
2367 if (SourceMgr->isLoadedFileID(File)) {
2368 assert(Ctx->getExternalSource() &&
"No external source!");
2369 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2373 FileDeclsTy::iterator I = FileDecls.find(File);
2374 if (I == FileDecls.end())
2378 if (LocDecls.empty())
2381 LocDeclsTy::iterator BeginIt =
2382 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2383 std::make_pair(Offset, (
Decl *)
nullptr),
2384 llvm::less_first());
2385 if (BeginIt != LocDecls.begin())
2391 while (BeginIt != LocDecls.begin() &&
2392 BeginIt->second->isTopLevelDeclInObjCContainer())
2395 LocDeclsTy::iterator EndIt = std::upper_bound(
2396 LocDecls.begin(), LocDecls.end(),
2397 std::make_pair(Offset + Length, (
Decl *)
nullptr), llvm::less_first());
2398 if (EndIt != LocDecls.end())
2401 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2402 Decls.push_back(DIt->second);
2406 unsigned Line,
unsigned Col)
const {
2425 PreambleID = SourceMgr->getPreambleFileID();
2431 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2433 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2446 PreambleID = SourceMgr->getPreambleFileID();
2452 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2453 Offs < Preamble->getBounds().Size) {
2454 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2464 FID = SourceMgr->getPreambleFileID();
2469 return SourceMgr->isInFileID(Loc, FID);
2475 FID = SourceMgr->getMainFileID();
2480 return SourceMgr->isInFileID(Loc, FID);
2486 FID = SourceMgr->getPreambleFileID();
2491 return SourceMgr->getLocForEndOfFile(FID);
2497 FID = SourceMgr->getMainFileID();
2502 return SourceMgr->getLocForStartOfFile(FID);
2505 llvm::iterator_range<PreprocessingRecord::iterator>
2509 Mod = Reader->getModuleManager().getPrimaryModule();
2510 return Reader->getModulePreprocessedEntities(Mod);
2514 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2523 Mod = Reader->getModuleManager().getPrimaryModule();
2524 for (
const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2525 if (!Fn(context, D))
2534 TL != TLEnd; ++TL) {
2535 if (!Fn(context, *TL))
2549 case serialization::MK_ImplicitModule:
2550 case serialization::MK_ExplicitModule:
2551 case serialization::MK_PrebuiltModule:
2553 case serialization::MK_PCH:
2556 case serialization::MK_Preamble:
2558 case serialization::MK_MainFile:
2578 if (LangOpts.OpenCL)
2580 else if (LangOpts.CUDA)
2582 else if (LangOpts.RenderScript)
2584 else if (LangOpts.CPlusPlus)
2600 ASTUnit::ConcurrencyState::ConcurrencyState() {
2601 Mutex =
new llvm::sys::MutexImpl(
true);
2604 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2605 delete static_cast<llvm::sys::MutexImpl *
>(Mutex);
2608 void ASTUnit::ConcurrencyState::start() {
2609 bool acquired =
static_cast<llvm::sys::MutexImpl *
>(Mutex)->tryacquire();
2610 assert(acquired &&
"Concurrent access to ASTUnit!");
2613 void ASTUnit::ConcurrencyState::finish() {
2614 static_cast<llvm::sys::MutexImpl *
>(Mutex)->release();
2619 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2620 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2621 void ASTUnit::ConcurrencyState::start() {}
2622 void ASTUnit::ConcurrencyState::finish() {}
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Defines the clang::ASTContext interface.
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
void ResetForParse()
Free data that will be re-generated on the next parse.
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.
CompilerInvocation & getInvocation()
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
DiagnosticConsumer * getClient()
A (possibly-)qualified type.
virtual Decl * GetExternalDecl(uint32_t ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
Implements support for file system lookup, file system caching, and directory search management...
const LangOptions & getLangOpts() const
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
std::pair< unsigned, unsigned > InsertFromRange
void addTopLevelDecl(Decl *D)
Add a new top-level declaration.
Code completion for a selector, as in an @selector expression.
void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
unsigned IncludeGlobals
Show top-level decls in code completion results.
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...
Code completion where an Objective-C class message is expected.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
Code completion within a type-qualifier list.
Load everything, including Sema.
Abstract base class for actions which can be performed by the frontend.
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
Decl - This represents one declaration (or definition), e.g.
ModuleKind Kind
The type of this module.
const FileManager & getFileManager() const
const unsigned DefaultPreambleRebuildInterval
After failing to build a precompiled preamble (due to errors in the source that occurs in the preambl...
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
An unspecified code-completion context.
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
NamespaceDecl - Represent a C++ namespace.
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
static std::unique_ptr< ASTUnit > LoadFromASTFile(const std::string &Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, bool UseDebugInfo=false, bool OnlyLocalDecls=false, ArrayRef< RemappedFile > RemappedFiles=None, bool CaptureDiagnostics=false, bool AllowPCHWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
unsigned getIdentifierNamespace() const
Code completion occurred where an Objective-C message receiver is expected.
ASTContext & getASTContext() const
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
bool isOutputBinary() const
Determine whether the output of this consumer is binary.
Options for controlling the target.
Manage memory buffers across multiple users.
SourceLocation mapLocationToPreamble(SourceLocation Loc) const
If Loc is a local location of the main file but inside the preamble chunk, returns the corresponding ...
void addRemappedFile(StringRef From, StringRef To)
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
static void checkAndSanitizeDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SourceManager &SM)
bool isInvalidDecl() const
Code completion occurred within the instance variable list of an Objective-C interface, implementation, or category implementation.
void AddTypedTextChunk(const char *Text)
Add a new typed-text chunk.
Describes how types, statements, expressions, and declarations should be printed. ...
bool hasSourceManager() const
This interface provides a way to observe the actions of the preprocessor as it does its thing...
Parse and apply any fixits to the source.
static std::unique_ptr< ASTUnit > create(std::shared_ptr< CompilerInvocation > CI, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, bool CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
Types, declared with 'struct foo', typedefs, etc.
std::vector< std::pair< unsigned, unsigned > > Ranges
RecordDecl - Represents a struct/union/class.
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
The virtual file system interface.
One of these records is kept for each identifier that is lexed.
CodeCompletionString * TakeString()
Take the resulting completion string.
cached_completion_iterator cached_completion_end()
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
SourceLocation getBegin() const
Iteration over the preprocessed entities.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Utility class for loading a ASTContext from an AST file.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
A "string" used to describe how code completion can be performed for an entity.
static std::atomic< unsigned > ActiveASTUnitObjects
Tracks the number of ASTUnit objects that are currently active.
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
static llvm::ErrorOr< PrecompiledPreamble > Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr< vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHContainerOps, bool StoreInMemory, PreambleCallbacks &Callbacks)
Try to build PrecompiledPreamble for Invocation.
Token - This structure provides full information about a lexed token.
bool isInPreambleFileID(SourceLocation Loc) const
std::unique_ptr< llvm::MemoryBuffer > getBufferForFile(StringRef Filename, std::string *ErrorStr=nullptr)
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
bool BeforePreviousInsertions
std::shared_ptr< Preprocessor > getPreprocessorPtr()
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Compiling a module from a module map.
Describes a module or submodule.
StringRef getMainFileName() const
unsigned IncludeCodePatterns
Show code patterns in code completion results.
An allocator used specifically for the purpose of code completion.
DiagnosticsEngine::Level Level
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
Load the AST, but do not restore Sema state.
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
static ASTUnit * LoadFromCommandLine(const char **ArgBegin, const char **ArgEnd, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, StringRef ResourceFilesPath, bool OnlyLocalDecls=false, bool CaptureDiagnostics=false, ArrayRef< RemappedFile > RemappedFiles=None, bool RemappedFilesKeepOriginalName=true, unsigned PrecompilePreambleAfterNParses=0, TranslationUnitKind TUKind=TU_Complete, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=false, bool AllowPCHWithCompilerErrors=false, bool SkipFunctionBodies=false, bool SingleFileParse=false, bool UserFilesAreVolatile=false, bool ForSerialization=false, llvm::Optional< StringRef > ModuleFormat=llvm::None, std::unique_ptr< ASTUnit > *ErrAST=nullptr, IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
LoadFromCommandLine - Create an ASTUnit from a vector of command line arguments, which must specify e...
void setPreprocessor(std::shared_ptr< Preprocessor > pp)
Priority for a nested-name-specifier.
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
Namespaces, declared with 'namespace foo {}'.
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
const FileEntry * getPCHFile()
Get the PCH file if one was included.
Code completion occurred where a preprocessor directive is expected.
bool serialize(raw_ostream &OS)
Serialize this translation unit with the given output stream.
Concrete class used by the front-end to report problems and issues.
virtual CodeCompletionTUInfo & getCodeCompletionTUInfo()=0
Code completion occurred within an Objective-C implementation or category implementation.
ArrayRef< CharSourceRange > getRanges() const
Defines the Diagnostic-related interfaces.
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
void addFileLevelDecl(Decl *D)
Add a new local file-level declaration.
QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression...
Code completion occurred where a namespace or namespace alias is expected.
ASTDeserializationListener * getDeserializationListener()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
const LangOptions & getLangOpts() const
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag)
StringRef getMessage() const
void Reset()
Reset the state of the diagnostic object to its initial configuration.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
The AST file itself appears corrupted.
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...
FrontendOptions & getFrontendOpts()
A set of callbacks to gather useful information while building a preamble.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Code completion where an Objective-C category name is expected.
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static void checkAndRemoveNonDriverDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiags)
Sema - This implements semantic analysis and AST building for C.
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope...
This declaration is a C++ operator declared in a non-class context.
bool isModuleFile() const
Returns true if the ASTUnit was constructed from a serialized module file.
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
Code completion occurred where a protocol name is expected.
Allows QualTypes to be sorted and hence used in maps and sets.
CommentOptions CommentOpts
Options for parsing comments.
QualType getPreferredType() const
Retrieve the type that this expression would prefer to have, e.g., if the expression is a variable in...
CodeCompletionTUInfo & getCodeCompletionTUInfo()
IntrusiveRefCntPtr< ASTReader > getASTReader() const
bool isMainFileAST() const
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
Code completion occurred where a new name is expected.
Represents a character-granular source range.
DiagnosticsEngine::Level getLevel() const
llvm::StringRef getAsString(SyncScope S)
std::pair< unsigned, unsigned > RemoveRange
unsigned & getCurrentTopLevelHashValue()
Retrieve a reference to the current top-level name hash value.
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror...
const AnnotatedLine * Line
const FunctionProtoType * T
ArrayRef< FixItHint > getFixIts() const
std::vector< StandaloneFixIt > FixIts
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
Defines the clang::Preprocessor interface.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
const NamedDecl * Declaration
When Kind == RK_Declaration or RK_Pattern, the declaration we are referring to.
bool isFileContext() const
comments::CommandTraits & getCommentCommandTraits() const
const SourceManager & getManager() const
DeclContext * getDeclContext()
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Information about a module that has been loaded by the ASTReader.
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
Captures a result of code completion.
Code completion occurred where a new name is expected and a qualified name is permissible.
static unsigned getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier)
Determine the set of code-completion contexts in which this declaration should be shown...
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
std::string FileName
The file name of the module file.
bool BeforePreviousInsertions
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
Divide by this factor when a code-completion result's type exactly matches the type we expect...
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts, llvm::MemoryBuffer *Buffer, unsigned MaxLines)
Runs lexer to compute suggested preamble bounds.
SmallString< 128 > Buffer
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, const LangOptions &LangOpts, const FixItHint &InFix)
top_level_iterator top_level_begin()
std::unique_ptr< CompilerInvocation > createInvocationFromCommandLine(ArrayRef< const char *> Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >(), IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
createInvocationFromCommandLine - Construct a compiler invocation object for a command line argument ...
The result type of a method or function.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
The client can't handle any AST loading failures.
The AST file was missing.
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
unsigned getNumWarnings() const
std::unique_ptr< Sema > takeSema()
static CharSourceRange getCharRange(SourceRange R)
The context in which code completion occurred, so that the code-completion consumer can process the r...
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
unsigned getFileOffset(SourceLocation SpellingLoc) const
Returns the offset from the start of the file that the specified SourceLocation represents.
Abstract interface for external sources of AST nodes.
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...
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
The control block was read successfully.
bool hasPreprocessor() const
Code completion occurred within a class, struct, or union.
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles=None, IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
Reparse the source files using the same command-line options that were originally used to produce thi...
SourceLocation mapLocationFromPreamble(SourceLocation Loc) const
If Loc is a loaded location from the preamble, returns the corresponding local location of the main f...
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
ContinuousRangeMap< unsigned, int, 2 > SLocRemap
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
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...
bool Execute()
Set the source manager's main input file, and run the action.
bool isInMainFileID(SourceLocation Loc) const
Members, declared with object declarations within tag definitions.
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
ASTWriterData(MemoryBufferCache &PCMCache)
llvm::StringMap< unsigned > & getCachedCompletionTypes()
Retrieve the mapping from formatted type names to unique type identifiers.
std::vector< FrontendInputFile > Inputs
The input files and their types.
void CodeComplete(StringRef File, unsigned Line, unsigned Column, ArrayRef< RemappedFile > RemappedFiles, bool IncludeMacros, bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr< PCHContainerOperations > PCHContainerOps, DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, FileManager &FileMgr, SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SmallVectorImpl< const llvm::MemoryBuffer *> &OwnedBuffers)
Perform code completion at the given file, line, and column within this translation unit...
IdentifierInfo * getIdentifierInfo() const
Cached information about one file (either on disk or in the virtual file system). ...
Code completion where the name of an Objective-C class is expected.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Abstract base class to use for AST consumer-based frontend actions.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location...
Code completion occurred within an Objective-C interface, protocol, or category interface.
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates)
Defines the clang::TargetOptions class.
DiagnosticOptions & getDiagnosticOpts() const
static std::pair< unsigned, unsigned > makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
bool isAnyPointerType() const
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
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.
void setListener(std::unique_ptr< ASTReaderListener > Listener)
Set the AST callbacks listener.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
SourceManager & getSourceManager() const
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
llvm::BitstreamWriter Stream
TranslationUnitKind getTranslationUnitKind() const
Determine what kind of translation unit this AST represents.
void setNumWarnings(unsigned NumWarnings)
The AST file was writtten with a different language/target configuration.
bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn)
Iterate over local declarations (locally parsed if this is a parsed source file or the loaded declara...
File is a PCH file treated as the actual main file.
static ASTUnit * LoadFromCompilerInvocationAction(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, FrontendAction *Action=nullptr, ASTUnit *Unit=nullptr, bool Persistent=true, StringRef ResourceFilesPath=StringRef(), bool OnlyLocalDecls=false, bool CaptureDiagnostics=false, unsigned PrecompilePreambleAfterNParses=0, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=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...
Describes a module import declaration, which makes the contents of the named module visible in the cu...
virtual StringRef getFormat() const =0
Equivalent to the format passed to -fmodule-format=.
StringRef getName() const
Return the actual identifier string.
Abstract interface for a consumer of code-completion information.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Options controlling the behavior of code completion.
static ASTUnit::StandaloneDiagnostic makeStandaloneDiagnostic(const LangOptions &LangOpts, const StoredDiagnostic &InDiag)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
Code completion occurred where an macro is being defined.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
bool hasInvocation() const
PreprocessorOptions & getPreprocessorOpts()
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name...
llvm::iterator_range< PreprocessingRecord::iterator > getLocalPreprocessingEntities() const
Returns an iterator range for the local preprocessing entities of the local Preprocessor, if this is a parsed source file, or the loaded preprocessing entities of the primary module if this is an AST file.
Reads an AST files chain containing the contents of a translation unit.
const FullSourceLoc & getLocation() const
Code completion occurred after the "union" keyword, to indicate a union name.
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
std::vector< Decl * >::iterator top_level_iterator
A builder class used to construct new code-completion strings.
Code completion where an Objective-C instance message is expected.
DeclarationName - The name of a declaration.
ASTMutationListener * getASTMutationListener()
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
bool SingleFileParseMode
When enabled, preprocessor is in a mode for parsing a single file only.
Helper class for holding the data necessary to invoke the compiler.
const HeaderSearchOptions & getHeaderSearchOpts() const
Defines the virtual file system interface vfs::FileSystem.
EnumDecl - Represents an enum.
SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const
If Loc points inside a function macro argument, the returned location will be the macro location in w...
top_level_iterator top_level_end()
A map from continuous integer ranges to some value, with a very specialized interface.
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
FrontendOptions - Options for controlling the behavior of the frontend.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
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.
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Code completion occurred where a statement (or declaration) is expected in a function, method, or block.
Code completion occurred on the right-hand side of an Objective-C property access expression...
bool Save(StringRef File)
Save this translation unit to a file with the given name.
cached_completion_iterator cached_completion_begin()
Abstract interface for callback invocations by the ASTReader.
SourceLocation getEndOfPreambleFileID() const
TargetInfo & getTarget() const
CodeCompleteOptions CodeCompleteOpts
unsigned Size
Size of the preamble in bytes.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
This is a convenience method that opens a file, gets its content and then closes the file...
SourceLocation getEnd() const
const ASTContext & getASTContext() const
bool hasASTContext() const
Keeps track of options that affect how file operations are performed.
unsigned DisableFree
Disable memory freeing on exit.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl< char > &Buffer, Sema &S, bool hasErrors, raw_ostream &OS)
enum Kind getKind() const
Retrieve the kind of code-completion context.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Code completion occurred within a preprocessor expression.
Code completion occurred where an expression is expected.
Priority for a code pattern.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
const DiagnosticsEngine & getDiagnostics() const
virtual CodeCompletionAllocator & getAllocator()=0
Retrieve the allocator that will be used to allocate code completion strings.
DiagnosticsEngine & getDiagnostics() const
const SourceManager & getSourceManager() const
An unspecified code-completion context where we should also add macro completions.
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
Level
The level of the diagnostic, after it has been through mapping.
ASTFileSignature WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors=false)
Write a precompiled header for the given semantic analysis.
std::vector< CachedCodeCompletionResult >::iterator cached_completion_iterator
TranslationUnitKind
Describes the kind of translation unit being processed.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Writes an AST file containing the contents of a translation unit.
serialization::DeclID getDeclID(const Decl *D)
Determine the declaration ID of an already-emitted declaration.
bool hadModuleLoaderFatalFailure() const
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Defines the clang::TargetInfo interface.
The AST file is out-of-date relative to its input files, and needs to be regenerated.
A SourceLocation and its associated SourceManager.
The translation unit is a complete translation unit.
SourceLocation getStartOfMainFileID() const
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
The AST file was written by a different version of Clang.
Code completion occurred on the right-hand side of a member access expression using the dot operator...
void clearRemappedFiles()
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion...
Code completion occurred where a type name is expected.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
unsigned IncludeMacros
Show macros in code completion results.
NamedDecl - This represents a decl with a name.
bool isTranslationUnit() const
LangOptions * getLangOpts()
InputKind getInputKind() const
Determine the input kind this AST unit represents.
const FileEntry * File
The file entry for the module file.
const LangOptions & getLangOpts() const
SourceLocation getLocation(const FileEntry *File, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
This class handles loading and caching of source files into memory.
bool(* DeclVisitorFn)(void *context, const Decl *D)
Type for a function iterating over a number of declarations.
SourceLocation getLocation() const
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.