36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringSet.h"
39 #include "llvm/Support/CrashRecoveryContext.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Mutex.h"
43 #include "llvm/Support/MutexGuard.h"
44 #include "llvm/Support/Path.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());
85 std::string PreambleFile;
92 void CleanTemporaryFiles();
95 void CleanPreambleFile();
103 static llvm::sys::SmartMutex<false> M(
true);
109 typedef llvm::DenseMap<
const ASTUnit *,
113 static bool hasRegisteredAtExit =
false;
114 if (!hasRegisteredAtExit) {
115 hasRegisteredAtExit =
true;
138 D = llvm::make_unique<OnDiskData>();
153 I->second->Cleanup();
166 void OnDiskData::CleanTemporaryFiles() {
167 for (StringRef File : TemporaryFiles)
168 llvm::sys::fs::remove(File);
169 TemporaryFiles.clear();
172 void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
174 llvm::sys::fs::remove(PreambleFile);
175 PreambleFile.clear();
179 void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
192 void ASTUnit::clearFileLevelDecls() {
193 llvm::DeleteContainerSeconds(FileDecls);
196 void ASTUnit::CleanTemporaryFiles() {
215 ASTUnit::ASTUnit(
bool _MainFileIsAST)
216 : Reader(nullptr), HadModuleLoaderFatalFailure(
false),
217 OnlyLocalDecls(
false), CaptureDiagnostics(
false),
218 MainFileIsAST(_MainFileIsAST),
219 TUKind(
TU_Complete), WantTiming(getenv(
"LIBCLANG_TIMING")),
220 OwnsRemappedFileBuffers(
true),
221 NumStoredDiagnosticsFromDriver(0),
222 PreambleRebuildCounter(0),
223 NumWarningsInPreamble(0),
224 ShouldCacheCodeCompletionResults(
false),
225 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
226 CompletionCacheTopLevelHashValue(0),
227 PreambleTopLevelHashValue(0),
228 CurrentTopLevelHashValue(0),
229 UnsafeToFree(
false) {
230 if (getenv(
"LIBCLANG_OBJTRACKING"))
234 ASTUnit::~ASTUnit() {
240 clearFileLevelDecls();
249 if (Invocation.get() && OwnsRemappedFileBuffers) {
255 ClearCachedCompletionResults();
257 if (getenv(
"LIBCLANG_OBJTRACKING"))
267 bool &IsNestedNameSpecifier) {
268 IsNestedNameSpecifier =
false;
270 if (isa<UsingShadowDecl>(ND))
276 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
277 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
279 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
288 if (LangOpts.CPlusPlus)
293 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
297 if (isa<ObjCInterfaceDecl>(ND))
301 if (isa<EnumDecl>(ND)) {
305 if (LangOpts.CPlusPlus11)
306 IsNestedNameSpecifier =
true;
307 }
else if (
const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
308 if (Record->isUnion())
313 if (LangOpts.CPlusPlus)
314 IsNestedNameSpecifier =
true;
315 }
else if (isa<ClassTemplateDecl>(ND))
316 IsNestedNameSpecifier =
true;
317 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
323 }
else if (isa<ObjCProtocolDecl>(ND)) {
325 }
else if (isa<ObjCCategoryDecl>(ND)) {
327 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
331 IsNestedNameSpecifier =
true;
337 void ASTUnit::CacheCodeCompletionResults() {
341 SimpleTimer Timer(WantTiming);
342 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
345 ClearCachedCompletionResults();
352 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
356 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
359 for (Result &R : Results) {
361 case Result::RK_Declaration: {
362 bool IsNestedNameSpecifier =
false;
363 CachedCodeCompletionResult CachedResult;
364 CachedResult.Completion = R.CreateCodeCompletionString(
365 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
366 IncludeBriefCommentsInCodeCompletion);
368 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
369 CachedResult.Priority = R.Priority;
370 CachedResult.Kind = R.CursorKind;
371 CachedResult.Availability = R.Availability;
378 CachedResult.Type = 0;
387 unsigned &TypeValue = CompletionTypes[CanUsageType];
388 if (TypeValue == 0) {
389 TypeValue = CompletionTypes.size();
394 CachedResult.Type = TypeValue;
397 CachedCompletionResults.push_back(CachedResult);
400 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
401 !R.StartsNestedNameSpecifier) {
417 if (isa<NamespaceDecl>(R.Declaration) ||
418 isa<NamespaceAliasDecl>(R.Declaration))
421 if (
unsigned RemainingContexts
422 = NNSContexts & ~CachedResult.ShowInContexts) {
426 R.StartsNestedNameSpecifier =
true;
427 CachedResult.Completion = R.CreateCodeCompletionString(
428 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
429 IncludeBriefCommentsInCodeCompletion);
430 CachedResult.ShowInContexts = RemainingContexts;
433 CachedResult.Type = 0;
434 CachedCompletionResults.push_back(CachedResult);
440 case Result::RK_Keyword:
441 case Result::RK_Pattern:
446 case Result::RK_Macro: {
447 CachedCodeCompletionResult CachedResult;
448 CachedResult.Completion = R.CreateCodeCompletionString(
449 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
450 IncludeBriefCommentsInCodeCompletion);
451 CachedResult.ShowInContexts
465 CachedResult.Priority = R.Priority;
466 CachedResult.Kind = R.CursorKind;
467 CachedResult.Availability = R.Availability;
469 CachedResult.Type = 0;
470 CachedCompletionResults.push_back(CachedResult);
477 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
480 void ASTUnit::ClearCachedCompletionResults() {
481 CachedCompletionResults.clear();
482 CachedCompletionTypes.clear();
483 CachedCompletionAllocator =
nullptr;
494 std::shared_ptr<TargetOptions> &TargetOpts;
498 bool InitializedLanguage;
501 std::shared_ptr<TargetOptions> &TargetOpts,
503 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
504 Target(Target), Counter(Counter), InitializedLanguage(
false) {}
506 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
507 bool AllowCompatibleDifferences)
override {
508 if (InitializedLanguage)
512 InitializedLanguage =
true;
518 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
519 bool AllowCompatibleDifferences)
override {
524 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
533 unsigned Value)
override {
539 if (!Target || !InitializedLanguage)
546 Target->adjust(LangOpt);
549 PP.Initialize(*Target);
557 LangOpt.CommentOpts);
567 explicit StoredDiagnosticConsumer(
569 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
574 SourceMgr = &PP->getSourceManager();
583 class CaptureDroppedDiagnostics {
585 StoredDiagnosticConsumer Client;
587 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
592 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
594 if (RequestCapture || Diags.
getClient() ==
nullptr) {
601 ~CaptureDroppedDiagnostics() {
603 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
618 StoredDiags.emplace_back(Level, Info);
623 return &WriterData->Writer;
629 return &WriterData->Writer;
633 std::unique_ptr<llvm::MemoryBuffer>
636 auto Buffer = FileMgr->getBufferForFile(Filename);
638 return std::move(*
Buffer);
640 *ErrorStr =
Buffer.getError().message();
646 ASTUnit &AST,
bool CaptureDiagnostics) {
647 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
648 if (CaptureDiagnostics)
649 Diags->setClient(
new StoredDiagnosticConsumer(AST.StoredDiagnostics));
657 bool CaptureDiagnostics,
bool AllowPCHWithCompilerErrors,
658 bool UserFilesAreVolatile) {
659 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
662 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
663 ASTUnitCleanup(AST.get());
665 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
666 DiagCleanup(Diags.get());
668 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
670 AST->OnlyLocalDecls = OnlyLocalDecls;
671 AST->CaptureDiagnostics = CaptureDiagnostics;
672 AST->Diagnostics = Diags;
674 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
675 AST->UserFilesAreVolatile = UserFilesAreVolatile;
677 AST->getFileManager(),
678 UserFilesAreVolatile);
680 AST->HSOpts->ModuleFormat = PCHContainerRdr.
getFormat();
682 AST->getSourceManager(),
683 AST->getDiagnostics(),
684 AST->ASTFileLangOpts,
698 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
699 AST->getSourceManager(), HeaderInfo, *AST,
704 AST->Ctx =
new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
705 PP.getIdentifierTable(), PP.getSelectorTable(),
706 PP.getBuiltinInfo());
709 bool disableValid =
false;
710 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
712 AST->Reader =
new ASTReader(PP, Context, PCHContainerRdr, { },
715 AllowPCHWithCompilerErrors);
717 AST->Reader->
setListener(llvm::make_unique<ASTInfoCollector>(
718 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
726 Context.setExternalSource(AST->Reader);
739 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
743 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
745 PP.setCounterValue(Counter);
751 AST->TheSema.reset(
new Sema(PP, Context, *AST->Consumer));
752 AST->TheSema->Initialize();
753 AST->Reader->InitializeSema(*AST->TheSema);
756 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
765 class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
769 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) { }
771 void MacroDefined(
const Token &MacroNameTok,
778 void AddTopLevelDeclarationToHash(
Decl *D,
unsigned &Hash) {
789 if (
NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
790 if (
EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
793 if (!EnumD->isScoped()) {
794 for (
const auto *EI : EnumD->enumerators()) {
795 if (EI->getIdentifier())
796 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
801 if (ND->getIdentifier())
802 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
804 std::string NameStr =
Name.getAsString();
805 Hash = llvm::HashString(NameStr, Hash);
810 if (
ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
811 if (
Module *Mod = ImportD->getImportedModule()) {
812 std::string ModName = Mod->getFullModuleName();
813 Hash = llvm::HashString(ModName, Hash);
819 class TopLevelDeclTrackerConsumer :
public ASTConsumer {
824 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
825 : Unit(_Unit), Hash(Hash) {
829 void handleTopLevelDecl(
Decl *D) {
837 if (isa<ObjCMethodDecl>(D))
840 AddTopLevelDeclarationToHash(D, Hash);
841 Unit.addTopLevelDecl(D);
843 handleFileLevelDecl(D);
846 void handleFileLevelDecl(
Decl *D) {
847 Unit.addFileLevelDecl(D);
849 for (
auto *
I : NSD->decls())
850 handleFileLevelDecl(
I);
855 for (
Decl *TopLevelDecl : D)
856 handleTopLevelDecl(TopLevelDecl);
863 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
864 for (
Decl *TopLevelDecl : D)
865 handleTopLevelDecl(TopLevelDecl);
869 return Unit.getASTMutationListener();
873 return Unit.getDeserializationListener();
882 StringRef InFile)
override {
884 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
885 Unit.getCurrentTopLevelHashValue()));
886 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
887 Unit, Unit.getCurrentTopLevelHashValue());
891 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
893 bool hasCodeCompletionSupport()
const override {
return false; }
895 return Unit.getTranslationUnitKind();
901 bool HasEmittedPreamblePCH;
904 explicit PrecompilePreambleAction(
ASTUnit &Unit)
905 : Unit(Unit), HasEmittedPreamblePCH(
false) {}
908 StringRef InFile)
override;
909 bool hasEmittedPreamblePCH()
const {
return HasEmittedPreamblePCH; }
910 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH =
true; }
911 bool shouldEraseOutputFiles()
override {
return !hasEmittedPreamblePCH(); }
913 bool hasCodeCompletionSupport()
const override {
return false; }
914 bool hasASTFileSupport()
const override {
return false; }
918 class PrecompilePreambleConsumer :
public PCHGenerator {
921 std::vector<Decl *> TopLevelDecls;
922 PrecompilePreambleAction *
Action;
923 std::unique_ptr<raw_ostream> Out;
926 PrecompilePreambleConsumer(
ASTUnit &Unit, PrecompilePreambleAction *
Action,
928 std::unique_ptr<raw_ostream> Out)
932 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
933 Out(std::move(Out)) {
943 if (isa<ObjCMethodDecl>(D))
945 AddTopLevelDeclarationToHash(D, Hash);
946 TopLevelDecls.push_back(D);
951 void HandleTranslationUnit(
ASTContext &Ctx)
override {
953 if (hasEmittedPCH()) {
960 getPCH() = std::move(Empty);
966 for (
Decl *D : TopLevelDecls) {
968 if (D->isInvalidDecl())
970 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
973 Action->setHasEmittedPreamblePCH();
980 std::unique_ptr<ASTConsumer>
984 std::string OutputFile;
985 std::unique_ptr<raw_ostream> OS =
995 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
996 Unit.getCurrentTopLevelHashValue()));
997 return llvm::make_unique<PrecompilePreambleConsumer>(
1010 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1023 if (SD.getLocation().isValid()) {
1025 SD.setLocation(Loc);
1035 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1036 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1037 SavedMainFileBuffer.reset();
1043 std::unique_ptr<CompilerInstance> Clang(
1047 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1048 CICleanup(Clang.get());
1053 Clang->setInvocation(CCInvocation.get());
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() !=
IK_AST &&
1075 "FIXME: AST inputs not yet supported here!");
1076 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1077 "IR inputs not support here!");
1080 LangOpts = Clang->getInvocation().LangOpts;
1081 FileSystemOpts = Clang->getFileSystemOpts();
1083 Clang->createFileManager();
1084 FileMgr = &Clang->getFileManager();
1087 UserFilesAreVolatile);
1094 TopLevelDecls.clear();
1095 clearFileLevelDecls();
1096 CleanTemporaryFiles();
1098 if (!OverrideMainBuffer) {
1100 TopLevelDeclsInPreamble.clear();
1112 if (OverrideMainBuffer) {
1114 OverrideMainBuffer.get());
1117 = PreambleEndsAtStartOfLine;
1129 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1132 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1133 new TopLevelDeclTrackerAction(*
this));
1136 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1137 ActCleanup(Act.get());
1139 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1142 if (SavedMainFileBuffer)
1144 PreambleDiagnostics, StoredDiagnostics);
1146 if (!Act->Execute())
1149 transferASTDataFromCompilerInstance(*Clang);
1151 Act->EndSourceFile();
1153 FailedParseDiagnostics.clear();
1159 SavedMainFileBuffer =
nullptr;
1163 transferASTDataFromCompilerInstance(*Clang);
1164 FailedParseDiagnostics.swap(StoredDiagnostics);
1165 StoredDiagnostics.clear();
1166 NumStoredDiagnosticsFromDriver = 0;
1175 const char *TmpFile = ::getenv(
"CINDEXTEST_PREAMBLE_FILE");
1180 llvm::sys::fs::createTemporaryFile(
"preamble",
"pch", Path);
1188 ASTUnit::ComputedPreamble
1196 llvm::MemoryBuffer *
Buffer =
nullptr;
1197 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1198 std::string MainFilePath(FrontendOpts.
Inputs[0].getFile());
1199 llvm::sys::fs::UniqueID MainFileID;
1200 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1203 std::string MPath(RF.first);
1204 llvm::sys::fs::UniqueID MID;
1205 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1206 if (MainFileID == MID) {
1210 return ComputedPreamble(
nullptr,
nullptr, 0,
true);
1218 std::string MPath(RB.first);
1219 llvm::sys::fs::UniqueID MID;
1220 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1221 if (MainFileID == MID) {
1223 BufferOwner.reset();
1224 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
1231 if (!Buffer && !BufferOwner) {
1234 return ComputedPreamble(
nullptr,
nullptr, 0,
true);
1238 Buffer = BufferOwner.get();
1241 return ComputedPreamble(Buffer, std::move(BufferOwner),
Pre.first,
1250 memset(Result.
MD5, 0,
sizeof(Result.
MD5));
1255 const llvm::MemoryBuffer *Buffer) {
1257 Result.
Size = Buffer->getBufferSize();
1261 MD5Ctx.update(Buffer->getBuffer().data());
1262 MD5Ctx.final(Result.
MD5);
1271 memcmp(LHS.
MD5, RHS.
MD5,
sizeof(LHS.
MD5)) == 0;
1275 static std::pair<unsigned, unsigned>
1281 return std::make_pair(Offset, EndOffset);
1340 std::unique_ptr<llvm::MemoryBuffer>
1341 ASTUnit::getMainBufferWithPrecompiledPreamble(
1342 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1344 unsigned MaxLines) {
1348 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1350 = PreambleInvocation->getPreprocessorOpts();
1352 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1354 if (!NewPreamble.Size) {
1361 PreambleRebuildCounter = 1;
1365 if (!Preamble.
empty()) {
1370 if (Preamble.
size() == NewPreamble.Size &&
1371 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1372 memcmp(Preamble.
getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1373 NewPreamble.Size) == 0) {
1378 bool AnyFileChanged =
false;
1382 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1388 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1391 AnyFileChanged =
true;
1404 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1405 AnyFileChanged =
true;
1415 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1416 !AnyFileChanged && F != FEnd;
1419 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1421 AnyFileChanged =
true;
1427 if (Overridden != OverriddenFiles.end()) {
1430 if (Overridden->second != F->second)
1431 AnyFileChanged =
true;
1436 if (Status.
getSize() != uint64_t(F->second.Size) ||
1438 uint64_t(F->second.ModTime))
1439 AnyFileChanged =
true;
1442 if (!AnyFileChanged) {
1449 PreambleInvocation->getDiagnosticOpts());
1452 return llvm::MemoryBuffer::getMemBufferCopy(
1453 NewPreamble.Buffer->getBuffer(), FrontendOpts.
Inputs[0].getFile());
1464 PreambleDiagnostics.clear();
1466 PreambleRebuildCounter = 1;
1467 }
else if (!AllowRebuild) {
1476 if (PreambleRebuildCounter > 1) {
1477 --PreambleRebuildCounter;
1484 if (PreamblePCHPath.empty()) {
1486 PreambleRebuildCounter = 1;
1491 SimpleTimer PreambleTimer(WantTiming);
1492 PreambleTimer.setOutput(
"Precompiling preamble");
1496 StringRef MainFilename = FrontendOpts.
Inputs[0].getFile();
1497 Preamble.
assign(FileMgr->getFile(MainFilename),
1498 NewPreamble.Buffer->getBufferStart(),
1499 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1500 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1502 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1503 NewPreamble.Buffer->getBuffer().slice(0, Preamble.
size()), MainFilename);
1506 StringRef MainFilePath = FrontendOpts.
Inputs[0].getFile();
1517 std::unique_ptr<CompilerInstance> Clang(
1521 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1522 CICleanup(Clang.get());
1524 Clang->setInvocation(&*PreambleInvocation);
1525 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1532 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1533 if (!Clang->hasTarget()) {
1534 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1545 Clang->getTarget().adjust(Clang->getLangOpts());
1547 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1548 "Invocation must have exactly one source file!");
1549 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1550 "FIXME: AST inputs not yet supported here!");
1551 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1552 "IR inputs not support here!");
1558 TopLevelDecls.clear();
1559 TopLevelDeclsInPreamble.clear();
1560 PreambleDiagnostics.clear();
1568 Clang->setFileManager(
new FileManager(Clang->getFileSystemOpts(), VFS));
1572 Clang->getFileManager()));
1574 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1575 Clang->addDependencyCollector(PreambleDepCollector);
1577 std::unique_ptr<PrecompilePreambleAction> Act;
1578 Act.reset(
new PrecompilePreambleAction(*
this));
1579 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1580 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1594 PreambleDiagnostics.push_back(
1597 Act->EndSourceFile();
1601 if (!Act->hasEmittedPreamblePCH()) {
1605 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1607 TopLevelDeclsInPreamble.clear();
1619 FilesInPreamble.clear();
1621 for (
auto &
Filename : PreambleDepCollector->getDependencies()) {
1630 FilesInPreamble[File->
getName()] =
1635 PreambleRebuildCounter = 1;
1641 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1642 CompletionCacheTopLevelHashValue = 0;
1643 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1646 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1650 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1651 std::vector<Decl *> Resolved;
1652 Resolved.reserve(TopLevelDeclsInPreamble.size());
1658 Resolved.push_back(D);
1660 TopLevelDeclsInPreamble.clear();
1661 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1689 return Input.
getBuffer()->getBufferIdentifier();
1695 return FE->getName();
1706 Mod = Reader->getModuleManager().getPrimaryModule();
1712 bool CaptureDiagnostics,
1713 bool UserFilesAreVolatile) {
1714 std::unique_ptr<ASTUnit> AST;
1715 AST.reset(
new ASTUnit(
false));
1716 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1717 AST->Diagnostics = Diags;
1718 AST->Invocation = CI;
1724 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1725 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1726 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1727 UserFilesAreVolatile);
1729 return AST.release();
1734 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1736 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1737 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1738 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1739 bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile,
1740 std::unique_ptr<ASTUnit> *ErrAST) {
1741 assert(CI &&
"A CompilerInvocation is required");
1743 std::unique_ptr<ASTUnit> OwnAST;
1747 OwnAST.reset(
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1753 if (!ResourceFilesPath.empty()) {
1757 AST->OnlyLocalDecls = OnlyLocalDecls;
1758 AST->CaptureDiagnostics = CaptureDiagnostics;
1759 if (PrecompilePreambleAfterNParses > 0)
1760 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1762 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1763 AST->IncludeBriefCommentsInCodeCompletion
1764 = IncludeBriefCommentsInCodeCompletion;
1767 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1768 ASTUnitCleanup(OwnAST.get());
1770 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1771 DiagCleanup(Diags.get());
1779 std::unique_ptr<CompilerInstance> Clang(
1783 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1784 CICleanup(Clang.get());
1786 Clang->setInvocation(CI);
1787 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1795 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1796 if (!Clang->hasTarget())
1803 Clang->getTarget().adjust(Clang->getLangOpts());
1805 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1806 "Invocation must have exactly one source file!");
1807 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1808 "FIXME: AST inputs not yet supported here!");
1809 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1810 "IR inputs not supported here!");
1813 AST->TheSema.reset();
1816 AST->Reader =
nullptr;
1826 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1828 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1829 Act = TrackerAct.get();
1833 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1834 ActCleanup(TrackerAct.get());
1836 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1837 AST->transferASTDataFromCompilerInstance(*Clang);
1838 if (OwnAST && ErrAST)
1839 ErrAST->swap(OwnAST);
1844 if (Persistent && !TrackerAct) {
1845 Clang->getPreprocessor().addPPCallbacks(
1846 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1848 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1849 if (Clang->hasASTConsumer())
1850 Consumers.push_back(Clang->takeASTConsumer());
1851 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1853 Clang->setASTConsumer(
1854 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1857 AST->transferASTDataFromCompilerInstance(*Clang);
1858 if (OwnAST && ErrAST)
1859 ErrAST->swap(OwnAST);
1865 AST->transferASTDataFromCompilerInstance(*Clang);
1870 return OwnAST.release();
1875 bool ASTUnit::LoadFromCompilerInvocation(
1876 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1877 unsigned PrecompilePreambleAfterNParses) {
1886 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1887 if (PrecompilePreambleAfterNParses > 0) {
1888 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1889 OverrideMainBuffer =
1890 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1893 SimpleTimer ParsingTimer(WantTiming);
1897 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1898 MemBufferCleanup(OverrideMainBuffer.get());
1900 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
1903 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1905 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1907 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1909 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1910 bool UserFilesAreVolatile) {
1912 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1913 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1914 AST->Diagnostics = Diags;
1915 AST->OnlyLocalDecls = OnlyLocalDecls;
1916 AST->CaptureDiagnostics = CaptureDiagnostics;
1917 AST->TUKind = TUKind;
1918 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1919 AST->IncludeBriefCommentsInCodeCompletion
1920 = IncludeBriefCommentsInCodeCompletion;
1921 AST->Invocation = CI;
1923 AST->FileMgr = FileMgr;
1924 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1927 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1928 ASTUnitCleanup(AST.get());
1930 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1931 DiagCleanup(Diags.get());
1933 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1934 PrecompilePreambleAfterNParses))
1940 const char **ArgBegin,
const char **ArgEnd,
1941 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1943 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1946 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1947 bool AllowPCHWithCompilerErrors,
bool SkipFunctionBodies,
1948 bool UserFilesAreVolatile,
bool ForSerialization,
1950 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1958 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1962 llvm::makeArrayRef(ArgBegin, ArgEnd),
1970 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1978 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1980 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1983 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1986 std::unique_ptr<ASTUnit> AST;
1987 AST.reset(
new ASTUnit(
false));
1988 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1989 AST->Diagnostics = Diags;
1990 AST->FileSystemOpts = CI->getFileSystemOpts();
1995 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1996 AST->OnlyLocalDecls = OnlyLocalDecls;
1997 AST->CaptureDiagnostics = CaptureDiagnostics;
1998 AST->TUKind = TUKind;
1999 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2000 AST->IncludeBriefCommentsInCodeCompletion
2001 = IncludeBriefCommentsInCodeCompletion;
2002 AST->UserFilesAreVolatile = UserFilesAreVolatile;
2003 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2004 AST->StoredDiagnostics.swap(StoredDiagnostics);
2005 AST->Invocation = CI;
2006 if (ForSerialization)
2013 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2014 ASTUnitCleanup(AST.get());
2016 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2017 PrecompilePreambleAfterNParses)) {
2021 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2027 return AST.release();
2035 clearFileLevelDecls();
2037 SimpleTimer ParsingTimer(WantTiming);
2053 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2055 OverrideMainBuffer =
2056 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2062 if (OverrideMainBuffer)
2067 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
2071 if (!Result && ShouldCacheCodeCompletionResults &&
2072 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2073 CacheCodeCompletionResults();
2091 uint64_t NormalContexts;
2099 AST(AST), Next(Next)
2126 unsigned NumResults)
override;
2128 void ProcessOverloadCandidates(
Sema &
S,
unsigned CurrentArg,
2130 unsigned NumCandidates)
override {
2148 unsigned NumResults,
2150 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2151 bool OnlyTagNames =
false;
2176 OnlyTagNames =
true;
2198 for (
unsigned I = 0;
I != NumResults; ++
I) {
2199 if (Results[
I].
Kind != Result::RK_Declaration)
2205 bool Hiding =
false;
2207 Hiding = (IDNS & Decl::IDNS_Tag);
2209 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2210 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2211 Decl::IDNS_NonMemberOperator);
2213 HiddenIDNS |= Decl::IDNS_Tag;
2214 Hiding = (IDNS & HiddenIDNS);
2222 HiddenNames.insert(Identifier->getName());
2228 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2231 unsigned NumResults) {
2233 bool AddedResult =
false;
2234 uint64_t InContexts =
2236 ? NormalContexts : (1LL << Context.
getKind());
2238 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2247 if ((
C->ShowInContexts & InContexts) == 0)
2254 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2261 HiddenNames.count(
C->Completion->getTypedText()))
2265 unsigned Priority =
C->Priority;
2272 }
else if (
C->Type) {
2277 if (ExpectedSTC ==
C->TypeClass) {
2279 llvm::StringMap<unsigned> &CachedCompletionTypes
2282 = CachedCompletionTypes.find(
QualType(Expected).getAsString());
2283 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2298 Builder.AddTypedTextChunk(
C->Completion->getTypedText());
2300 Completion =
Builder.TakeString();
2303 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2319 StringRef File,
unsigned Line,
unsigned Column,
2321 bool IncludeCodePatterns,
bool IncludeBriefComments,
2323 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2330 SimpleTimer CompletionTimer(WantTiming);
2331 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2332 Twine(Line) +
":" + Twine(Column));
2342 CachedCompletionResults.empty();
2344 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2347 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2354 LangOpts = *CCInvocation->getLangOpts();
2357 LangOpts.SpellChecking =
false;
2358 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2360 std::unique_ptr<CompilerInstance> Clang(
2364 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2365 CICleanup(Clang.get());
2367 Clang->setInvocation(&*CCInvocation);
2368 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2371 Clang->setDiagnostics(&Diag);
2372 CaptureDroppedDiagnostics Capture(
true,
2373 Clang->getDiagnostics(),
2379 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2380 if (!Clang->hasTarget()) {
2381 Clang->setInvocation(
nullptr);
2389 Clang->getTarget().adjust(Clang->getLangOpts());
2391 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2392 "Invocation must have exactly one source file!");
2393 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
2394 "FIXME: AST inputs not yet supported here!");
2395 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
2396 "IR inputs not support here!");
2400 Clang->setFileManager(&FileMgr);
2401 Clang->setSourceManager(&SourceMgr);
2413 AugmentedCodeCompleteConsumer *AugmentedConsumer
2414 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2415 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2421 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2423 std::string CompleteFilePath(File);
2424 llvm::sys::fs::UniqueID CompleteFileID;
2426 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2427 std::string MainPath(OriginalSourceFile);
2428 llvm::sys::fs::UniqueID MainID;
2429 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2430 if (CompleteFileID == MainID && Line > 1)
2431 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2432 PCHContainerOps, *CCInvocation,
false, Line - 1);
2439 if (OverrideMainBuffer) {
2441 OverrideMainBuffer.get());
2444 = PreambleEndsAtStartOfLine;
2448 OwnedBuffers.push_back(OverrideMainBuffer.release());
2455 if (!Clang->getLangOpts().Modules)
2458 std::unique_ptr<SyntaxOnlyAction> Act;
2460 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2462 Act->EndSourceFile();
2467 if (HadModuleLoaderFatalFailure)
2474 TempPath +=
"-%%%%%%%%";
2476 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2481 llvm::raw_fd_ostream Out(fd,
true);
2485 if (Out.has_error()) {
2490 if (llvm::sys::fs::rename(TempPath, File)) {
2491 llvm::sys::fs::remove(TempPath);
2503 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2506 if (!Buffer.empty())
2507 OS.write(Buffer.data(), Buffer.size());
2517 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2521 llvm::BitstreamWriter Stream(Buffer);
2528 void ASTUnit::TranslateStoredDiagnostics(
2539 Result.reserve(Diags.size());
2540 for (
const StandaloneDiagnostic &SD : Diags) {
2542 if (SD.Filename.empty())
2555 Ranges.reserve(SD.Ranges.size());
2556 for (
const auto &Range : SD.Ranges) {
2563 FixIts.reserve(SD.FixIts.size());
2564 for (
const StandaloneFixIt &
FixIt : SD.FixIts) {
2574 SD.Message, Loc, Ranges, FixIts));
2583 if (D->isFromASTFile())
2592 if (!D->getLexicalDeclContext()->isFileContext())
2600 if (FID.isInvalid())
2607 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2609 if (Decls->empty() || Decls->back().first <=
Offset) {
2610 Decls->push_back(LocDecl);
2615 LocDecl, llvm::less_first());
2617 Decls->insert(I, LocDecl);
2632 if (I == FileDecls.end())
2636 if (LocDecls.empty())
2640 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2641 std::make_pair(Offset, (
Decl *)
nullptr),
2642 llvm::less_first());
2643 if (BeginIt != LocDecls.begin())
2649 while (BeginIt != LocDecls.begin() &&
2650 BeginIt->second->isTopLevelDeclInObjCContainer())
2654 LocDecls.begin(), LocDecls.end(),
2655 std::make_pair(Offset + Length, (
Decl *)
nullptr), llvm::less_first());
2656 if (EndIt != LocDecls.end())
2660 Decls.push_back(DIt->second);
2664 unsigned Line,
unsigned Col)
const {
2689 if (SourceMgr->
isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.
size()) {
2711 Offs < Preamble.
size()) {
2763 llvm::iterator_range<PreprocessingRecord::iterator>
2767 Mod = Reader->getModuleManager().getPrimaryModule();
2768 return Reader->getModulePreprocessedEntities(Mod);
2772 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2781 Mod = Reader->getModuleManager().getPrimaryModule();
2782 for (
const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2783 if (!Fn(context, D))
2792 TL != TLEnd; ++TL) {
2793 if (!Fn(context, *TL))
2831 void ASTUnit::PreambleData::countLines()
const {
2836 NumLines = std::count(Buffer.begin(), Buffer.end(),
'\n');
2838 if (Buffer.back() !=
'\n')
2843 ASTUnit::ConcurrencyState::ConcurrencyState() {
2844 Mutex =
new llvm::sys::MutexImpl(
true);
2847 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2848 delete static_cast<llvm::sys::MutexImpl *
>(Mutex);
2851 void ASTUnit::ConcurrencyState::start() {
2852 bool acquired =
static_cast<llvm::sys::MutexImpl *
>(Mutex)->tryacquire();
2853 assert(acquired &&
"Concurrent access to ASTUnit!");
2856 void ASTUnit::ConcurrencyState::finish() {
2857 static_cast<llvm::sys::MutexImpl *
>(Mutex)->release();
2862 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2863 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2864 void ASTUnit::ConcurrencyState::start() {}
2865 void ASTUnit::ConcurrencyState::finish() {}
HeaderSearchOptions & getHeaderSearchOpts()
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
std::string OutputFile
The output file, if any.
stored_diag_iterator stored_diag_afterDriver_begin()
Defines the clang::ASTContext interface.
ASTContext & getASTContext() const
StringRef getMainFileName() const
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.
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()
unsigned getNumWarnings() const
bool isInMainFileID(SourceLocation Loc)
DiagnosticConsumer * getClient()
A (possibly-)qualified type.
virtual Decl * GetExternalDecl(uint32_t ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
SourceLocation getBegin() const
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...
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
std::pair< unsigned, unsigned > InsertFromRange
static std::pair< unsigned, bool > ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
bool operator==(CanQual< T > x, CanQual< U > y)
Divide by this factor when a code-completion result's type exactly matches the type we expect...
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...
const LangOptions & getLangOpts() const
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.
const DiagnosticsEngine & getDiagnostics() const
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.
StringRef getMessage() const
Abstract base class for actions which can be performed by the frontend.
SourceLocation getEndOfPreambleFileID()
ModuleKind Kind
The type of this module.
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...
The translation unit is a prefix to a translation unit, and is not complete.
static const std::string & getPreambleFile(const ASTUnit *AU)
const SourceManager & getManager() const
std::string getAsString() const
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
const FullSourceLoc & getLocation() const
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
std::unique_ptr< llvm::MemoryBuffer > Buffer
An unspecified code-completion context.
static std::unique_ptr< raw_pwrite_stream > ComputeASTConsumerArguments(CompilerInstance &CI, StringRef InFile, std::string &Sysroot, std::string &OutputFile)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
NamespaceDecl - Represent a C++ namespace.
Allocator for a cached set of global code completions.
bool hasInvocation() const
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
llvm::sys::TimeValue getLastModificationTime() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Code completion occurred where an Objective-C message receiver is expected.
void assign(const FileEntry *F, const char *begin, const char *end)
static OnDiskDataMap & getOnDiskDataMap()
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.
TargetInfo & getTarget() const
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
bool(* DeclVisitorFn)(void *context, const Decl *D)
Type for a function iterating over a number of declarations.
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
Data used to determine if a file used in the preamble has been changed.
Options for controlling the target.
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.
bool isModuleFile()
Returns true if the ASTUnit was constructed from a serialized module file.
static void checkAndSanitizeDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SourceManager &SM)
Code completion occurred within the instance variable list of an Objective-C interface, implementation, or category implementation.
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 PreambleFileHash createForMemoryBuffer(const llvm::MemoryBuffer *Buffer)
static ASTUnit * create(CompilerInvocation *CI, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, bool CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
std::vector< std::pair< unsigned, unsigned > > Ranges
RecordDecl - Represents a struct/union/class.
One of these records is kept for each identifier that is lexed.
comments::CommandTraits & getCommentCommandTraits() const
cached_completion_iterator cached_completion_end()
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
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.
void HandleTranslationUnit(ASTContext &Ctx) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
bool isAnyPointerType() const
static std::atomic< unsigned > ActiveASTUnitObjects
Tracks the number of ASTUnit objects that are currently active.
bool isTranslationUnit() const
Token - This structure provides full information about a lexed token.
unsigned DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::unique_ptr< llvm::MemoryBuffer > getBufferForFile(StringRef Filename, std::string *ErrorStr=nullptr)
static ASTUnit * LoadFromCompilerInvocationAction(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...
bool BeforePreviousInsertions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
Describes a module or submodule.
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
const SourceManager & getSourceManager() const
virtual 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.
unsigned IncludeCodePatterns
Show code patterns in code completion results.
An allocator used specifically for the purpose of code completion.
DiagnosticsEngine::Level Level
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
const LangOptions & getLangOpts() const
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
FrontendOptions & getFrontendOpts()
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.
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location...
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
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...
Priority for a nested-name-specifier.
Code completion occurred where a namespace or namespace alias is expected.
ASTDeserializationListener * getDeserializationListener()
The result of a status operation.
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag)
void Reset()
Reset the state of the diagnostic object to its initial configuration.
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
The AST file itself appears corrupted.
detail::InMemoryDirectory::const_iterator I
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
QualType getPreferredType() const
Retrieve the type that this expression would prefer to have, e.g., if the expression is a variable in...
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()
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...
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
SourceLocation getLocForEndOfFile(FileID FID) const
Return the source location corresponding to the last byte of the specified file.
void setPreprocessor(Preprocessor *pp)
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
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...
const FileManager & getFileManager() const
Code completion occurred where a protocol name is expected.
SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const
If Loc points inside a function macro argument, the returned location will be the macro location in w...
bool hadModuleLoaderFatalFailure() const
Allows QualTypes to be sorted and hence used in maps and sets.
static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile)
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.
CodeCompletionTUInfo & getCodeCompletionTUInfo()
StringRef getName() const
Return the actual identifier string.
Code completion occurred where a new name is expected.
Represents a character-granular source range.
std::pair< unsigned, unsigned > RemoveRange
off_t Size
All files have size set.
SourceLocation getEnd() const
unsigned & getCurrentTopLevelHashValue()
Retrieve a reference to the current top-level name hash value.
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 UserFilesAreVolatile=false, bool ForSerialization=false, llvm::Optional< StringRef > ModuleFormat=llvm::None, std::unique_ptr< ASTUnit > *ErrAST=nullptr)
LoadFromCommandLine - Create an ASTUnit from a vector of command line arguments, which must specify e...
llvm::sys::fs::UniqueID getUniqueID() const
static void erasePreambleFile(const ASTUnit *AU)
virtual void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults)
Process the finalized code-completion results.
std::vector< StandaloneFixIt > FixIts
Defines the clang::Preprocessor interface.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
static PreambleFileHash createForFile(off_t Size, time_t ModTime)
const NamedDecl * Declaration
When Kind == RK_Declaration or RK_Pattern, the declaration we are referring to.
FileID getPreambleFileID() const
Get the file ID for the precompiled preamble if there is one.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
stored_diag_const_iterator stored_diag_end() const
Information about a module that has been loaded by the ASTReader.
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...
static std::string GetPreamblePCHPath()
Simple function to retrieve a path for a preamble precompiled header.
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
static llvm::sys::SmartMutex< false > & getOnDiskMutex()
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
SmallString< 128 > Buffer
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, const LangOptions &LangOpts, const FixItHint &InFix)
top_level_iterator top_level_begin()
The result type of a method or function.
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.
std::unique_ptr< Sema > takeSema()
static OnDiskData & getOnDiskData(const ASTUnit *AU)
Priority for a code pattern.
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.
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...
ArrayRef< FixItHint > getFixIts() const
The control block was read successfully.
Code completion occurred within a class, struct, or union.
static void cleanupOnDiskMapAtExit()
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
File is a PCH file treated as the preamble.
ContinuousRangeMap< unsigned, int, 2 > SLocRemap
const char * getName() const
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...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
bool Execute()
Set the source manager's main input file, and run the action.
const TemplateArgument * iterator
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
File is a PCH file treated as such.
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.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool isValid() const
Return true if this is a valid SourceLocation object.
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.
File is an implicitly-loaded module.
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.
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.
llvm::MemoryBuffer * getMemoryBufferForFile(const FileEntry *File, bool *Invalid=nullptr)
Retrieve the memory buffer associated with the given file.
static std::pair< unsigned, unsigned > makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
llvm::DenseMap< const ASTUnit *, std::unique_ptr< OnDiskData > > OnDiskDataMap
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.
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
llvm::BitstreamWriter Stream
FileID getMainFileID() const
Returns the FileID of the main source file.
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...
StoredDiagnostic * stored_diag_iterator
const ASTContext & getASTContext() const
File is a PCH file treated as the actual main file.
bool isInPreambleFileID(SourceLocation Loc)
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
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=.
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)
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles=None)
Reparse the source files using the same command-line options that were originally used to produce thi...
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 hasSourceManager() const
PreprocessorOptions & getPreprocessorOpts()
frontend::ActionKind ProgramAction
The frontend action to perform.
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...
Reads an AST files chain containing the contents of a translation unit.
File is an explicitly-loaded module.
CompilerInvocation * createInvocationFromCommandLine(ArrayRef< const char * > Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >())
createInvocationFromCommandLine - Construct a compiler invocation object for a command line argument ...
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()
Helper class for holding the data necessary to invoke the compiler.
DiagnosticOptions & getDiagnosticOpts() const
Defines the virtual file system interface vfs::FileSystem.
llvm::MD5::MD5Result MD5
Memory buffers have MD5 instead of modification time.
EnumDecl - Represents an enum.
detail::InMemoryDirectory::const_iterator E
void addTemporaryFile(StringRef TempFile)
Add a temporary file that the ASTUnit depends on.
top_level_iterator top_level_end()
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
A map from continuous integer ranges to some value, with a very specialized interface.
FrontendOptions - Options for controlling the behavior of the frontend.
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
Code completion occurred where a statement (or declaration) is expected in a function, method, or block.
bool isMainFileAST() const
SourceLocation getStartOfMainFileID()
Code completion occurred on the right-hand side of an Objective-C property access expression...
SmallVector< Context, 8 > Contexts
Defines the Diagnostic-related interfaces.
SourceLocation mapLocationFromPreamble(SourceLocation Loc)
If Loc is a loaded location from the preamble, returns the corresponding local location of the main f...
bool Save(StringRef File)
Save this translation unit to a file with the given name.
cached_completion_iterator cached_completion_begin()
time_t getModificationTime() const
Abstract interface for callback invocations by the ASTReader.
time_t ModTime
Modification time is set for files that are on disk.
SourceManager & getSourceManager() const
enum Kind getKind() const
Retrieve the kind of code-completion context.
CodeCompleteOptions CodeCompleteOpts
bool hasASTContext() const
ArrayRef< CharSourceRange > getRanges() const
Keeps track of options that affect how file operations are performed.
unsigned DisableFree
Disable memory freeing on exit.
Generate pre-compiled header.
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl< char > &Buffer, Sema &S, bool hasErrors, raw_ostream &OS)
Code completion occurred within a preprocessor expression.
Code completion occurred where an expression is expected.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
BoundNodesTreeBuilder *const Builder
virtual CodeCompletionAllocator & getAllocator()=0
Retrieve the allocator that will be used to allocate code completion strings.
SourceLocation getLocation(const FileEntry *File, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
An unspecified code-completion context where we should also add macro completions.
Level
The level of the diagnostic, after it has been through mapping.
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.
FileSystemOptions & getFileSystemOpts()
std::vector< std::pair< std::string, std::string > > RemappedFiles
The set of file remappings, which take existing files on the system (the first part of each pair) and...
Writes an AST file containing the contents of a translation unit.
DiagnosticsEngine::Level getLevel() 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...
uint64_t WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors=false)
Write a precompiled header for the given semantic analysis.
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 mapLocationToPreamble(SourceLocation Loc)
If Loc is a local location of the main file but inside the preamble chunk, returns the corresponding ...
bool hasPreprocessor() const
const char * getBufferStart() 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.
An abstract superclass that describes a custom extension to the module/precompiled header file format...
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...
AST and semantic-analysis consumer that generates a precompiled header from the parsed source code...
Code completion occurred where a type name is expected.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
unsigned getFileOffset(SourceLocation SpellingLoc) const
Returns the offset from the start of the file that the specified SourceLocation represents.
unsigned IncludeMacros
Show macros in code completion results.
NamedDecl - This represents a decl with a name.
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...
LangOptions * getLangOpts()
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror...
static std::unique_ptr< ASTUnit > LoadFromASTFile(const std::string &Filename, const PCHContainerReader &PCHContainerRdr, 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.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
This class handles loading and caching of source files into memory.
static void removeOnDiskEntry(const ASTUnit *AU)
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo() const