66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/IntrusiveRefCntPtr.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallString.h" 73 #include "llvm/ADT/SmallVector.h" 74 #include "llvm/ADT/StringMap.h" 75 #include "llvm/ADT/StringRef.h" 76 #include "llvm/ADT/StringSet.h" 77 #include "llvm/ADT/Twine.h" 78 #include "llvm/ADT/iterator_range.h" 79 #include "llvm/Bitcode/BitstreamWriter.h" 80 #include "llvm/Support/Allocator.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CrashRecoveryContext.h" 83 #include "llvm/Support/DJB.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/ErrorOr.h" 86 #include "llvm/Support/FileSystem.h" 87 #include "llvm/Support/MemoryBuffer.h" 88 #include "llvm/Support/Mutex.h" 89 #include "llvm/Support/Timer.h" 90 #include "llvm/Support/VirtualFileSystem.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>
158 llvm::vfs::FileSystem *VFS,
159 StringRef FilePath,
bool isVolatile) {
165 llvm::MemoryBuffer *Buffer =
nullptr;
166 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
167 auto FileStatus = VFS->status(FilePath);
169 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
172 for (
const auto &RF : PreprocessorOpts.RemappedFiles) {
173 std::string MPath(RF.first);
174 auto MPathStatus = VFS->status(MPath);
176 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
177 if (MainFileID == MID) {
179 BufferOwner =
valueOrNull(VFS->getBufferForFile(RF.second, -1,
true, isVolatile));
188 for (
const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
189 std::string MPath(RB.first);
190 auto MPathStatus = VFS->status(MPath);
192 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
193 if (MainFileID == MID) {
196 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
203 if (!Buffer && !BufferOwner) {
204 BufferOwner =
valueOrNull(VFS->getBufferForFile(FilePath, -1,
true, isVolatile));
213 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
222 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
225 void ASTUnit::clearFileLevelDecls() {
226 llvm::DeleteContainerSeconds(FileDecls);
240 ASTUnit::ASTUnit(
bool _MainFileIsAST)
241 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv(
"LIBCLANG_TIMING")),
242 ShouldCacheCodeCompletionResults(
false),
243 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
244 UnsafeToFree(
false) {
245 if (getenv(
"LIBCLANG_OBJTRACKING"))
246 fprintf(stderr,
"+++ %u translation units\n", ++ActiveASTUnitObjects);
249 ASTUnit::~ASTUnit() {
255 clearFileLevelDecls();
261 if (Invocation && OwnsRemappedFileBuffers) {
267 ClearCachedCompletionResults();
269 if (getenv(
"LIBCLANG_OBJTRACKING"))
270 fprintf(stderr,
"--- %u translation units\n", --ActiveASTUnitObjects);
274 this->PP = std::move(PP);
279 "Bad context for source file");
287 bool &IsNestedNameSpecifier) {
288 IsNestedNameSpecifier =
false;
290 if (isa<UsingShadowDecl>(ND))
295 uint64_t Contexts = 0;
296 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
297 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
298 isa<TypeAliasTemplateDecl>(ND)) {
300 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
309 if (LangOpts.CPlusPlus)
314 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
318 if (
const auto *
ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
320 if (
ID->getDefinition())
326 if (isa<EnumDecl>(ND)) {
330 if (LangOpts.CPlusPlus11)
331 IsNestedNameSpecifier =
true;
332 }
else if (
const auto *Record = dyn_cast<RecordDecl>(ND)) {
333 if (Record->isUnion())
338 if (LangOpts.CPlusPlus)
339 IsNestedNameSpecifier =
true;
340 }
else if (isa<ClassTemplateDecl>(ND))
341 IsNestedNameSpecifier =
true;
342 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
348 }
else if (isa<ObjCProtocolDecl>(ND)) {
350 }
else if (isa<ObjCCategoryDecl>(ND)) {
352 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
356 IsNestedNameSpecifier =
true;
362 void ASTUnit::CacheCodeCompletionResults() {
366 SimpleTimer Timer(WantTiming);
367 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
370 ClearCachedCompletionResults();
375 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
377 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
381 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
384 for (
auto &R : Results) {
386 case Result::RK_Declaration: {
387 bool IsNestedNameSpecifier =
false;
388 CachedCodeCompletionResult CachedResult;
389 CachedResult.Completion = R.CreateCodeCompletionString(
390 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
391 IncludeBriefCommentsInCodeCompletion);
393 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
394 CachedResult.Priority = R.Priority;
395 CachedResult.Kind = R.CursorKind;
396 CachedResult.Availability = R.Availability;
403 CachedResult.Type = 0;
412 unsigned &TypeValue = CompletionTypes[CanUsageType];
413 if (TypeValue == 0) {
414 TypeValue = CompletionTypes.size();
419 CachedResult.Type = TypeValue;
422 CachedCompletionResults.push_back(CachedResult);
425 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
426 !R.StartsNestedNameSpecifier) {
443 if (isa<NamespaceDecl>(R.Declaration) ||
444 isa<NamespaceAliasDecl>(R.Declaration))
447 if (uint64_t 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 llvm::vfs::getRealFileSystem();
757 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
758 AST->UserFilesAreVolatile = UserFilesAreVolatile;
760 AST->getFileManager(),
761 UserFilesAreVolatile);
763 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
764 AST->HSOpts->ModuleFormat = PCHContainerRdr.
getFormat();
766 AST->getSourceManager(),
767 AST->getDiagnostics(),
770 AST->PPOpts = std::make_shared<PreprocessorOptions>();
780 AST->PP = std::make_shared<Preprocessor>(
781 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
782 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
788 AST->Ctx =
new ASTContext(*AST->LangOpts, AST->getSourceManager(),
789 PP.getIdentifierTable(), PP.getSelectorTable(),
790 PP.getBuiltinInfo());
792 bool disableValid =
false;
793 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
795 AST->Reader =
new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, {},
798 AllowPCHWithCompilerErrors);
800 AST->Reader->
setListener(llvm::make_unique<ASTInfoCollector>(
801 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
802 AST->TargetOpts, AST->Target, Counter));
810 AST->Ctx->setExternalSource(AST->Reader);
823 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
827 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
829 PP.setCounterValue(Counter);
837 AST->TheSema.reset(
new Sema(PP, *AST->Ctx, *AST->Consumer));
838 AST->TheSema->Initialize();
839 AST->Reader->InitializeSema(*AST->TheSema);
843 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
857 class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
861 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) {}
863 void MacroDefined(
const Token &MacroNameTok,
883 if (
const auto *ND = dyn_cast<NamedDecl>(D)) {
884 if (
const auto *EnumD = dyn_cast<EnumDecl>(D)) {
887 if (!EnumD->isScoped()) {
888 for (
const auto *EI : EnumD->enumerators()) {
889 if (EI->getIdentifier())
890 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
895 if (ND->getIdentifier())
896 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
898 std::string NameStr = Name.getAsString();
899 Hash = llvm::djbHash(NameStr, Hash);
904 if (
const auto *ImportD = dyn_cast<ImportDecl>(D)) {
905 if (
const Module *Mod = ImportD->getImportedModule()) {
906 std::string ModName = Mod->getFullModuleName();
907 Hash = llvm::djbHash(ModName, Hash);
915 class TopLevelDeclTrackerConsumer :
public ASTConsumer {
920 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
921 : Unit(_Unit), Hash(Hash) {
925 void handleTopLevelDecl(
Decl *D) {
933 if (isa<ObjCMethodDecl>(D))
939 handleFileLevelDecl(D);
942 void handleFileLevelDecl(
Decl *D) {
944 if (
auto *NSD = dyn_cast<NamespaceDecl>(D)) {
945 for (
auto *I : NSD->decls())
946 handleFileLevelDecl(I);
951 for (
auto *TopLevelDecl : D)
952 handleTopLevelDecl(TopLevelDecl);
959 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
960 for (
auto *TopLevelDecl : D)
961 handleTopLevelDecl(TopLevelDecl);
978 StringRef InFile)
override {
980 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
982 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
987 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
989 bool hasCodeCompletionSupport()
const override {
return false; }
998 unsigned getHash()
const {
return Hash; }
1000 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
1002 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1003 return std::move(TopLevelDeclIDs);
1006 void AfterPCHEmitted(
ASTWriter &Writer)
override {
1007 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1008 for (
const auto *D : TopLevelDecls) {
1010 if (D->isInvalidDecl())
1012 TopLevelDeclIDs.push_back(Writer.
getDeclID(D));
1017 for (
auto *D : DG) {
1022 if (isa<ObjCMethodDecl>(D))
1025 TopLevelDecls.push_back(D);
1029 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
1030 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1035 std::vector<Decl *> TopLevelDecls;
1036 std::vector<serialization::DeclID> TopLevelDeclIDs;
1051 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1063 for (
auto &SD : StoredDiagnostics) {
1064 if (SD.getLocation().isValid()) {
1066 SD.setLocation(Loc);
1076 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1077 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1078 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1082 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1083 if (OverrideMainBuffer) {
1085 "No preamble was built, but OverrideMainBuffer is not null");
1086 IntrusiveRefCntPtr<llvm::vfs::FileSystem> OldVFS = VFS;
1087 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1088 if (OldVFS != VFS && FileMgr) {
1089 assert(OldVFS == FileMgr->getVirtualFileSystem() &&
1090 "VFS passed to Parse and VFS in FileMgr are different");
1091 FileMgr =
new FileManager(FileMgr->getFileSystemOpts(), VFS);
1096 std::unique_ptr<CompilerInstance> Clang(
1098 if (FileMgr && VFS) {
1099 assert(VFS == FileMgr->getVirtualFileSystem() &&
1100 "VFS passed to Parse and VFS in FileMgr are different");
1102 Clang->setVirtualFileSystem(VFS);
1106 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1107 CICleanup(Clang.get());
1109 Clang->setInvocation(CCInvocation);
1110 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1118 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1119 if (!Clang->hasTarget())
1126 Clang->getTarget().adjust(Clang->getLangOpts());
1128 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1129 "Invocation must have exactly one source file!");
1130 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1132 "FIXME: AST inputs not yet supported here!");
1133 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1135 "IR inputs not support here!");
1138 LangOpts = Clang->getInvocation().LangOpts;
1139 FileSystemOpts = Clang->getFileSystemOpts();
1141 Clang->createFileManager();
1142 FileMgr = &Clang->getFileManager();
1148 UserFilesAreVolatile);
1149 if (!OverrideMainBuffer) {
1151 TopLevelDeclsInPreamble.clear();
1162 if (OverrideMainBuffer) {
1171 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1174 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1175 new TopLevelDeclTrackerAction(*
this));
1178 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1179 ActCleanup(Act.get());
1181 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1184 if (SavedMainFileBuffer)
1186 PreambleDiagnostics, StoredDiagnostics);
1188 PreambleSrcLocCache.clear();
1190 if (!Act->Execute())
1193 transferASTDataFromCompilerInstance(*Clang);
1195 Act->EndSourceFile();
1197 FailedParseDiagnostics.clear();
1203 SavedMainFileBuffer =
nullptr;
1207 transferASTDataFromCompilerInstance(*Clang);
1208 FailedParseDiagnostics.swap(StoredDiagnostics);
1209 StoredDiagnostics.clear();
1210 NumStoredDiagnosticsFromDriver = 0;
1214 static std::pair<unsigned, unsigned>
1220 return std::make_pair(Offset, EndOffset);
1251 for (
const auto &Range : InDiag.
getRanges())
1279 std::unique_ptr<llvm::MemoryBuffer>
1280 ASTUnit::getMainBufferWithPrecompiledPreamble(
1281 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1283 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
bool AllowRebuild,
1284 unsigned MaxLines) {
1287 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1289 MainFilePath, UserFilesAreVolatile);
1290 if (!MainFileBuffer)
1295 MainFileBuffer.get(), MaxLines);
1300 if (
Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1311 PreambleRebuildCounter = 1;
1312 return MainFileBuffer;
1315 PreambleDiagnostics.clear();
1316 TopLevelDeclsInPreamble.clear();
1317 PreambleSrcLocCache.clear();
1318 PreambleRebuildCounter = 1;
1325 if (PreambleRebuildCounter > 1) {
1326 --PreambleRebuildCounter;
1330 assert(!
Preamble &&
"No Preamble should be stored at that point");
1338 ASTUnitPreambleCallbacks Callbacks;
1341 if (CaptureDiagnostics)
1342 Capture.emplace(
true, *Diagnostics, &NewPreambleDiags,
1343 &NewPreambleDiagsStandalone);
1346 SimpleTimer PreambleTimer(WantTiming);
1347 PreambleTimer.setOutput(
"Precompiling preamble");
1349 const bool PreviousSkipFunctionBodies =
1355 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1356 PCHContainerOps,
false, Callbacks);
1359 PreviousSkipFunctionBodies;
1362 Preamble = std::move(*NewPreamble);
1363 PreambleRebuildCounter = 1;
1365 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();
1758 VFS = llvm::vfs::getRealFileSystem();
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,
1936 unsigned NumResults,
1938 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1939 bool OnlyTagNames =
false;
1964 OnlyTagNames =
true;
1988 for (
unsigned I = 0; I != NumResults; ++I) {
1989 if (Results[I].
Kind != Result::RK_Declaration)
1995 bool Hiding =
false;
2004 Hiding = (IDNS & HiddenIDNS);
2018 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2021 unsigned NumResults) {
2023 bool AddedResult =
false;
2024 uint64_t InContexts =
2026 ? NormalContexts : (1LL << Context.
getKind());
2028 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2037 if ((
C->ShowInContexts & InContexts) == 0)
2044 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2051 HiddenNames.count(
C->Completion->getTypedText()))
2055 unsigned Priority =
C->Priority;
2062 }
else if (
C->Type) {
2067 if (ExpectedSTC ==
C->TypeClass) {
2069 llvm::StringMap<unsigned> &CachedCompletionTypes
2071 llvm::StringMap<unsigned>::iterator Pos
2073 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2093 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2100 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2104 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2109 StringRef File,
unsigned Line,
unsigned Column,
2111 bool IncludeCodePatterns,
bool IncludeBriefComments,
2113 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2120 SimpleTimer CompletionTimer(WantTiming);
2121 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2122 Twine(Line) +
":" + Twine(Column));
2124 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2131 CachedCompletionResults.empty();
2133 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2138 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2145 LangOpts = *CCInvocation->getLangOpts();
2148 LangOpts.SpellChecking =
false;
2149 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2151 std::unique_ptr<CompilerInstance> Clang(
2155 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2156 CICleanup(Clang.get());
2158 auto &Inv = *CCInvocation;
2159 Clang->setInvocation(std::move(CCInvocation));
2160 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2163 Clang->setDiagnostics(&Diag);
2164 CaptureDroppedDiagnostics
Capture(
true,
2165 Clang->getDiagnostics(),
2166 &StoredDiagnostics,
nullptr);
2171 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2172 if (!Clang->hasTarget()) {
2173 Clang->setInvocation(
nullptr);
2181 Clang->getTarget().adjust(Clang->getLangOpts());
2183 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2184 "Invocation must have exactly one source file!");
2185 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2187 "FIXME: AST inputs not yet supported here!");
2188 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2190 "IR inputs not support here!");
2193 Clang->setFileManager(&FileMgr);
2194 Clang->setSourceManager(&SourceMgr);
2206 AugmentedCodeCompleteConsumer *AugmentedConsumer
2207 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2208 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2214 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2216 std::string CompleteFilePath(File);
2219 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2220 if (CompleteFileStatus) {
2221 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2223 std::string MainPath(OriginalSourceFile);
2224 auto MainStatus = VFS->status(MainPath);
2226 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2227 if (CompleteFileID == MainID && Line > 1)
2228 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2229 PCHContainerOps, Inv, VFS,
false, Line - 1);
2236 if (OverrideMainBuffer) {
2238 "No preamble was built, but OverrideMainBuffer is not null");
2241 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2242 OverrideMainBuffer.get());
2247 OwnedBuffers.push_back(OverrideMainBuffer.release());
2254 if (!Clang->getLangOpts().Modules)
2257 std::unique_ptr<SyntaxOnlyAction> Act;
2259 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2261 Act->EndSourceFile();
2266 if (HadModuleLoaderFatalFailure)
2273 TempPath +=
"-%%%%%%%%";
2275 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2280 llvm::raw_fd_ostream Out(fd,
true);
2284 if (Out.has_error()) {
2289 if (llvm::sys::fs::rename(TempPath, File)) {
2290 llvm::sys::fs::remove(TempPath);
2302 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2305 if (!Buffer.empty())
2306 OS.write(Buffer.data(), Buffer.size());
2316 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2320 llvm::BitstreamWriter Stream(Buffer);
2322 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2328 void ASTUnit::TranslateStoredDiagnostics(
2338 Result.reserve(Diags.size());
2340 for (
const auto &SD : Diags) {
2342 if (SD.Filename.empty())
2348 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2349 if (ItFileID == PreambleSrcLocCache.end()) {
2352 PreambleSrcLocCache[SD.Filename] = FileLoc;
2354 FileLoc = ItFileID->getValue();
2363 Ranges.reserve(SD.Ranges.size());
2364 for (
const auto &Range : SD.Ranges) {
2371 FixIts.reserve(SD.FixIts.size());
2372 for (
const auto &
FixIt : SD.FixIts) {
2382 SD.Message, Loc, Ranges, FixIts));
2408 if (FID.isInvalid())
2415 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2417 if (Decls->empty() || Decls->back().first <=
Offset) {
2418 Decls->push_back(LocDecl);
2422 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2423 LocDecl, llvm::less_first());
2425 Decls->insert(I, LocDecl);
2433 if (SourceMgr->isLoadedFileID(File)) {
2434 assert(Ctx->getExternalSource() &&
"No external source!");
2435 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2439 FileDeclsTy::iterator I = FileDecls.find(File);
2440 if (I == FileDecls.end())
2444 if (LocDecls.empty())
2447 LocDeclsTy::iterator BeginIt =
2448 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2449 std::make_pair(Offset, (
Decl *)
nullptr),
2450 llvm::less_first());
2451 if (BeginIt != LocDecls.begin())
2457 while (BeginIt != LocDecls.begin() &&
2458 BeginIt->second->isTopLevelDeclInObjCContainer())
2461 LocDeclsTy::iterator EndIt = std::upper_bound(
2462 LocDecls.begin(), LocDecls.end(),
2463 std::make_pair(Offset + Length, (
Decl *)
nullptr), llvm::less_first());
2464 if (EndIt != LocDecls.end())
2467 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2468 Decls.push_back(DIt->second);
2472 unsigned Line,
unsigned Col)
const {
2491 PreambleID = SourceMgr->getPreambleFileID();
2497 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs <
Preamble->getBounds().Size) {
2499 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2512 PreambleID = SourceMgr->getPreambleFileID();
2518 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2519 Offs < Preamble->getBounds().Size) {
2520 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2530 FID = SourceMgr->getPreambleFileID();
2535 return SourceMgr->isInFileID(Loc, FID);
2541 FID = SourceMgr->getMainFileID();
2546 return SourceMgr->isInFileID(Loc, FID);
2552 FID = SourceMgr->getPreambleFileID();
2557 return SourceMgr->getLocForEndOfFile(FID);
2563 FID = SourceMgr->getMainFileID();
2568 return SourceMgr->getLocForStartOfFile(FID);
2571 llvm::iterator_range<PreprocessingRecord::iterator>
2575 Mod = Reader->getModuleManager().getPrimaryModule();
2576 return Reader->getModulePreprocessedEntities(Mod);
2580 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2589 Mod = Reader->getModuleManager().getPrimaryModule();
2590 for (
const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2591 if (!Fn(context, D))
2600 TL != TLEnd; ++TL) {
2601 if (!Fn(context, *TL))
2615 case serialization::MK_ImplicitModule:
2616 case serialization::MK_ExplicitModule:
2617 case serialization::MK_PrebuiltModule:
2619 case serialization::MK_PCH:
2622 case serialization::MK_Preamble:
2624 case serialization::MK_MainFile:
2644 if (LangOpts.OpenCL)
2646 else if (LangOpts.CUDA)
2648 else if (LangOpts.RenderScript)
2650 else if (LangOpts.CPlusPlus)
2666 ASTUnit::ConcurrencyState::ConcurrencyState() {
2667 Mutex =
new llvm::sys::MutexImpl(
true);
2670 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2671 delete static_cast<llvm::sys::MutexImpl *
>(Mutex);
2674 void ASTUnit::ConcurrencyState::start() {
2675 bool acquired =
static_cast<llvm::sys::MutexImpl *
>(Mutex)->tryacquire();
2676 assert(acquired &&
"Concurrent access to ASTUnit!");
2679 void ASTUnit::ConcurrencyState::finish() {
2680 static_cast<llvm::sys::MutexImpl *
>(Mutex)->release();
2685 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2686 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2687 void ASTUnit::ConcurrencyState::start() {}
2688 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...
Code completion occurred where an existing name(such as type, function or variable) is expected...
unsigned IncludeGlobals
Show top-level decls in code completion results.
Priority for a code pattern.
unsigned getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer=false)
Determine the priority to be given to a macro code completion result with the given name...
Code completion where an Objective-C class message is expected.
C Language Family Type Representation.
Defines the SourceManager interface.
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.
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.
Code completion occurred where both a new name and an existing symbol is permissible.
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.
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 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.
Divide by this factor when a code-completion result's type exactly matches the type we expect...
An allocator used specifically for the purpose of code completion.
DiagnosticsEngine::Level Level
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)
std::unique_ptr< CompilerInvocation > createInvocationFromCommandLine(ArrayRef< const char *> Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >(), IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
createInvocationFromCommandLine - Construct a compiler invocation object for a command line argument ...
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.
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates, SourceLocation OpenParLoc)
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
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
Retrieve the human-readable string for this name.
Defines the clang::Preprocessor interface.
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
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
Captures a result of code completion.
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()
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.
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
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...
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.
Code completion occurred where a new name is expected.
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.
Defines the clang::TargetOptions class.
DiagnosticOptions & getDiagnosticOpts() const
static std::pair< unsigned, unsigned > makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
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< llvm::vfs::FileSystem > VFS=nullptr)
LoadFromCommandLine - Create an ASTUnit from a vector of command line arguments, which must specify e...
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...
StringRef getName() const
Return the actual identifier string.
Priority for a nested-name-specifier.
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.
virtual llvm::StringRef getFormat() const =0
Equivalent to the format passed to -fmodule-format=.
bool isValid() const
Return true if this is a valid SourceLocation object.
static std::unique_ptr< llvm::MemoryBuffer > getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, llvm::vfs::FileSystem *VFS, StringRef FilePath, bool isVolatile)
Get a source buffer for MainFilePath, handling all file-to-file and file-to-buffer remappings inside ...
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...
static uint64_t getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier)
Determine the set of code-completion contexts in which this declaration should be shown...
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.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
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.
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
SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const
If Loc points inside a function macro argument, the returned location will be the macro location in w...
top_level_iterator top_level_end()
A map from continuous integer ranges to some value, with a very specialized interface.
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
FrontendOptions - Options for controlling the behavior of the frontend.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl *> &Decls)
Get the decls that are contained in a file in the Offset/Length range.
Code completion occurred where a statement (or declaration) is expected in a function, method, or block.
static llvm::ErrorOr< PrecompiledPreamble > Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHContainerOps, bool StoreInMemory, PreambleCallbacks &Callbacks)
Try to build PrecompiledPreamble for Invocation.
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.
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles=None, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Reparse the source files using the same command-line options that were originally used to produce thi...
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.
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
Code completion inside the filename part of a #include directive.
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.
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.
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.
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.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystem() const
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