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) {}
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;
926 PrecompilePreambleConsumer(
ASTUnit &Unit, PrecompilePreambleAction *
Action,
932 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
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;
986 CI, InFile, Sysroot, OutputFile);
994 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
995 Unit.getCurrentTopLevelHashValue()));
996 return llvm::make_unique<PrecompilePreambleConsumer>(
1009 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1022 if (SD.getLocation().isValid()) {
1024 SD.setLocation(Loc);
1034 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1035 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1036 SavedMainFileBuffer.reset();
1042 std::unique_ptr<CompilerInstance> Clang(
1046 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1047 CICleanup(Clang.get());
1052 Clang->setInvocation(CCInvocation.get());
1053 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1061 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1062 if (!Clang->hasTarget())
1069 Clang->getTarget().adjust(Clang->getLangOpts());
1071 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1072 "Invocation must have exactly one source file!");
1073 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1074 "FIXME: AST inputs not yet supported here!");
1075 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1076 "IR inputs not support here!");
1079 LangOpts = Clang->getInvocation().LangOpts;
1080 FileSystemOpts = Clang->getFileSystemOpts();
1082 Clang->createFileManager();
1083 FileMgr = &Clang->getFileManager();
1086 UserFilesAreVolatile);
1093 TopLevelDecls.clear();
1094 clearFileLevelDecls();
1095 CleanTemporaryFiles();
1097 if (!OverrideMainBuffer) {
1099 TopLevelDeclsInPreamble.clear();
1111 if (OverrideMainBuffer) {
1113 OverrideMainBuffer.get());
1116 = PreambleEndsAtStartOfLine;
1128 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1131 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1132 new TopLevelDeclTrackerAction(*
this));
1135 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1136 ActCleanup(Act.get());
1138 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1141 if (SavedMainFileBuffer) {
1144 PreambleDiagnostics, StoredDiagnostics);
1147 if (!Act->Execute())
1150 transferASTDataFromCompilerInstance(*Clang);
1152 Act->EndSourceFile();
1154 FailedParseDiagnostics.clear();
1160 SavedMainFileBuffer =
nullptr;
1164 transferASTDataFromCompilerInstance(*Clang);
1165 FailedParseDiagnostics.swap(StoredDiagnostics);
1166 StoredDiagnostics.clear();
1167 NumStoredDiagnosticsFromDriver = 0;
1176 const char *TmpFile = ::getenv(
"CINDEXTEST_PREAMBLE_FILE");
1181 llvm::sys::fs::createTemporaryFile(
"preamble",
"pch", Path);
1189 ASTUnit::ComputedPreamble
1197 llvm::MemoryBuffer *
Buffer =
nullptr;
1198 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1199 std::string MainFilePath(FrontendOpts.
Inputs[0].getFile());
1200 llvm::sys::fs::UniqueID MainFileID;
1201 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1204 std::string MPath(RF.first);
1205 llvm::sys::fs::UniqueID MID;
1206 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1207 if (MainFileID == MID) {
1211 return ComputedPreamble(
nullptr,
nullptr, 0,
true);
1219 std::string MPath(RB.first);
1220 llvm::sys::fs::UniqueID MID;
1221 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1222 if (MainFileID == MID) {
1224 BufferOwner.reset();
1225 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
1232 if (!Buffer && !BufferOwner) {
1235 return ComputedPreamble(
nullptr,
nullptr, 0,
true);
1239 Buffer = BufferOwner.get();
1242 return ComputedPreamble(Buffer, std::move(BufferOwner),
Pre.first,
1251 memset(Result.
MD5, 0,
sizeof(Result.
MD5));
1256 const llvm::MemoryBuffer *Buffer) {
1258 Result.
Size = Buffer->getBufferSize();
1262 MD5Ctx.update(Buffer->getBuffer().data());
1263 MD5Ctx.final(Result.
MD5);
1272 memcmp(LHS.
MD5, RHS.
MD5,
sizeof(LHS.
MD5)) == 0;
1276 static std::pair<unsigned, unsigned>
1282 return std::make_pair(Offset, EndOffset);
1341 std::unique_ptr<llvm::MemoryBuffer>
1342 ASTUnit::getMainBufferWithPrecompiledPreamble(
1343 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1345 unsigned MaxLines) {
1349 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1351 = PreambleInvocation->getPreprocessorOpts();
1353 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1355 if (!NewPreamble.Size) {
1362 PreambleRebuildCounter = 1;
1366 if (!Preamble.
empty()) {
1371 if (Preamble.
size() == NewPreamble.Size &&
1372 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1373 memcmp(Preamble.
getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1374 NewPreamble.Size) == 0) {
1379 bool AnyFileChanged =
false;
1383 llvm::StringMap<PreambleFileHash> OverriddenFiles;
1389 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1392 AnyFileChanged =
true;
1403 OverriddenFiles[RB.first] =
1409 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1410 !AnyFileChanged && F != FEnd;
1413 = OverriddenFiles.find(F->first());
1414 if (Overridden != OverriddenFiles.end()) {
1417 if (Overridden->second != F->second)
1418 AnyFileChanged =
true;
1424 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1426 AnyFileChanged =
true;
1427 }
else if (Status.
getSize() != uint64_t(F->second.Size) ||
1429 uint64_t(F->second.ModTime))
1430 AnyFileChanged =
true;
1433 if (!AnyFileChanged) {
1440 PreambleInvocation->getDiagnosticOpts());
1443 return llvm::MemoryBuffer::getMemBufferCopy(
1444 NewPreamble.Buffer->getBuffer(), FrontendOpts.
Inputs[0].getFile());
1455 PreambleDiagnostics.clear();
1457 PreambleRebuildCounter = 1;
1458 }
else if (!AllowRebuild) {
1467 if (PreambleRebuildCounter > 1) {
1468 --PreambleRebuildCounter;
1475 if (PreamblePCHPath.empty()) {
1477 PreambleRebuildCounter = 1;
1482 SimpleTimer PreambleTimer(WantTiming);
1483 PreambleTimer.setOutput(
"Precompiling preamble");
1487 StringRef MainFilename = FrontendOpts.
Inputs[0].getFile();
1488 Preamble.
assign(FileMgr->getFile(MainFilename),
1489 NewPreamble.Buffer->getBufferStart(),
1490 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1491 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1493 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1494 NewPreamble.Buffer->getBuffer().slice(0, Preamble.
size()), MainFilename);
1497 StringRef MainFilePath = FrontendOpts.
Inputs[0].getFile();
1508 std::unique_ptr<CompilerInstance> Clang(
1512 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1513 CICleanup(Clang.get());
1515 Clang->setInvocation(&*PreambleInvocation);
1516 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1523 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1524 if (!Clang->hasTarget()) {
1525 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1536 Clang->getTarget().adjust(Clang->getLangOpts());
1538 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1539 "Invocation must have exactly one source file!");
1540 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1541 "FIXME: AST inputs not yet supported here!");
1542 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1543 "IR inputs not support here!");
1549 TopLevelDecls.clear();
1550 TopLevelDeclsInPreamble.clear();
1551 PreambleDiagnostics.clear();
1559 Clang->setFileManager(
new FileManager(Clang->getFileSystemOpts(), VFS));
1563 Clang->getFileManager()));
1565 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1566 Clang->addDependencyCollector(PreambleDepCollector);
1568 std::unique_ptr<PrecompilePreambleAction> Act;
1569 Act.reset(
new PrecompilePreambleAction(*
this));
1570 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1571 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1585 PreambleDiagnostics.push_back(
1588 Act->EndSourceFile();
1592 if (!Act->hasEmittedPreamblePCH()) {
1596 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1598 TopLevelDeclsInPreamble.clear();
1610 FilesInPreamble.clear();
1612 for (
auto &
Filename : PreambleDepCollector->getDependencies()) {
1621 FilesInPreamble[File->
getName()] =
1626 PreambleRebuildCounter = 1;
1632 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1633 CompletionCacheTopLevelHashValue = 0;
1634 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1637 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1641 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1642 std::vector<Decl *> Resolved;
1643 Resolved.reserve(TopLevelDeclsInPreamble.size());
1649 Resolved.push_back(D);
1651 TopLevelDeclsInPreamble.clear();
1652 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1680 return Input.
getBuffer()->getBufferIdentifier();
1686 return FE->getName();
1697 Mod = Reader->getModuleManager().getPrimaryModule();
1703 bool CaptureDiagnostics,
1704 bool UserFilesAreVolatile) {
1705 std::unique_ptr<ASTUnit> AST;
1706 AST.reset(
new ASTUnit(
false));
1707 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1708 AST->Diagnostics = Diags;
1709 AST->Invocation = CI;
1715 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1716 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1717 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1718 UserFilesAreVolatile);
1720 return AST.release();
1725 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1727 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1728 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1729 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1730 bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile,
1731 std::unique_ptr<ASTUnit> *ErrAST) {
1732 assert(CI &&
"A CompilerInvocation is required");
1734 std::unique_ptr<ASTUnit> OwnAST;
1738 OwnAST.reset(
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1744 if (!ResourceFilesPath.empty()) {
1748 AST->OnlyLocalDecls = OnlyLocalDecls;
1749 AST->CaptureDiagnostics = CaptureDiagnostics;
1750 if (PrecompilePreambleAfterNParses > 0)
1751 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1753 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1754 AST->IncludeBriefCommentsInCodeCompletion
1755 = IncludeBriefCommentsInCodeCompletion;
1758 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1759 ASTUnitCleanup(OwnAST.get());
1761 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1762 DiagCleanup(Diags.get());
1770 std::unique_ptr<CompilerInstance> Clang(
1774 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1775 CICleanup(Clang.get());
1777 Clang->setInvocation(CI);
1778 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1786 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1787 if (!Clang->hasTarget())
1794 Clang->getTarget().adjust(Clang->getLangOpts());
1796 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1797 "Invocation must have exactly one source file!");
1798 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1799 "FIXME: AST inputs not yet supported here!");
1800 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1801 "IR inputs not supported here!");
1804 AST->TheSema.reset();
1807 AST->Reader =
nullptr;
1817 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1819 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1820 Act = TrackerAct.get();
1824 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1825 ActCleanup(TrackerAct.get());
1827 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1828 AST->transferASTDataFromCompilerInstance(*Clang);
1829 if (OwnAST && ErrAST)
1830 ErrAST->swap(OwnAST);
1835 if (Persistent && !TrackerAct) {
1836 Clang->getPreprocessor().addPPCallbacks(
1837 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1839 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1840 if (Clang->hasASTConsumer())
1841 Consumers.push_back(Clang->takeASTConsumer());
1842 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1844 Clang->setASTConsumer(
1845 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1848 AST->transferASTDataFromCompilerInstance(*Clang);
1849 if (OwnAST && ErrAST)
1850 ErrAST->swap(OwnAST);
1856 AST->transferASTDataFromCompilerInstance(*Clang);
1861 return OwnAST.release();
1866 bool ASTUnit::LoadFromCompilerInvocation(
1867 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1868 unsigned PrecompilePreambleAfterNParses) {
1877 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1878 if (PrecompilePreambleAfterNParses > 0) {
1879 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1880 OverrideMainBuffer =
1881 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1884 SimpleTimer ParsingTimer(WantTiming);
1888 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1889 MemBufferCleanup(OverrideMainBuffer.get());
1891 return Parse(PCHContainerOps, std::move(OverrideMainBuffer));
1894 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1896 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1898 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1900 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1901 bool UserFilesAreVolatile) {
1903 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1904 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1905 AST->Diagnostics = Diags;
1906 AST->OnlyLocalDecls = OnlyLocalDecls;
1907 AST->CaptureDiagnostics = CaptureDiagnostics;
1908 AST->TUKind = TUKind;
1909 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1910 AST->IncludeBriefCommentsInCodeCompletion
1911 = IncludeBriefCommentsInCodeCompletion;
1912 AST->Invocation = CI;
1914 AST->FileMgr = FileMgr;
1915 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1918 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1919 ASTUnitCleanup(AST.get());
1921 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1922 DiagCleanup(Diags.get());
1924 if (AST->LoadFromCompilerInvocation(PCHContainerOps,
1925 PrecompilePreambleAfterNParses))
1931 const char **ArgBegin,
const char **ArgEnd,
1932 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1934 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1937 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1938 bool AllowPCHWithCompilerErrors,
bool SkipFunctionBodies,
1939 bool UserFilesAreVolatile,
bool ForSerialization,
1941 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1949 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1953 llvm::makeArrayRef(ArgBegin, ArgEnd),
1961 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1969 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1971 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1974 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1977 std::unique_ptr<ASTUnit> AST;
1978 AST.reset(
new ASTUnit(
false));
1979 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1980 AST->Diagnostics = Diags;
1981 AST->FileSystemOpts = CI->getFileSystemOpts();
1986 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1987 AST->OnlyLocalDecls = OnlyLocalDecls;
1988 AST->CaptureDiagnostics = CaptureDiagnostics;
1989 AST->TUKind = TUKind;
1990 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1991 AST->IncludeBriefCommentsInCodeCompletion
1992 = IncludeBriefCommentsInCodeCompletion;
1993 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1994 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1995 AST->StoredDiagnostics.swap(StoredDiagnostics);
1996 AST->Invocation = CI;
1997 if (ForSerialization)
2004 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2005 ASTUnitCleanup(AST.get());
2007 if (AST->LoadFromCompilerInvocation(PCHContainerOps,
2008 PrecompilePreambleAfterNParses)) {
2012 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2018 return AST.release();
2026 clearFileLevelDecls();
2028 SimpleTimer ParsingTimer(WantTiming);
2044 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2046 OverrideMainBuffer =
2047 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2053 if (OverrideMainBuffer)
2057 bool Result = Parse(PCHContainerOps, std::move(OverrideMainBuffer));
2061 if (!Result && ShouldCacheCodeCompletionResults &&
2062 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2063 CacheCodeCompletionResults();
2081 uint64_t NormalContexts;
2089 AST(AST), Next(Next)
2116 unsigned NumResults)
override;
2118 void ProcessOverloadCandidates(
Sema &
S,
unsigned CurrentArg,
2120 unsigned NumCandidates)
override {
2138 unsigned NumResults,
2140 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2141 bool OnlyTagNames =
false;
2166 OnlyTagNames =
true;
2188 for (
unsigned I = 0;
I != NumResults; ++
I) {
2189 if (Results[
I].
Kind != Result::RK_Declaration)
2195 bool Hiding =
false;
2204 Hiding = (IDNS & HiddenIDNS);
2212 HiddenNames.insert(Identifier->getName());
2218 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2221 unsigned NumResults) {
2223 bool AddedResult =
false;
2224 uint64_t InContexts =
2226 ? NormalContexts : (1LL << Context.
getKind());
2228 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2237 if ((
C->ShowInContexts & InContexts) == 0)
2244 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2251 HiddenNames.count(
C->Completion->getTypedText()))
2255 unsigned Priority =
C->Priority;
2262 }
else if (
C->Type) {
2267 if (ExpectedSTC ==
C->TypeClass) {
2269 llvm::StringMap<unsigned> &CachedCompletionTypes
2272 = CachedCompletionTypes.find(
QualType(Expected).getAsString());
2273 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2288 Builder.AddTypedTextChunk(
C->Completion->getTypedText());
2290 Completion =
Builder.TakeString();
2293 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2309 StringRef File,
unsigned Line,
unsigned Column,
2311 bool IncludeCodePatterns,
bool IncludeBriefComments,
2313 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2320 SimpleTimer CompletionTimer(WantTiming);
2321 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2322 Twine(Line) +
":" + Twine(Column));
2332 CachedCompletionResults.empty();
2334 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2337 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2344 LangOpts = *CCInvocation->getLangOpts();
2347 LangOpts.SpellChecking =
false;
2348 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2350 std::unique_ptr<CompilerInstance> Clang(
2354 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2355 CICleanup(Clang.get());
2357 Clang->setInvocation(&*CCInvocation);
2358 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2361 Clang->setDiagnostics(&Diag);
2362 CaptureDroppedDiagnostics Capture(
true,
2363 Clang->getDiagnostics(),
2369 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2370 if (!Clang->hasTarget()) {
2371 Clang->setInvocation(
nullptr);
2379 Clang->getTarget().adjust(Clang->getLangOpts());
2381 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2382 "Invocation must have exactly one source file!");
2383 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
2384 "FIXME: AST inputs not yet supported here!");
2385 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
2386 "IR inputs not support here!");
2390 Clang->setFileManager(&FileMgr);
2391 Clang->setSourceManager(&SourceMgr);
2403 AugmentedCodeCompleteConsumer *AugmentedConsumer
2404 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2405 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2411 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2413 std::string CompleteFilePath(File);
2414 llvm::sys::fs::UniqueID CompleteFileID;
2416 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2417 std::string MainPath(OriginalSourceFile);
2418 llvm::sys::fs::UniqueID MainID;
2419 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2420 if (CompleteFileID == MainID && Line > 1)
2421 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2422 PCHContainerOps, *CCInvocation,
false, Line - 1);
2429 if (OverrideMainBuffer) {
2431 OverrideMainBuffer.get());
2434 = PreambleEndsAtStartOfLine;
2438 OwnedBuffers.push_back(OverrideMainBuffer.release());
2445 if (!Clang->getLangOpts().Modules)
2448 std::unique_ptr<SyntaxOnlyAction> Act;
2450 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2452 Act->EndSourceFile();
2457 if (HadModuleLoaderFatalFailure)
2464 TempPath +=
"-%%%%%%%%";
2466 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2471 llvm::raw_fd_ostream Out(fd,
true);
2475 if (Out.has_error()) {
2480 if (llvm::sys::fs::rename(TempPath, File)) {
2481 llvm::sys::fs::remove(TempPath);
2493 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2496 if (!Buffer.empty())
2497 OS.write(Buffer.data(), Buffer.size());
2506 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2510 llvm::BitstreamWriter Stream(Buffer);
2517 void ASTUnit::TranslateStoredDiagnostics(
2528 Result.reserve(Diags.size());
2529 for (
const StandaloneDiagnostic &SD : Diags) {
2531 if (SD.Filename.empty())
2544 Ranges.reserve(SD.Ranges.size());
2545 for (
const auto &Range : SD.Ranges) {
2552 FixIts.reserve(SD.FixIts.size());
2553 for (
const StandaloneFixIt &
FixIt : SD.FixIts) {
2563 SD.Message, Loc, Ranges, FixIts));
2589 if (FID.isInvalid())
2596 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2598 if (Decls->empty() || Decls->back().first <=
Offset) {
2599 Decls->push_back(LocDecl);
2604 LocDecl, llvm::less_first());
2606 Decls->insert(I, LocDecl);
2621 if (I == FileDecls.end())
2625 if (LocDecls.empty())
2629 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2630 std::make_pair(Offset, (
Decl *)
nullptr),
2631 llvm::less_first());
2632 if (BeginIt != LocDecls.begin())
2638 while (BeginIt != LocDecls.begin() &&
2639 BeginIt->second->isTopLevelDeclInObjCContainer())
2643 LocDecls.begin(), LocDecls.end(),
2644 std::make_pair(Offset + Length, (
Decl *)
nullptr), llvm::less_first());
2645 if (EndIt != LocDecls.end())
2649 Decls.push_back(DIt->second);
2653 unsigned Line,
unsigned Col)
const {
2678 if (SourceMgr->
isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.
size()) {
2700 Offs < Preamble.
size()) {
2752 llvm::iterator_range<PreprocessingRecord::iterator>
2756 Mod = Reader->getModuleManager().getPrimaryModule();
2757 return Reader->getModulePreprocessedEntities(Mod);
2761 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2770 Mod = Reader->getModuleManager().getPrimaryModule();
2771 for (
const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2772 if (!Fn(context, D))
2781 TL != TLEnd; ++TL) {
2782 if (!Fn(context, *TL))
2820 void ASTUnit::PreambleData::countLines()
const {
2825 NumLines = std::count(Buffer.begin(), Buffer.end(),
'\n');
2827 if (Buffer.back() !=
'\n')
2832 ASTUnit::ConcurrencyState::ConcurrencyState() {
2833 Mutex =
new llvm::sys::MutexImpl(
true);
2836 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2837 delete static_cast<llvm::sys::MutexImpl *
>(Mutex);
2840 void ASTUnit::ConcurrencyState::start() {
2841 bool acquired =
static_cast<llvm::sys::MutexImpl *
>(Mutex)->tryacquire();
2842 assert(acquired &&
"Concurrent access to ASTUnit!");
2845 void ASTUnit::ConcurrencyState::finish() {
2846 static_cast<llvm::sys::MutexImpl *
>(Mutex)->release();
2851 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2852 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2853 void ASTUnit::ConcurrencyState::start() {}
2854 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)
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
Decl - This represents one declaration (or definition), e.g.
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)
bool hasErrorOccurred() const
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.
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.
Types, declared with 'struct foo', typedefs, etc.
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.
Priority for a code pattern.
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.
unsigned getIdentifierNamespace() const
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)
bool BeforePreviousInsertions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
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...
Namespaces, declared with 'namespace foo {}'.
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...
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)...
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.
std::string CurrentModule
The name of the current module.
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
This declaration is a C++ operator declared in a non-class context.
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.
static ASTUnit * LoadFromCompilerInvocationAction(CompilerInvocation *CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, ASTFrontendAction *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 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...
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.
DeclContext * getDeclContext()
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
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
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)
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.
Members, declared with object declarations within tag definitions.
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.
Priority for a nested-name-specifier.
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.
bool isFileContext() const
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.
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
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.
Divide by this factor when a code-completion result's type exactly matches the type we expect...
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...
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
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...
static 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 ...
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.
SourceLocation getLocation() const
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.
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