67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/IntrusiveRefCntPtr.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallString.h" 74 #include "llvm/ADT/SmallVector.h" 75 #include "llvm/ADT/StringMap.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSet.h" 78 #include "llvm/ADT/Twine.h" 79 #include "llvm/ADT/iterator_range.h" 80 #include "llvm/Bitcode/BitstreamWriter.h" 81 #include "llvm/Support/Allocator.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/CrashRecoveryContext.h" 84 #include "llvm/Support/DJB.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/ErrorOr.h" 87 #include "llvm/Support/FileSystem.h" 88 #include "llvm/Support/MemoryBuffer.h" 89 #include "llvm/Support/Mutex.h" 90 #include "llvm/Support/Timer.h" 91 #include "llvm/Support/raw_ostream.h" 104 using namespace clang;
106 using llvm::TimeRecord;
116 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
118 Start = TimeRecord::getCurrentTime();
123 TimeRecord Elapsed = TimeRecord::getCurrentTime();
125 llvm::errs() << Output <<
':';
126 Elapsed.print(Elapsed, llvm::errs());
127 llvm::errs() <<
'\n';
131 void setOutput(
const Twine &Output) {
133 this->Output = Output.str();
140 static std::unique_ptr<T>
valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
143 return std::move(*Val);
150 Output = std::move(*Val);
156 static std::unique_ptr<llvm::MemoryBuffer>
166 llvm::MemoryBuffer *Buffer =
nullptr;
167 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
168 auto FileStatus = VFS->
status(FilePath);
170 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
173 for (
const auto &RF : PreprocessorOpts.RemappedFiles) {
174 std::string MPath(RF.first);
175 auto MPathStatus = VFS->
status(MPath);
177 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
178 if (MainFileID == MID) {
189 for (
const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
190 std::string MPath(RB.first);
191 auto MPathStatus = VFS->
status(MPath);
193 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
194 if (MainFileID == MID) {
197 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
204 if (!Buffer && !BufferOwner) {
214 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
223 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
226 void ASTUnit::clearFileLevelDecls() {
227 llvm::DeleteContainerSeconds(FileDecls);
241 ASTUnit::ASTUnit(
bool _MainFileIsAST)
242 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv(
"LIBCLANG_TIMING")),
243 ShouldCacheCodeCompletionResults(
false),
244 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
245 UnsafeToFree(
false) {
246 if (getenv(
"LIBCLANG_OBJTRACKING"))
247 fprintf(stderr,
"+++ %u translation units\n", ++ActiveASTUnitObjects);
250 ASTUnit::~ASTUnit() {
256 clearFileLevelDecls();
262 if (Invocation && OwnsRemappedFileBuffers) {
268 ClearCachedCompletionResults();
270 if (getenv(
"LIBCLANG_OBJTRACKING"))
271 fprintf(stderr,
"--- %u translation units\n", --ActiveASTUnitObjects);
275 this->PP = std::move(PP);
280 "Bad context for source file");
288 bool &IsNestedNameSpecifier) {
289 IsNestedNameSpecifier =
false;
291 if (isa<UsingShadowDecl>(ND))
296 uint64_t Contexts = 0;
297 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
298 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
299 isa<TypeAliasTemplateDecl>(ND)) {
301 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
310 if (LangOpts.CPlusPlus)
315 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
319 if (
const auto *
ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
321 if (
ID->getDefinition())
327 if (isa<EnumDecl>(ND)) {
331 if (LangOpts.CPlusPlus11)
332 IsNestedNameSpecifier =
true;
333 }
else if (
const auto *Record = dyn_cast<RecordDecl>(ND)) {
334 if (Record->isUnion())
339 if (LangOpts.CPlusPlus)
340 IsNestedNameSpecifier =
true;
341 }
else if (isa<ClassTemplateDecl>(ND))
342 IsNestedNameSpecifier =
true;
343 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
349 }
else if (isa<ObjCProtocolDecl>(ND)) {
351 }
else if (isa<ObjCCategoryDecl>(ND)) {
353 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
357 IsNestedNameSpecifier =
true;
363 void ASTUnit::CacheCodeCompletionResults() {
367 SimpleTimer Timer(WantTiming);
368 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
371 ClearCachedCompletionResults();
376 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
378 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
382 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
385 for (
auto &R : Results) {
387 case Result::RK_Declaration: {
388 bool IsNestedNameSpecifier =
false;
389 CachedCodeCompletionResult CachedResult;
390 CachedResult.Completion = R.CreateCodeCompletionString(
391 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
392 IncludeBriefCommentsInCodeCompletion);
394 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
395 CachedResult.Priority = R.Priority;
396 CachedResult.Kind = R.CursorKind;
397 CachedResult.Availability = R.Availability;
404 CachedResult.Type = 0;
413 unsigned &TypeValue = CompletionTypes[CanUsageType];
414 if (TypeValue == 0) {
415 TypeValue = CompletionTypes.size();
420 CachedResult.Type = TypeValue;
423 CachedCompletionResults.push_back(CachedResult);
426 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
427 !R.StartsNestedNameSpecifier) {
443 if (isa<NamespaceDecl>(R.Declaration) ||
444 isa<NamespaceAliasDecl>(R.Declaration))
447 if (
unsigned RemainingContexts
448 = NNSContexts & ~CachedResult.ShowInContexts) {
452 R.StartsNestedNameSpecifier =
true;
453 CachedResult.Completion = R.CreateCodeCompletionString(
454 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
455 IncludeBriefCommentsInCodeCompletion);
456 CachedResult.ShowInContexts = RemainingContexts;
459 CachedResult.Type = 0;
460 CachedCompletionResults.push_back(CachedResult);
466 case Result::RK_Keyword:
467 case Result::RK_Pattern:
472 case Result::RK_Macro: {
473 CachedCodeCompletionResult CachedResult;
474 CachedResult.Completion = R.CreateCodeCompletionString(
475 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
476 IncludeBriefCommentsInCodeCompletion);
477 CachedResult.ShowInContexts
491 CachedResult.Priority = R.Priority;
492 CachedResult.Kind = R.CursorKind;
493 CachedResult.Availability = R.Availability;
495 CachedResult.Type = 0;
496 CachedCompletionResults.push_back(CachedResult);
503 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
506 void ASTUnit::ClearCachedCompletionResults() {
507 CachedCompletionResults.clear();
508 CachedCompletionTypes.clear();
509 CachedCompletionAllocator =
nullptr;
522 std::shared_ptr<TargetOptions> &TargetOpts;
523 IntrusiveRefCntPtr<TargetInfo> &Target;
525 bool InitializedLanguage =
false;
531 std::shared_ptr<TargetOptions> &TargetOpts,
532 IntrusiveRefCntPtr<TargetInfo> &Target,
unsigned &Counter)
533 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
534 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
537 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
538 bool AllowCompatibleDifferences)
override {
539 if (InitializedLanguage)
543 InitializedLanguage =
true;
550 StringRef SpecificModuleCachePath,
551 bool Complain)
override {
552 this->HSOpts = HSOpts;
557 std::string &SuggestedPredefines)
override {
558 this->PPOpts = PPOpts;
562 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
563 bool AllowCompatibleDifferences)
override {
568 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
577 unsigned Value)
override {
583 if (!Target || !InitializedLanguage)
590 Target->adjust(LangOpt);
619 StoredDiagnosticConsumer(
622 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags) {
623 assert((StoredDiags || StandaloneDiags) &&
624 "No output collections were passed to StoredDiagnosticConsumer.");
629 this->LangOpts = &LangOpts;
631 SourceMgr = &PP->getSourceManager();
640 class CaptureDroppedDiagnostics {
642 StoredDiagnosticConsumer Client;
644 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
647 CaptureDroppedDiagnostics(
651 : Diags(Diags), Client(StoredDiags, StandaloneDiags) {
652 if (RequestCapture || Diags.
getClient() ==
nullptr) {
659 ~CaptureDroppedDiagnostics() {
661 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
682 StoredDiags->emplace_back(Level, Info);
683 ResultDiag = &StoredDiags->back();
686 if (StandaloneDiags) {
689 StoredDiag.emplace(Level, Info);
690 ResultDiag = StoredDiag.getPointer();
692 StandaloneDiags->push_back(
704 return &WriterData->Writer;
710 return &WriterData->Writer;
714 std::unique_ptr<llvm::MemoryBuffer>
717 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
719 return std::move(*Buffer);
721 *ErrorStr = Buffer.getError().message();
727 ASTUnit &AST,
bool CaptureDiagnostics) {
728 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
729 if (CaptureDiagnostics)
730 Diags->setClient(
new StoredDiagnosticConsumer(&AST.StoredDiagnostics,
nullptr));
738 bool CaptureDiagnostics,
bool AllowPCHWithCompilerErrors,
739 bool UserFilesAreVolatile) {
740 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
743 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
744 ASTUnitCleanup(AST.get());
746 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
747 DiagCleanup(Diags.get());
749 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
751 AST->LangOpts = std::make_shared<LangOptions>();
752 AST->OnlyLocalDecls = OnlyLocalDecls;
753 AST->CaptureDiagnostics = CaptureDiagnostics;
754 AST->Diagnostics = Diags;
756 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
757 AST->UserFilesAreVolatile = UserFilesAreVolatile;
759 AST->getFileManager(),
760 UserFilesAreVolatile);
762 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
763 AST->HSOpts->ModuleFormat = PCHContainerRdr.
getFormat();
765 AST->getSourceManager(),
766 AST->getDiagnostics(),
769 AST->PPOpts = std::make_shared<PreprocessorOptions>();
779 AST->PP = std::make_shared<Preprocessor>(
780 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
781 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
787 AST->Ctx =
new ASTContext(*AST->LangOpts, AST->getSourceManager(),
788 PP.getIdentifierTable(), PP.getSelectorTable(),
789 PP.getBuiltinInfo());
791 bool disableValid =
false;
792 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
794 AST->Reader =
new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, {},
797 AllowPCHWithCompilerErrors);
799 AST->Reader->
setListener(llvm::make_unique<ASTInfoCollector>(
800 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
801 AST->TargetOpts, AST->Target, Counter));
809 AST->Ctx->setExternalSource(AST->Reader);
822 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
826 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
828 PP.setCounterValue(Counter);
836 AST->TheSema.reset(
new Sema(PP, *AST->Ctx, *AST->Consumer));
837 AST->TheSema->Initialize();
838 AST->Reader->InitializeSema(*AST->TheSema);
842 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
856 class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
860 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) {}
862 void MacroDefined(
const Token &MacroNameTok,
882 if (
const auto *ND = dyn_cast<NamedDecl>(D)) {
883 if (
const auto *EnumD = dyn_cast<EnumDecl>(D)) {
886 if (!EnumD->isScoped()) {
887 for (
const auto *EI : EnumD->enumerators()) {
888 if (EI->getIdentifier())
889 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
894 if (ND->getIdentifier())
895 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
897 std::string NameStr = Name.getAsString();
898 Hash = llvm::djbHash(NameStr, Hash);
903 if (
const auto *ImportD = dyn_cast<ImportDecl>(D)) {
904 if (
const Module *Mod = ImportD->getImportedModule()) {
905 std::string ModName = Mod->getFullModuleName();
906 Hash = llvm::djbHash(ModName, Hash);
914 class TopLevelDeclTrackerConsumer :
public ASTConsumer {
919 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
920 : Unit(_Unit), Hash(Hash) {
924 void handleTopLevelDecl(
Decl *D) {
932 if (isa<ObjCMethodDecl>(D))
938 handleFileLevelDecl(D);
941 void handleFileLevelDecl(
Decl *D) {
943 if (
auto *NSD = dyn_cast<NamespaceDecl>(D)) {
944 for (
auto *I : NSD->decls())
945 handleFileLevelDecl(I);
950 for (
auto *TopLevelDecl : D)
951 handleTopLevelDecl(TopLevelDecl);
958 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
959 for (
auto *TopLevelDecl : D)
960 handleTopLevelDecl(TopLevelDecl);
977 StringRef InFile)
override {
979 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
981 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
986 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
988 bool hasCodeCompletionSupport()
const override {
return false; }
997 unsigned getHash()
const {
return Hash; }
999 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
1001 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1002 return std::move(TopLevelDeclIDs);
1005 void AfterPCHEmitted(
ASTWriter &Writer)
override {
1006 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1007 for (
const auto *D : TopLevelDecls) {
1009 if (D->isInvalidDecl())
1011 TopLevelDeclIDs.push_back(Writer.
getDeclID(D));
1016 for (
auto *D : DG) {
1021 if (isa<ObjCMethodDecl>(D))
1024 TopLevelDecls.push_back(D);
1028 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
1029 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1034 std::vector<Decl *> TopLevelDecls;
1035 std::vector<serialization::DeclID> TopLevelDeclIDs;
1050 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1062 for (
auto &SD : StoredDiagnostics) {
1063 if (SD.getLocation().isValid()) {
1065 SD.setLocation(Loc);
1075 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1076 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1077 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1081 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1082 if (OverrideMainBuffer) {
1084 "No preamble was built, but OverrideMainBuffer is not null");
1085 IntrusiveRefCntPtr<vfs::FileSystem> OldVFS = VFS;
1086 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1087 if (OldVFS != VFS && FileMgr) {
1088 assert(OldVFS == FileMgr->getVirtualFileSystem() &&
1089 "VFS passed to Parse and VFS in FileMgr are different");
1090 FileMgr =
new FileManager(FileMgr->getFileSystemOpts(), VFS);
1095 std::unique_ptr<CompilerInstance> Clang(
1097 if (FileMgr && VFS) {
1098 assert(VFS == FileMgr->getVirtualFileSystem() &&
1099 "VFS passed to Parse and VFS in FileMgr are different");
1101 Clang->setVirtualFileSystem(VFS);
1105 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1106 CICleanup(Clang.get());
1108 Clang->setInvocation(CCInvocation);
1109 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1117 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1118 if (!Clang->hasTarget())
1125 Clang->getTarget().adjust(Clang->getLangOpts());
1127 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1128 "Invocation must have exactly one source file!");
1129 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1131 "FIXME: AST inputs not yet supported here!");
1132 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1134 "IR inputs not support here!");
1137 LangOpts = Clang->getInvocation().LangOpts;
1138 FileSystemOpts = Clang->getFileSystemOpts();
1140 Clang->createFileManager();
1141 FileMgr = &Clang->getFileManager();
1147 UserFilesAreVolatile);
1148 if (!OverrideMainBuffer) {
1150 TopLevelDeclsInPreamble.clear();
1161 if (OverrideMainBuffer) {
1170 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1173 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1174 new TopLevelDeclTrackerAction(*
this));
1177 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1178 ActCleanup(Act.get());
1180 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1183 if (SavedMainFileBuffer)
1185 PreambleDiagnostics, StoredDiagnostics);
1187 PreambleSrcLocCache.clear();
1189 if (!Act->Execute())
1192 transferASTDataFromCompilerInstance(*Clang);
1194 Act->EndSourceFile();
1196 FailedParseDiagnostics.clear();
1202 SavedMainFileBuffer =
nullptr;
1206 transferASTDataFromCompilerInstance(*Clang);
1207 FailedParseDiagnostics.swap(StoredDiagnostics);
1208 StoredDiagnostics.clear();
1209 NumStoredDiagnosticsFromDriver = 0;
1213 static std::pair<unsigned, unsigned>
1219 return std::make_pair(Offset, EndOffset);
1250 for (
const auto &Range : InDiag.
getRanges())
1278 std::unique_ptr<llvm::MemoryBuffer>
1279 ASTUnit::getMainBufferWithPrecompiledPreamble(
1280 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1282 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
bool AllowRebuild,
1283 unsigned MaxLines) {
1286 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1288 MainFilePath, UserFilesAreVolatile);
1289 if (!MainFileBuffer)
1294 MainFileBuffer.get(), MaxLines);
1299 if (
Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1310 PreambleRebuildCounter = 1;
1311 return MainFileBuffer;
1314 PreambleDiagnostics.clear();
1315 TopLevelDeclsInPreamble.clear();
1316 PreambleSrcLocCache.clear();
1317 PreambleRebuildCounter = 1;
1324 if (PreambleRebuildCounter > 1) {
1325 --PreambleRebuildCounter;
1329 assert(!
Preamble &&
"No Preamble should be stored at that point");
1337 ASTUnitPreambleCallbacks Callbacks;
1340 if (CaptureDiagnostics)
1341 Capture.emplace(
true, *Diagnostics, &NewPreambleDiags,
1342 &NewPreambleDiagsStandalone);
1345 SimpleTimer PreambleTimer(WantTiming);
1346 PreambleTimer.setOutput(
"Precompiling preamble");
1348 const bool PreviousSkipFunctionBodies =
1354 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1355 PCHContainerOps,
false, Callbacks);
1358 PreviousSkipFunctionBodies;
1361 Preamble = std::move(*NewPreamble);
1362 PreambleRebuildCounter = 1;
1364 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1368 PreambleRebuildCounter = 1;
1377 llvm_unreachable(
"unexpected BuildPreambleError");
1381 assert(
Preamble &&
"Preamble wasn't built");
1383 TopLevelDecls.clear();
1384 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1385 PreambleTopLevelHashValue = Callbacks.getHash();
1390 StoredDiagnostics = std::move(NewPreambleDiags);
1391 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1396 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1397 CompletionCacheTopLevelHashValue = 0;
1398 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1401 return MainFileBuffer;
1404 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1405 assert(
Preamble &&
"Should only be called when preamble was built");
1407 std::vector<Decl *> Resolved;
1408 Resolved.reserve(TopLevelDeclsInPreamble.size());
1410 for (
const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1414 Resolved.push_back(D);
1416 TopLevelDeclsInPreamble.clear();
1417 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1440 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1445 return Input.
getBuffer()->getBufferIdentifier();
1450 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1451 return FE->getName();
1462 Mod = Reader->getModuleManager().getPrimaryModule();
1466 std::unique_ptr<ASTUnit>
1469 bool CaptureDiagnostics,
bool UserFilesAreVolatile) {
1470 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1471 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1474 AST->Diagnostics = Diags;
1475 AST->FileSystemOpts = CI->getFileSystemOpts();
1476 AST->Invocation = std::move(CI);
1477 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1478 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1479 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1480 UserFilesAreVolatile);
1487 std::shared_ptr<CompilerInvocation> CI,
1488 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1490 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1491 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1492 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1493 bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile,
1494 std::unique_ptr<ASTUnit> *ErrAST) {
1495 assert(CI &&
"A CompilerInvocation is required");
1497 std::unique_ptr<ASTUnit> OwnAST;
1501 OwnAST =
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1507 if (!ResourceFilesPath.empty()) {
1511 AST->OnlyLocalDecls = OnlyLocalDecls;
1512 AST->CaptureDiagnostics = CaptureDiagnostics;
1513 if (PrecompilePreambleAfterNParses > 0)
1514 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1516 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1517 AST->IncludeBriefCommentsInCodeCompletion
1518 = IncludeBriefCommentsInCodeCompletion;
1521 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1522 ASTUnitCleanup(OwnAST.get());
1524 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1525 DiagCleanup(Diags.get());
1528 CI->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1529 CI->getFrontendOpts().DisableFree =
false;
1533 std::unique_ptr<CompilerInstance> Clang(
1537 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1538 CICleanup(Clang.get());
1540 Clang->setInvocation(std::move(CI));
1541 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1549 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1550 if (!Clang->hasTarget())
1557 Clang->getTarget().adjust(Clang->getLangOpts());
1559 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1560 "Invocation must have exactly one source file!");
1561 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1563 "FIXME: AST inputs not yet supported here!");
1564 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1566 "IR inputs not support here!");
1569 AST->TheSema.reset();
1572 AST->Reader =
nullptr;
1582 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1584 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1585 Act = TrackerAct.get();
1589 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1590 ActCleanup(TrackerAct.get());
1592 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1593 AST->transferASTDataFromCompilerInstance(*Clang);
1594 if (OwnAST && ErrAST)
1595 ErrAST->swap(OwnAST);
1600 if (Persistent && !TrackerAct) {
1601 Clang->getPreprocessor().addPPCallbacks(
1602 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1604 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1605 if (Clang->hasASTConsumer())
1606 Consumers.push_back(Clang->takeASTConsumer());
1607 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1609 Clang->setASTConsumer(
1610 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1613 AST->transferASTDataFromCompilerInstance(*Clang);
1614 if (OwnAST && ErrAST)
1615 ErrAST->swap(OwnAST);
1621 AST->transferASTDataFromCompilerInstance(*Clang);
1626 return OwnAST.release();
1631 bool ASTUnit::LoadFromCompilerInvocation(
1632 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1633 unsigned PrecompilePreambleAfterNParses,
1638 assert(VFS &&
"VFS is null");
1641 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1642 Invocation->getFrontendOpts().DisableFree =
false;
1646 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1647 if (PrecompilePreambleAfterNParses > 0) {
1648 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1649 OverrideMainBuffer =
1650 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1655 SimpleTimer ParsingTimer(WantTiming);
1659 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1660 MemBufferCleanup(OverrideMainBuffer.get());
1662 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1665 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1666 std::shared_ptr<CompilerInvocation> CI,
1667 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1669 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1671 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1672 bool UserFilesAreVolatile) {
1674 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1675 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1676 AST->Diagnostics = Diags;
1677 AST->OnlyLocalDecls = OnlyLocalDecls;
1678 AST->CaptureDiagnostics = CaptureDiagnostics;
1679 AST->TUKind = TUKind;
1680 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1681 AST->IncludeBriefCommentsInCodeCompletion
1682 = IncludeBriefCommentsInCodeCompletion;
1683 AST->Invocation = std::move(CI);
1685 AST->FileMgr = FileMgr;
1686 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1689 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1690 ASTUnitCleanup(AST.get());
1692 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1693 DiagCleanup(Diags.get());
1695 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1696 PrecompilePreambleAfterNParses,
1697 AST->FileMgr->getVirtualFileSystem()))
1703 const char **ArgBegin,
const char **ArgEnd,
1704 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1706 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1709 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1711 bool SingleFileParse,
bool UserFilesAreVolatile,
bool ForSerialization,
1714 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1718 std::shared_ptr<CompilerInvocation> CI;
1721 CaptureDroppedDiagnostics
Capture(CaptureDiagnostics, *Diags,
1722 &StoredDiagnostics,
nullptr);
1725 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1732 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1741 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1743 CI->getFrontendOpts().SkipFunctionBodies =
1747 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1750 std::unique_ptr<ASTUnit> AST;
1751 AST.reset(
new ASTUnit(
false));
1752 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1753 AST->StoredDiagnostics.swap(StoredDiagnostics);
1754 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1755 AST->Diagnostics = Diags;
1756 AST->FileSystemOpts = CI->getFileSystemOpts();
1760 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1762 AST->OnlyLocalDecls = OnlyLocalDecls;
1763 AST->CaptureDiagnostics = CaptureDiagnostics;
1764 AST->TUKind = TUKind;
1765 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1766 AST->IncludeBriefCommentsInCodeCompletion
1767 = IncludeBriefCommentsInCodeCompletion;
1768 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1769 AST->Invocation = CI;
1770 AST->SkipFunctionBodies = SkipFunctionBodies;
1771 if (ForSerialization)
1778 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1779 ASTUnitCleanup(AST.get());
1781 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1782 PrecompilePreambleAfterNParses,
1787 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1793 return AST.release();
1803 assert(FileMgr &&
"FileMgr is null on Reparse call");
1804 VFS = FileMgr->getVirtualFileSystem();
1807 clearFileLevelDecls();
1809 SimpleTimer ParsingTimer(WantTiming);
1819 Invocation->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1825 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1826 if (
Preamble || PreambleRebuildCounter > 0)
1827 OverrideMainBuffer =
1828 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1834 if (OverrideMainBuffer)
1839 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1843 if (!Result && ShouldCacheCodeCompletionResults &&
1844 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1845 CacheCodeCompletionResults();
1855 SavedMainFileBuffer.reset();
1863 TopLevelDecls.clear();
1864 clearFileLevelDecls();
1877 uint64_t NormalContexts;
1885 AST(AST), Next(Next) {
1911 unsigned NumResults)
override;
1913 void ProcessOverloadCandidates(
Sema &S,
unsigned CurrentArg,
1915 unsigned NumCandidates)
override {
1934 unsigned NumResults,
1936 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1937 bool OnlyTagNames =
false;
1962 OnlyTagNames =
true;
1984 for (
unsigned I = 0; I != NumResults; ++I) {
1985 if (Results[I].
Kind != Result::RK_Declaration)
1991 bool Hiding =
false;
2000 Hiding = (IDNS & HiddenIDNS);
2008 HiddenNames.insert(Identifier->getName());
2014 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2017 unsigned NumResults) {
2019 bool AddedResult =
false;
2020 uint64_t InContexts =
2022 ? NormalContexts : (1LL << Context.
getKind());
2024 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2033 if ((
C->ShowInContexts & InContexts) == 0)
2040 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2047 HiddenNames.count(
C->Completion->getTypedText()))
2051 unsigned Priority =
C->Priority;
2058 }
else if (
C->Type) {
2063 if (ExpectedSTC ==
C->TypeClass) {
2065 llvm::StringMap<unsigned> &CachedCompletionTypes
2067 llvm::StringMap<unsigned>::iterator Pos
2069 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2089 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2096 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2100 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2105 StringRef File,
unsigned Line,
unsigned Column,
2107 bool IncludeCodePatterns,
bool IncludeBriefComments,
2109 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2116 SimpleTimer CompletionTimer(WantTiming);
2117 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2118 Twine(Line) +
":" + Twine(Column));
2120 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2127 CachedCompletionResults.empty();
2129 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2134 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2141 LangOpts = *CCInvocation->getLangOpts();
2144 LangOpts.SpellChecking =
false;
2145 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2147 std::unique_ptr<CompilerInstance> Clang(
2151 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2152 CICleanup(Clang.get());
2154 auto &Inv = *CCInvocation;
2155 Clang->setInvocation(std::move(CCInvocation));
2156 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2159 Clang->setDiagnostics(&Diag);
2160 CaptureDroppedDiagnostics
Capture(
true,
2161 Clang->getDiagnostics(),
2162 &StoredDiagnostics,
nullptr);
2167 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2168 if (!Clang->hasTarget()) {
2169 Clang->setInvocation(
nullptr);
2177 Clang->getTarget().adjust(Clang->getLangOpts());
2179 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2180 "Invocation must have exactly one source file!");
2181 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2183 "FIXME: AST inputs not yet supported here!");
2184 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2186 "IR inputs not support here!");
2189 Clang->setFileManager(&FileMgr);
2190 Clang->setSourceManager(&SourceMgr);
2202 AugmentedCodeCompleteConsumer *AugmentedConsumer
2203 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2204 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2210 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2212 std::string CompleteFilePath(File);
2215 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2216 if (CompleteFileStatus) {
2217 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2219 std::string MainPath(OriginalSourceFile);
2220 auto MainStatus = VFS->status(MainPath);
2222 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2223 if (CompleteFileID == MainID && Line > 1)
2224 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2225 PCHContainerOps, Inv, VFS,
false, Line - 1);
2232 if (OverrideMainBuffer) {
2234 "No preamble was built, but OverrideMainBuffer is not null");
2237 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2238 OverrideMainBuffer.get());
2243 OwnedBuffers.push_back(OverrideMainBuffer.release());
2250 if (!Clang->getLangOpts().Modules)
2253 std::unique_ptr<SyntaxOnlyAction> Act;
2255 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2257 Act->EndSourceFile();
2262 if (HadModuleLoaderFatalFailure)
2269 TempPath +=
"-%%%%%%%%";
2271 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2276 llvm::raw_fd_ostream Out(fd,
true);
2280 if (Out.has_error()) {
2285 if (llvm::sys::fs::rename(TempPath, File)) {
2286 llvm::sys::fs::remove(TempPath);
2298 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2301 if (!Buffer.empty())
2302 OS.write(Buffer.data(), Buffer.size());
2312 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2316 llvm::BitstreamWriter Stream(Buffer);
2318 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2324 void ASTUnit::TranslateStoredDiagnostics(
2334 Result.reserve(Diags.size());
2336 for (
const auto &SD : Diags) {
2338 if (SD.Filename.empty())
2344 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2345 if (ItFileID == PreambleSrcLocCache.end()) {
2348 PreambleSrcLocCache[SD.Filename] = FileLoc;
2350 FileLoc = ItFileID->getValue();
2359 Ranges.reserve(SD.Ranges.size());
2360 for (
const auto &Range : SD.Ranges) {
2367 FixIts.reserve(SD.FixIts.size());
2368 for (
const auto &
FixIt : SD.FixIts) {
2378 SD.Message, Loc, Ranges, FixIts));
2404 if (FID.isInvalid())
2411 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2413 if (Decls->empty() || Decls->back().first <=
Offset) {
2414 Decls->push_back(LocDecl);
2418 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2419 LocDecl, llvm::less_first());
2421 Decls->insert(I, LocDecl);
2429 if (SourceMgr->isLoadedFileID(File)) {
2430 assert(Ctx->getExternalSource() &&
"No external source!");
2431 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2435 FileDeclsTy::iterator I = FileDecls.find(File);
2436 if (I == FileDecls.end())
2440 if (LocDecls.empty())
2443 LocDeclsTy::iterator BeginIt =
2444 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2445 std::make_pair(Offset, (
Decl *)
nullptr),
2446 llvm::less_first());
2447 if (BeginIt != LocDecls.begin())
2453 while (BeginIt != LocDecls.begin() &&
2454 BeginIt->second->isTopLevelDeclInObjCContainer())
2457 LocDeclsTy::iterator EndIt = std::upper_bound(
2458 LocDecls.begin(), LocDecls.end(),
2459 std::make_pair(Offset + Length, (
Decl *)
nullptr), llvm::less_first());
2460 if (EndIt != LocDecls.end())
2463 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2464 Decls.push_back(DIt->second);
2468 unsigned Line,
unsigned Col)
const {
2487 PreambleID = SourceMgr->getPreambleFileID();
2493 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs <
Preamble->getBounds().Size) {
2495 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2508 PreambleID = SourceMgr->getPreambleFileID();
2514 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2515 Offs < Preamble->getBounds().Size) {
2516 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2526 FID = SourceMgr->getPreambleFileID();
2531 return SourceMgr->isInFileID(Loc, FID);
2537 FID = SourceMgr->getMainFileID();
2542 return SourceMgr->isInFileID(Loc, FID);
2548 FID = SourceMgr->getPreambleFileID();
2553 return SourceMgr->getLocForEndOfFile(FID);
2559 FID = SourceMgr->getMainFileID();
2564 return SourceMgr->getLocForStartOfFile(FID);
2567 llvm::iterator_range<PreprocessingRecord::iterator>
2571 Mod = Reader->getModuleManager().getPrimaryModule();
2572 return Reader->getModulePreprocessedEntities(Mod);
2576 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2585 Mod = Reader->getModuleManager().getPrimaryModule();
2586 for (
const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2587 if (!Fn(context, D))
2596 TL != TLEnd; ++TL) {
2597 if (!Fn(context, *TL))
2611 case serialization::MK_ImplicitModule:
2612 case serialization::MK_ExplicitModule:
2613 case serialization::MK_PrebuiltModule:
2615 case serialization::MK_PCH:
2618 case serialization::MK_Preamble:
2620 case serialization::MK_MainFile:
2640 if (LangOpts.OpenCL)
2642 else if (LangOpts.CUDA)
2644 else if (LangOpts.RenderScript)
2646 else if (LangOpts.CPlusPlus)
2662 ASTUnit::ConcurrencyState::ConcurrencyState() {
2663 Mutex =
new llvm::sys::MutexImpl(
true);
2666 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2667 delete static_cast<llvm::sys::MutexImpl *
>(Mutex);
2670 void ASTUnit::ConcurrencyState::start() {
2671 bool acquired =
static_cast<llvm::sys::MutexImpl *
>(Mutex)->tryacquire();
2672 assert(acquired &&
"Concurrent access to ASTUnit!");
2675 void ASTUnit::ConcurrencyState::finish() {
2676 static_cast<llvm::sys::MutexImpl *
>(Mutex)->release();
2681 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2682 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2683 void ASTUnit::ConcurrencyState::start() {}
2684 void ASTUnit::ConcurrencyState::finish() {}
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Defines the clang::ASTContext interface.
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
void ResetForParse()
Free data that will be re-generated on the next parse.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
CompilerInvocation & getInvocation()
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
DiagnosticConsumer * getClient()
A (possibly-)qualified type.
virtual Decl * GetExternalDecl(uint32_t ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
static std::unique_ptr< T > valueOrNull(llvm::ErrorOr< std::unique_ptr< T >> Val)
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
Implements support for file system lookup, file system caching, and directory search management...
const LangOptions & getLangOpts() const
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
std::pair< unsigned, unsigned > InsertFromRange
void addTopLevelDecl(Decl *D)
Add a new top-level declaration.
Defines the clang::FileManager interface and associated types.
Code completion for a selector, as in an @selector expression.
void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
unsigned IncludeGlobals
Show top-level decls in code completion results.
unsigned getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer=false)
Determine the priority to be given to a macro code completion result with the given name...
Code completion where an Objective-C class message is expected.
C Language Family Type Representation.
Defines the SourceManager interface.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
Code completion within a type-qualifier list.
Load everything, including Sema.
Abstract base class for actions which can be performed by the frontend.
Defines the clang::Module class, which describes a module in the source code.
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
Decl - This represents one declaration (or definition), e.g.
ModuleKind Kind
The type of this module.
const FileManager & getFileManager() const
Defines the C++ template declaration subclasses.
const unsigned DefaultPreambleRebuildInterval
After failing to build a precompiled preamble (due to errors in the source that occurs in the preambl...
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
An unspecified code-completion context.
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
static std::unique_ptr< ASTUnit > LoadFromASTFile(const std::string &Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, bool UseDebugInfo=false, bool OnlyLocalDecls=false, ArrayRef< RemappedFile > RemappedFiles=None, bool CaptureDiagnostics=false, bool AllowPCHWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
bool loadExternal() const
Hint whether to load data from the external AST in order to provide full results. ...
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
unsigned getIdentifierNamespace() const
Code completion occurred where an Objective-C message receiver is expected.
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, SkipFunctionBodiesScope SkipFunctionBodies=SkipFunctionBodiesScope::None, bool SingleFileParse=false, bool UserFilesAreVolatile=false, bool ForSerialization=false, llvm::Optional< StringRef > ModuleFormat=llvm::None, std::unique_ptr< ASTUnit > *ErrAST=nullptr, IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
LoadFromCommandLine - Create an ASTUnit from a vector of command line arguments, which must specify e...
ASTContext & getASTContext() const
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
bool isOutputBinary() const
Determine whether the output of this consumer is binary.
Options for controlling the target.
Manage memory buffers across multiple users.
SourceLocation mapLocationToPreamble(SourceLocation Loc) const
If Loc is a local location of the main file but inside the preamble chunk, returns the corresponding ...
void addRemappedFile(StringRef From, StringRef To)
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
static void checkAndSanitizeDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SourceManager &SM)
Code completion occurred within the instance variable list of an Objective-C interface, implementation, or category implementation.
void AddTypedTextChunk(const char *Text)
Add a new typed-text chunk.
Describes how types, statements, expressions, and declarations should be printed. ...
bool hasSourceManager() const
This interface provides a way to observe the actions of the preprocessor as it does its thing...
Parse and apply any fixits to the source.
static std::unique_ptr< ASTUnit > create(std::shared_ptr< CompilerInvocation > CI, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, bool CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
Types, declared with 'struct foo', typedefs, etc.
std::vector< std::pair< unsigned, unsigned > > Ranges
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
The virtual file system interface.
One of these records is kept for each identifier that is lexed.
CodeCompletionString * TakeString()
Take the resulting completion string.
cached_completion_iterator cached_completion_end()
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
SourceLocation getBegin() const
Iteration over the preprocessed entities.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Utility class for loading a ASTContext from an AST file.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
SkipFunctionBodiesScope
Enumerates the available scopes for skipping function bodies.
A "string" used to describe how code completion can be performed for an entity.
static std::atomic< unsigned > ActiveASTUnitObjects
Tracks the number of ASTUnit objects that are currently active.
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
static llvm::ErrorOr< PrecompiledPreamble > Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr< vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHContainerOps, bool StoreInMemory, PreambleCallbacks &Callbacks)
Try to build PrecompiledPreamble for Invocation.
static bool moveOnNoError(llvm::ErrorOr< T > Val, T &Output)
Kind getKind() const
Retrieve the kind of code-completion context.
Token - This structure provides full information about a lexed token.
bool isInPreambleFileID(SourceLocation Loc) const
std::unique_ptr< llvm::MemoryBuffer > getBufferForFile(StringRef Filename, std::string *ErrorStr=nullptr)
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
bool BeforePreviousInsertions
std::shared_ptr< Preprocessor > getPreprocessorPtr()
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Compiling a module from a module map.
Describes a module or submodule.
StringRef getMainFileName() const
unsigned IncludeCodePatterns
Show code patterns in code completion results.
An allocator used specifically for the purpose of code completion.
DiagnosticsEngine::Level Level
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
Load the AST, but do not restore Sema state.
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
void setPreprocessor(std::shared_ptr< Preprocessor > pp)
Divide by this factor when a code-completion result's type exactly matches the type we expect...
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
Namespaces, declared with 'namespace foo {}'.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
const FileEntry * getPCHFile()
Get the PCH file if one was included.
Code completion occurred where a preprocessor directive is expected.
bool serialize(raw_ostream &OS)
Serialize this translation unit with the given output stream.
Concrete class used by the front-end to report problems and issues.
virtual CodeCompletionTUInfo & getCodeCompletionTUInfo()=0
Code completion occurred within an Objective-C implementation or category implementation.
ArrayRef< CharSourceRange > getRanges() const
Defines the Diagnostic-related interfaces.
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
unsigned SkipFunctionBodies
Skip over function bodies to speed up parsing in cases you do not need them (e.g. ...
void addFileLevelDecl(Decl *D)
Add a new local file-level declaration.
QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression...
Code completion occurred where a namespace or namespace alias is expected.
ASTDeserializationListener * getDeserializationListener()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
const LangOptions & getLangOpts() const
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag)
StringRef getMessage() const
void Reset()
Reset the state of the diagnostic object to its initial configuration.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
The AST file itself appears corrupted.
std::vector< std::pair< std::string, llvm::MemoryBuffer * > > RemappedFileBuffers
The set of file-to-buffer remappings, which take existing files on the system (the first part of each...
FrontendOptions & getFrontendOpts()
A set of callbacks to gather useful information while building a preamble.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Code completion where an Objective-C category name is expected.
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static void checkAndRemoveNonDriverDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiags)
Sema - This implements semantic analysis and AST building for C.
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope...
static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash)
Add the given macro to the hash of all top-level entities.
This declaration is a C++ operator declared in a non-class context.
bool isModuleFile() const
Returns true if the ASTUnit was constructed from a serialized module file.
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
Code completion occurred where a protocol name is expected.
Allows QualTypes to be sorted and hence used in maps and sets.
CommentOptions CommentOpts
Options for parsing comments.
QualType getPreferredType() const
Retrieve the type that this expression would prefer to have, e.g., if the expression is a variable in...
CodeCompletionTUInfo & getCodeCompletionTUInfo()
IntrusiveRefCntPtr< ASTReader > getASTReader() const
Defines the clang::LangOptions interface.
bool isMainFileAST() const
Code completion occurred where a new name is expected.
Represents a character-granular source range.
DiagnosticsEngine::Level getLevel() const
llvm::StringRef getAsString(SyncScope S)
std::pair< unsigned, unsigned > RemoveRange
static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash)
Add the given declaration to the hash of all top-level entities.
unsigned & getCurrentTopLevelHashValue()
Retrieve a reference to the current top-level name hash value.
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror...
const AnnotatedLine * Line
ArrayRef< FixItHint > getFixIts() const
std::vector< StandaloneFixIt > FixIts
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
Defines the clang::Preprocessor interface.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
const NamedDecl * Declaration
When Kind == RK_Declaration or RK_Pattern, the declaration we are referring to.
bool isFileContext() const
comments::CommandTraits & getCommentCommandTraits() const
const SourceManager & getManager() const
DeclContext * getDeclContext()
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Information about a module that has been loaded by the ASTReader.
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
Captures a result of code completion.
Code completion occurred where a new name is expected and a qualified name is permissible.
static unsigned getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier)
Determine the set of code-completion contexts in which this declaration should be shown...
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
std::string FileName
The file name of the module file.
bool BeforePreviousInsertions
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts, llvm::MemoryBuffer *Buffer, unsigned MaxLines)
Runs lexer to compute suggested preamble bounds.
SmallString< 128 > Buffer
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, const LangOptions &LangOpts, const FixItHint &InFix)
top_level_iterator top_level_begin()
std::unique_ptr< CompilerInvocation > createInvocationFromCommandLine(ArrayRef< const char *> Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >(), IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
createInvocationFromCommandLine - Construct a compiler invocation object for a command line argument ...
The result type of a method or function.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
The client can't handle any AST loading failures.
The AST file was missing.
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
unsigned getNumWarnings() const
std::unique_ptr< Sema > takeSema()
static CharSourceRange getCharRange(SourceRange R)
The context in which code completion occurred, so that the code-completion consumer can process the r...
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
unsigned getFileOffset(SourceLocation SpellingLoc) const
Returns the offset from the start of the file that the specified SourceLocation represents.
Abstract interface for external sources of AST nodes.
static void CalculateHiddenNames(const CodeCompletionContext &Context, CodeCompletionResult *Results, unsigned NumResults, ASTContext &Ctx, llvm::StringSet< llvm::BumpPtrAllocator > &HiddenNames)
Helper function that computes which global names are hidden by the local code-completion results...
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
The control block was read successfully.
bool hasPreprocessor() const
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...
Code completion occurred within a class, struct, or union.
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles=None, IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
Reparse the source files using the same command-line options that were originally used to produce thi...
SourceLocation mapLocationFromPreamble(SourceLocation Loc) const
If Loc is a loaded location from the preamble, returns the corresponding local location of the main f...
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
bool Execute()
Set the source manager's main input file, and run the action.
bool isInMainFileID(SourceLocation Loc) const
Members, declared with object declarations within tag definitions.
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
ASTWriterData(MemoryBufferCache &PCMCache)
llvm::StringMap< unsigned > & getCachedCompletionTypes()
Retrieve the mapping from formatted type names to unique type identifiers.
std::vector< FrontendInputFile > Inputs
The input files and their types.
void CodeComplete(StringRef File, unsigned Line, unsigned Column, ArrayRef< RemappedFile > RemappedFiles, bool IncludeMacros, bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr< PCHContainerOperations > PCHContainerOps, DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, FileManager &FileMgr, SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SmallVectorImpl< const llvm::MemoryBuffer *> &OwnedBuffers)
Perform code completion at the given file, line, and column within this translation unit...
IdentifierInfo * getIdentifierInfo() const
Cached information about one file (either on disk or in the virtual file system). ...
Code completion where the name of an Objective-C class is expected.
std::vector< CachedCodeCompletionResult >::iterator cached_completion_iterator
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Abstract base class to use for AST consumer-based frontend actions.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location...
Code completion occurred within an Objective-C interface, protocol, or category interface.
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates)
Defines the clang::TargetOptions class.
DiagnosticOptions & getDiagnosticOpts() const
static std::pair< unsigned, unsigned > makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
bool isAnyPointerType() const
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
void setListener(std::unique_ptr< ASTReaderListener > Listener)
Set the AST callbacks listener.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
SourceManager & getSourceManager() const
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
llvm::BitstreamWriter Stream
TranslationUnitKind getTranslationUnitKind() const
Determine what kind of translation unit this AST represents.
void setNumWarnings(unsigned NumWarnings)
The AST file was writtten with a different language/target configuration.
bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn)
Iterate over local declarations (locally parsed if this is a parsed source file or the loaded declara...
File is a PCH file treated as the actual main file.
static ASTUnit * LoadFromCompilerInvocationAction(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, FrontendAction *Action=nullptr, ASTUnit *Unit=nullptr, bool Persistent=true, StringRef ResourceFilesPath=StringRef(), bool OnlyLocalDecls=false, bool CaptureDiagnostics=false, unsigned PrecompilePreambleAfterNParses=0, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=false, bool UserFilesAreVolatile=false, std::unique_ptr< ASTUnit > *ErrAST=nullptr)
Create an ASTUnit from a source file, via a CompilerInvocation object, by invoking the optionally pro...
virtual StringRef getFormat() const =0
Equivalent to the format passed to -fmodule-format=.
StringRef getName() const
Return the actual identifier string.
Abstract interface for a consumer of code-completion information.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Options controlling the behavior of code completion.
static ASTUnit::StandaloneDiagnostic makeStandaloneDiagnostic(const LangOptions &LangOpts, const StoredDiagnostic &InDiag)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
Code completion occurred where an macro is being defined.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
bool hasInvocation() const
PreprocessorOptions & getPreprocessorOpts()
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name...
llvm::iterator_range< PreprocessingRecord::iterator > getLocalPreprocessingEntities() const
Returns an iterator range for the local preprocessing entities of the local Preprocessor, if this is a parsed source file, or the loaded preprocessing entities of the primary module if this is an AST file.
Reads an AST files chain containing the contents of a translation unit.
const FullSourceLoc & getLocation() const
Code completion occurred after the "union" keyword, to indicate a union name.
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
bool(*)(void *context, const Decl *D) DeclVisitorFn
Type for a function iterating over a number of declarations.
bool includeFixIts() const
Whether to include completion items with small fix-its, e.g.
A builder class used to construct new code-completion strings.
Code completion where an Objective-C instance message is expected.
DeclarationName - The name of a declaration.
ASTMutationListener * getASTMutationListener()
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
void enableSourceFileDiagnostics()
Enable source-range based diagnostic messages.
bool SingleFileParseMode
When enabled, preprocessor is in a mode for parsing a single file only.
Helper class for holding the data necessary to invoke the compiler.
const HeaderSearchOptions & getHeaderSearchOpts() const
Defines the virtual file system interface vfs::FileSystem.
SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const
If Loc points inside a function macro argument, the returned location will be the macro location in w...
top_level_iterator top_level_end()
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
A map from continuous integer ranges to some value, with a very specialized interface.
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
FrontendOptions - Options for controlling the behavior of the frontend.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl *> &Decls)
Get the decls that are contained in a file in the Offset/Length range.
Code completion occurred where a statement (or declaration) is expected in a function, method, or block.
Code completion occurred on the right-hand side of an Objective-C property access expression...
bool Save(StringRef File)
Save this translation unit to a file with the given name.
cached_completion_iterator cached_completion_begin()
Abstract interface for callback invocations by the ASTReader.
SourceLocation getEndOfPreambleFileID() const
TargetInfo & getTarget() const
CodeCompleteOptions CodeCompleteOpts
unsigned Size
Size of the preamble in bytes.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
This is a convenience method that opens a file, gets its content and then closes the file...
SourceLocation getEnd() const
const ASTContext & getASTContext() const
Defines the PPCallbacks interface.
bool hasASTContext() const
Keeps track of options that affect how file operations are performed.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl< char > &Buffer, Sema &S, bool hasErrors, raw_ostream &OS)
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Code completion occurred within a preprocessor expression.
Code completion occurred where an expression is expected.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Defines the clang::SourceLocation class and associated facilities.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
const DiagnosticsEngine & getDiagnostics() const
Priority for a nested-name-specifier.
virtual CodeCompletionAllocator & getAllocator()=0
Retrieve the allocator that will be used to allocate code completion strings.
DiagnosticsEngine & getDiagnostics() const
const SourceManager & getSourceManager() const
An unspecified code-completion context where we should also add macro completions.
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
unsigned IncludeFixIts
Include results after corrections (small fix-its), e.g.
Level
The level of the diagnostic, after it has been through mapping.
ASTFileSignature WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors=false)
Write a precompiled header for the given semantic analysis.
TranslationUnitKind
Describes the kind of translation unit being processed.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Writes an AST file containing the contents of a translation unit.
serialization::DeclID getDeclID(const Decl *D)
Determine the declaration ID of an already-emitted declaration.
bool hadModuleLoaderFatalFailure() const
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Defines the clang::TargetInfo interface.
The AST file is out-of-date relative to its input files, and needs to be regenerated.
A SourceLocation and its associated SourceManager.
The translation unit is a complete translation unit.
static std::unique_ptr< llvm::MemoryBuffer > getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, vfs::FileSystem *VFS, StringRef FilePath, bool isVolatile)
Get a source buffer for MainFilePath, handling all file-to-file and file-to-buffer remappings inside ...
SourceLocation getStartOfMainFileID() const
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
unsigned LoadExternal
Hint whether to load data from the external AST to provide full results.
The AST file was written by a different version of Clang.
Code completion occurred on the right-hand side of a member access expression using the dot operator...
void clearRemappedFiles()
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion...
Code completion occurred where a type name is expected.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
unsigned IncludeMacros
Show macros in code completion results.
This represents a decl that may have a name.
bool isTranslationUnit() const
LangOptions * getLangOpts()
InputKind getInputKind() const
Determine the input kind this AST unit represents.
virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr)
Callback to inform the diagnostic client that processing of a source file is beginning.
Priority for a code pattern.
const FileEntry * File
The file entry for the module file.
const LangOptions & getLangOpts() const
SourceLocation getLocation(const FileEntry *File, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
This class handles loading and caching of source files into memory.
SourceLocation getLocation() const
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
std::vector< Decl * >::iterator top_level_iterator