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/Bitstream/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/FileUtilities.h" 88 #include "llvm/Support/MemoryBuffer.h" 89 #include "llvm/Support/Timer.h" 90 #include "llvm/Support/VirtualFileSystem.h" 91 #include "llvm/Support/raw_ostream.h" 105 using namespace clang;
107 using llvm::TimeRecord;
117 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
119 Start = TimeRecord::getCurrentTime();
124 TimeRecord Elapsed = TimeRecord::getCurrentTime();
126 llvm::errs() << Output <<
':';
127 Elapsed.print(Elapsed, llvm::errs());
128 llvm::errs() <<
'\n';
132 void setOutput(
const Twine &Output) {
134 this->Output = Output.str();
141 static std::unique_ptr<T>
valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
144 return std::move(*Val);
151 Output = std::move(*Val);
157 static std::unique_ptr<llvm::MemoryBuffer>
159 llvm::vfs::FileSystem *VFS,
160 StringRef FilePath,
bool isVolatile) {
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) {
180 BufferOwner =
valueOrNull(VFS->getBufferForFile(RF.second, -1,
true, isVolatile));
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) {
205 BufferOwner =
valueOrNull(VFS->getBufferForFile(FilePath, -1,
true, isVolatile));
214 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
223 : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
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 (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);
615 bool CaptureNonErrorsFromIncludes =
true;
620 FilterAndStoreDiagnosticConsumer(
623 bool CaptureNonErrorsFromIncludes)
624 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
625 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
626 assert((StoredDiags || StandaloneDiags) &&
627 "No output collections were passed to StoredDiagnosticConsumer.");
632 this->LangOpts = &LangOpts;
634 SourceMgr = &PP->getSourceManager();
643 class CaptureDroppedDiagnostics {
645 FilterAndStoreDiagnosticConsumer Client;
647 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
650 CaptureDroppedDiagnostics(
655 Client(StoredDiags, StandaloneDiags,
656 CaptureDiagnostics !=
666 ~CaptureDroppedDiagnostics() {
668 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
686 void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
702 StoredDiags->emplace_back(Level, Info);
703 ResultDiag = &StoredDiags->back();
706 if (StandaloneDiags) {
709 StoredDiag.emplace(Level, Info);
710 ResultDiag = StoredDiag.getPointer();
712 StandaloneDiags->push_back(
724 return &WriterData->Writer;
730 return &WriterData->Writer;
734 std::unique_ptr<llvm::MemoryBuffer>
737 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
739 return std::move(*Buffer);
741 *ErrorStr = Buffer.getError().message();
749 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
751 Diags->setClient(
new FilterAndStoreDiagnosticConsumer(
752 &AST.StoredDiagnostics,
nullptr,
762 bool UserFilesAreVolatile) {
763 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
766 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
767 ASTUnitCleanup(AST.get());
769 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
770 DiagCleanup(Diags.get());
772 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
774 AST->LangOpts = std::make_shared<LangOptions>();
775 AST->OnlyLocalDecls = OnlyLocalDecls;
776 AST->CaptureDiagnostics = CaptureDiagnostics;
777 AST->Diagnostics = Diags;
779 llvm::vfs::getRealFileSystem();
780 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
781 AST->UserFilesAreVolatile = UserFilesAreVolatile;
783 AST->getFileManager(),
784 UserFilesAreVolatile);
786 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
787 AST->HSOpts->ModuleFormat = PCHContainerRdr.
getFormat();
789 AST->getSourceManager(),
790 AST->getDiagnostics(),
793 AST->PPOpts = std::make_shared<PreprocessorOptions>();
803 AST->PP = std::make_shared<Preprocessor>(
804 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
805 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
811 AST->Ctx =
new ASTContext(*AST->LangOpts, AST->getSourceManager(),
812 PP.getIdentifierTable(), PP.getSelectorTable(),
813 PP.getBuiltinInfo());
815 bool disableValid =
false;
816 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
819 PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
821 disableValid, AllowPCHWithCompilerErrors);
823 AST->Reader->
setListener(std::make_unique<ASTInfoCollector>(
824 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
825 AST->TargetOpts, AST->Target, Counter));
833 AST->Ctx->setExternalSource(AST->Reader);
846 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
850 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
852 PP.setCounterValue(Counter);
860 AST->TheSema.reset(
new Sema(PP, *AST->Ctx, *AST->Consumer));
861 AST->TheSema->Initialize();
862 AST->Reader->InitializeSema(*AST->TheSema);
866 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
880 class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
884 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) {}
886 void MacroDefined(
const Token &MacroNameTok,
906 if (
const auto *ND = dyn_cast<NamedDecl>(D)) {
907 if (
const auto *EnumD = dyn_cast<EnumDecl>(D)) {
910 if (!EnumD->isScoped()) {
911 for (
const auto *EI : EnumD->enumerators()) {
912 if (EI->getIdentifier())
913 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
918 if (ND->getIdentifier())
919 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
921 std::string NameStr = Name.getAsString();
922 Hash = llvm::djbHash(NameStr, Hash);
927 if (
const auto *ImportD = dyn_cast<ImportDecl>(D)) {
928 if (
const Module *Mod = ImportD->getImportedModule()) {
929 std::string ModName = Mod->getFullModuleName();
930 Hash = llvm::djbHash(ModName, Hash);
938 class TopLevelDeclTrackerConsumer :
public ASTConsumer {
943 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
944 : Unit(_Unit), Hash(Hash) {
948 void handleTopLevelDecl(
Decl *D) {
956 if (isa<ObjCMethodDecl>(D))
962 handleFileLevelDecl(D);
965 void handleFileLevelDecl(
Decl *D) {
967 if (
auto *NSD = dyn_cast<NamespaceDecl>(D)) {
968 for (
auto *I : NSD->decls())
969 handleFileLevelDecl(I);
974 for (
auto *TopLevelDecl : D)
975 handleTopLevelDecl(TopLevelDecl);
982 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
983 for (
auto *TopLevelDecl : D)
984 handleTopLevelDecl(TopLevelDecl);
1001 StringRef InFile)
override {
1003 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1005 return std::make_unique<TopLevelDeclTrackerConsumer>(
1010 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
1012 bool hasCodeCompletionSupport()
const override {
return false; }
1021 unsigned getHash()
const {
return Hash; }
1023 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
1025 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1026 return std::move(TopLevelDeclIDs);
1029 void AfterPCHEmitted(
ASTWriter &Writer)
override {
1030 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1031 for (
const auto *D : TopLevelDecls) {
1033 if (D->isInvalidDecl())
1035 TopLevelDeclIDs.push_back(Writer.
getDeclID(D));
1040 for (
auto *D : DG) {
1045 if (isa<ObjCMethodDecl>(D))
1048 TopLevelDecls.push_back(D);
1052 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
1053 return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1058 std::vector<Decl *> TopLevelDecls;
1059 std::vector<serialization::DeclID> TopLevelDeclIDs;
1074 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1086 for (
auto &SD : StoredDiagnostics) {
1087 if (SD.getLocation().isValid()) {
1089 SD.setLocation(Loc);
1099 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1100 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1106 assert(VFS == &FileMgr->getVirtualFileSystem() &&
1107 "VFS passed to Parse and VFS in FileMgr are different");
1109 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1110 if (OverrideMainBuffer) {
1112 "No preamble was built, but OverrideMainBuffer is not null");
1113 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1118 std::unique_ptr<CompilerInstance> Clang(
1124 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
1125 Clang->setFileManager(&*FileMgr);
1127 FileMgr = Clang->createFileManager(std::move(VFS));
1130 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1131 CICleanup(Clang.get());
1133 Clang->setInvocation(CCInvocation);
1134 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1142 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1143 if (!Clang->hasTarget())
1150 Clang->getTarget().adjust(Clang->getLangOpts());
1152 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1153 "Invocation must have exactly one source file!");
1154 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1156 "FIXME: AST inputs not yet supported here!");
1157 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1159 "IR inputs not support here!");
1162 LangOpts = Clang->getInvocation().LangOpts;
1163 FileSystemOpts = Clang->getFileSystemOpts();
1168 UserFilesAreVolatile);
1169 if (!OverrideMainBuffer) {
1171 TopLevelDeclsInPreamble.clear();
1182 if (OverrideMainBuffer) {
1191 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1194 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1195 new TopLevelDeclTrackerAction(*
this));
1198 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1199 ActCleanup(Act.get());
1201 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1204 if (SavedMainFileBuffer)
1206 PreambleDiagnostics, StoredDiagnostics);
1208 PreambleSrcLocCache.clear();
1211 consumeError(std::move(Err));
1215 transferASTDataFromCompilerInstance(*Clang);
1217 Act->EndSourceFile();
1219 FailedParseDiagnostics.clear();
1225 SavedMainFileBuffer =
nullptr;
1229 transferASTDataFromCompilerInstance(*Clang);
1230 FailedParseDiagnostics.swap(StoredDiagnostics);
1231 StoredDiagnostics.clear();
1232 NumStoredDiagnosticsFromDriver = 0;
1236 static std::pair<unsigned, unsigned>
1242 return std::make_pair(Offset, EndOffset);
1273 for (
const auto &Range : InDiag.
getRanges())
1301 std::unique_ptr<llvm::MemoryBuffer>
1302 ASTUnit::getMainBufferWithPrecompiledPreamble(
1303 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1306 unsigned MaxLines) {
1309 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1311 MainFilePath, UserFilesAreVolatile);
1312 if (!MainFileBuffer)
1317 MainFileBuffer.get(), MaxLines);
1322 if (
Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1333 PreambleRebuildCountdown = 1;
1334 return MainFileBuffer;
1337 PreambleDiagnostics.clear();
1338 TopLevelDeclsInPreamble.clear();
1339 PreambleSrcLocCache.clear();
1340 PreambleRebuildCountdown = 1;
1347 if (PreambleRebuildCountdown > 1) {
1348 --PreambleRebuildCountdown;
1352 assert(!
Preamble &&
"No Preamble should be stored at that point");
1362 ASTUnitPreambleCallbacks Callbacks;
1366 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1367 &NewPreambleDiagsStandalone);
1370 SimpleTimer PreambleTimer(WantTiming);
1371 PreambleTimer.setOutput(
"Precompiling preamble");
1373 const bool PreviousSkipFunctionBodies =
1379 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1380 PCHContainerOps,
false, Callbacks);
1383 PreviousSkipFunctionBodies;
1386 Preamble = std::move(*NewPreamble);
1387 PreambleRebuildCountdown = 1;
1389 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1392 PreambleRebuildCountdown = 1;
1402 llvm_unreachable(
"unexpected BuildPreambleError");
1406 assert(
Preamble &&
"Preamble wasn't built");
1408 TopLevelDecls.clear();
1409 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1410 PreambleTopLevelHashValue = Callbacks.getHash();
1415 StoredDiagnostics = std::move(NewPreambleDiags);
1416 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1421 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1422 CompletionCacheTopLevelHashValue = 0;
1423 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1426 return MainFileBuffer;
1429 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1430 assert(
Preamble &&
"Should only be called when preamble was built");
1432 std::vector<Decl *> Resolved;
1433 Resolved.reserve(TopLevelDeclsInPreamble.size());
1435 for (
const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1439 Resolved.push_back(D);
1441 TopLevelDeclsInPreamble.clear();
1442 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1465 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1470 return Input.
getBuffer()->getBufferIdentifier();
1475 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1476 return FE->getName();
1487 Mod = Reader->getModuleManager().getPrimaryModule();
1491 std::unique_ptr<ASTUnit>
1495 bool UserFilesAreVolatile) {
1496 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1497 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1500 AST->Diagnostics = Diags;
1501 AST->FileSystemOpts = CI->getFileSystemOpts();
1502 AST->Invocation = std::move(CI);
1503 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1504 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1505 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1506 UserFilesAreVolatile);
1513 std::shared_ptr<CompilerInvocation> CI,
1514 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1516 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1518 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1519 bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile,
1520 std::unique_ptr<ASTUnit> *ErrAST) {
1521 assert(CI &&
"A CompilerInvocation is required");
1523 std::unique_ptr<ASTUnit> OwnAST;
1527 OwnAST =
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1533 if (!ResourceFilesPath.empty()) {
1537 AST->OnlyLocalDecls = OnlyLocalDecls;
1538 AST->CaptureDiagnostics = CaptureDiagnostics;
1539 if (PrecompilePreambleAfterNParses > 0)
1540 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1542 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1543 AST->IncludeBriefCommentsInCodeCompletion
1544 = IncludeBriefCommentsInCodeCompletion;
1547 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1548 ASTUnitCleanup(OwnAST.get());
1550 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1551 DiagCleanup(Diags.get());
1554 CI->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1555 CI->getFrontendOpts().DisableFree =
false;
1559 std::unique_ptr<CompilerInstance> Clang(
1563 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1564 CICleanup(Clang.get());
1566 Clang->setInvocation(std::move(CI));
1567 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1575 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1576 if (!Clang->hasTarget())
1583 Clang->getTarget().adjust(Clang->getLangOpts());
1585 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1586 "Invocation must have exactly one source file!");
1587 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1589 "FIXME: AST inputs not yet supported here!");
1590 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1592 "IR inputs not support here!");
1595 AST->TheSema.reset();
1598 AST->Reader =
nullptr;
1608 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1610 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1611 Act = TrackerAct.get();
1615 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1616 ActCleanup(TrackerAct.get());
1618 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1619 AST->transferASTDataFromCompilerInstance(*Clang);
1620 if (OwnAST && ErrAST)
1621 ErrAST->swap(OwnAST);
1626 if (Persistent && !TrackerAct) {
1627 Clang->getPreprocessor().addPPCallbacks(
1628 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1630 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1631 if (Clang->hasASTConsumer())
1632 Consumers.push_back(Clang->takeASTConsumer());
1633 Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1635 Clang->setASTConsumer(
1636 std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1639 consumeError(std::move(Err));
1640 AST->transferASTDataFromCompilerInstance(*Clang);
1641 if (OwnAST && ErrAST)
1642 ErrAST->swap(OwnAST);
1648 AST->transferASTDataFromCompilerInstance(*Clang);
1653 return OwnAST.release();
1658 bool ASTUnit::LoadFromCompilerInvocation(
1659 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1660 unsigned PrecompilePreambleAfterNParses,
1665 assert(VFS &&
"VFS is null");
1668 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1669 Invocation->getFrontendOpts().DisableFree =
false;
1673 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1674 if (PrecompilePreambleAfterNParses > 0) {
1675 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1676 OverrideMainBuffer =
1677 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1682 SimpleTimer ParsingTimer(WantTiming);
1686 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1687 MemBufferCleanup(OverrideMainBuffer.get());
1689 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1692 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1693 std::shared_ptr<CompilerInvocation> CI,
1694 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1698 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1699 bool UserFilesAreVolatile) {
1701 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1702 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1703 AST->Diagnostics = Diags;
1704 AST->OnlyLocalDecls = OnlyLocalDecls;
1705 AST->CaptureDiagnostics = CaptureDiagnostics;
1706 AST->TUKind = TUKind;
1707 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1708 AST->IncludeBriefCommentsInCodeCompletion
1709 = IncludeBriefCommentsInCodeCompletion;
1710 AST->Invocation = std::move(CI);
1712 AST->FileMgr = FileMgr;
1713 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1716 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1717 ASTUnitCleanup(AST.get());
1719 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1720 DiagCleanup(Diags.get());
1722 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1723 PrecompilePreambleAfterNParses,
1724 &AST->FileMgr->getVirtualFileSystem()))
1730 const char **ArgBegin,
const char **ArgEnd,
1731 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1736 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1738 bool SingleFileParse,
bool UserFilesAreVolatile,
bool ForSerialization,
1739 bool RetainExcludedConditionalBlocks,
1742 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1746 std::shared_ptr<CompilerInvocation> CI;
1749 CaptureDroppedDiagnostics
Capture(CaptureDiagnostics, *Diags,
1750 &StoredDiagnostics,
nullptr);
1753 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1760 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1770 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1772 CI->getFrontendOpts().SkipFunctionBodies =
1776 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1779 std::unique_ptr<ASTUnit> AST;
1780 AST.reset(
new ASTUnit(
false));
1781 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1782 AST->StoredDiagnostics.swap(StoredDiagnostics);
1783 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1784 AST->Diagnostics = Diags;
1785 AST->FileSystemOpts = CI->getFileSystemOpts();
1787 VFS = llvm::vfs::getRealFileSystem();
1789 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1791 AST->OnlyLocalDecls = OnlyLocalDecls;
1792 AST->CaptureDiagnostics = CaptureDiagnostics;
1793 AST->TUKind = TUKind;
1794 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1795 AST->IncludeBriefCommentsInCodeCompletion
1796 = IncludeBriefCommentsInCodeCompletion;
1797 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1798 AST->Invocation = CI;
1799 AST->SkipFunctionBodies = SkipFunctionBodies;
1800 if (ForSerialization)
1801 AST->WriterData.reset(
new ASTWriterData(*AST->ModuleCache));
1807 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1808 ASTUnitCleanup(AST.get());
1810 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1811 PrecompilePreambleAfterNParses,
1816 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1822 return AST.release();
1832 assert(FileMgr &&
"FileMgr is null on Reparse call");
1833 VFS = &FileMgr->getVirtualFileSystem();
1836 clearFileLevelDecls();
1838 SimpleTimer ParsingTimer(WantTiming);
1848 Invocation->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1854 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1855 if (
Preamble || PreambleRebuildCountdown > 0)
1856 OverrideMainBuffer =
1857 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1863 if (OverrideMainBuffer)
1868 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1872 if (!Result && ShouldCacheCodeCompletionResults &&
1873 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1874 CacheCodeCompletionResults();
1884 SavedMainFileBuffer.reset();
1892 TopLevelDecls.clear();
1893 clearFileLevelDecls();
1906 uint64_t NormalContexts;
1939 unsigned NumResults)
override;
1941 void ProcessOverloadCandidates(
Sema &S,
unsigned CurrentArg,
1943 unsigned NumCandidates,
1964 unsigned NumResults,
1966 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1967 bool OnlyTagNames =
false;
1992 OnlyTagNames =
true;
2016 for (
unsigned I = 0; I != NumResults; ++I) {
2017 if (Results[I].
Kind != Result::RK_Declaration)
2023 bool Hiding =
false;
2032 Hiding = (IDNS & HiddenIDNS);
2046 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2049 unsigned NumResults) {
2051 bool AddedResult =
false;
2052 uint64_t InContexts =
2054 ? NormalContexts : (1LL << Context.
getKind());
2056 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2065 if ((
C->ShowInContexts & InContexts) == 0)
2072 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2079 HiddenNames.count(
C->Completion->getTypedText()))
2090 }
else if (
C->Type) {
2095 if (ExpectedSTC ==
C->TypeClass) {
2097 llvm::StringMap<unsigned> &CachedCompletionTypes
2099 llvm::StringMap<unsigned>::iterator Pos
2101 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2121 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2128 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2132 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2137 StringRef File,
unsigned Line,
unsigned Column,
2139 bool IncludeCodePatterns,
bool IncludeBriefComments,
2141 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2148 SimpleTimer CompletionTimer(WantTiming);
2149 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2150 Twine(Line) +
":" + Twine(Column));
2152 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2159 CachedCompletionResults.empty();
2161 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2166 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2173 LangOpts = *CCInvocation->getLangOpts();
2176 LangOpts.SpellChecking =
false;
2177 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2179 std::unique_ptr<CompilerInstance> Clang(
2183 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2184 CICleanup(Clang.get());
2186 auto &Inv = *CCInvocation;
2187 Clang->setInvocation(std::move(CCInvocation));
2188 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2191 Clang->setDiagnostics(&Diag);
2193 Clang->getDiagnostics(),
2194 &StoredDiagnostics,
nullptr);
2199 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2200 if (!Clang->hasTarget()) {
2201 Clang->setInvocation(
nullptr);
2209 Clang->getTarget().adjust(Clang->getLangOpts());
2211 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2212 "Invocation must have exactly one source file!");
2213 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2215 "FIXME: AST inputs not yet supported here!");
2216 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2218 "IR inputs not support here!");
2221 Clang->setFileManager(&FileMgr);
2222 Clang->setSourceManager(&SourceMgr);
2234 AugmentedCodeCompleteConsumer *AugmentedConsumer
2235 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2236 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2242 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2244 std::string CompleteFilePath(File);
2247 auto CompleteFileStatus = VFS.status(CompleteFilePath);
2248 if (CompleteFileStatus) {
2249 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2251 std::string MainPath(OriginalSourceFile);
2252 auto MainStatus = VFS.status(MainPath);
2254 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2255 if (CompleteFileID == MainID && Line > 1)
2256 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2257 PCHContainerOps, Inv, &VFS,
false, Line - 1);
2264 if (OverrideMainBuffer) {
2266 "No preamble was built, but OverrideMainBuffer is not null");
2270 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2271 OverrideMainBuffer.get());
2276 OwnedBuffers.push_back(OverrideMainBuffer.release());
2283 if (!Clang->getLangOpts().Modules)
2286 std::unique_ptr<SyntaxOnlyAction> Act;
2288 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2290 consumeError(std::move(Err));
2292 Act->EndSourceFile();
2297 if (HadModuleLoaderFatalFailure)
2304 TempPath +=
"-%%%%%%%%";
2309 TempPath, File, [
this](llvm::raw_ostream &Out) {
2310 return serialize(Out) ? llvm::make_error<llvm::StringError>(
2311 "ASTUnit serialization failed",
2312 llvm::inconvertibleErrorCode())
2313 : llvm::Error::success();
2315 consumeError(std::move(Err));
2326 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2329 if (!Buffer.empty())
2330 OS.write(Buffer.data(), Buffer.size());
2340 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2344 llvm::BitstreamWriter Stream(Buffer);
2346 ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2352 void ASTUnit::TranslateStoredDiagnostics(
2362 Result.reserve(Diags.size());
2364 for (
const auto &SD : Diags) {
2366 if (SD.Filename.empty())
2368 auto FE = FileMgr.
getFile(SD.Filename);
2372 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2373 if (ItFileID == PreambleSrcLocCache.end()) {
2376 PreambleSrcLocCache[SD.Filename] = FileLoc;
2378 FileLoc = ItFileID->getValue();
2387 Ranges.reserve(SD.Ranges.size());
2388 for (
const auto &Range : SD.Ranges) {
2395 FixIts.reserve(SD.FixIts.size());
2396 for (
const auto &
FixIt : SD.FixIts) {
2406 SD.Message, Loc, Ranges, FixIts));
2432 if (FID.isInvalid())
2439 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2441 if (Decls->empty() || Decls->back().first <=
Offset) {
2442 Decls->push_back(LocDecl);
2446 LocDeclsTy::iterator I =
2447 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2449 Decls->insert(I, LocDecl);
2457 if (SourceMgr->isLoadedFileID(File)) {
2458 assert(Ctx->getExternalSource() &&
"No external source!");
2459 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2463 FileDeclsTy::iterator I = FileDecls.find(File);
2464 if (I == FileDecls.end())
2468 if (LocDecls.empty())
2471 LocDeclsTy::iterator BeginIt =
2472 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2473 return LD.first <
Offset;
2475 if (BeginIt != LocDecls.begin())
2481 while (BeginIt != LocDecls.begin() &&
2482 BeginIt->second->isTopLevelDeclInObjCContainer())
2485 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2486 LocDecls, std::make_pair(Offset + Length, (
Decl *)
nullptr),
2487 llvm::less_first());
2488 if (EndIt != LocDecls.end())
2491 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2492 Decls.push_back(DIt->second);
2496 unsigned Line,
unsigned Col)
const {
2515 PreambleID = SourceMgr->getPreambleFileID();
2521 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs <
Preamble->getBounds().Size) {
2523 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2536 PreambleID = SourceMgr->getPreambleFileID();
2542 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2543 Offs < Preamble->getBounds().Size) {
2544 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2554 FID = SourceMgr->getPreambleFileID();
2559 return SourceMgr->isInFileID(Loc, FID);
2565 FID = SourceMgr->getMainFileID();
2570 return SourceMgr->isInFileID(Loc, FID);
2576 FID = SourceMgr->getPreambleFileID();
2581 return SourceMgr->getLocForEndOfFile(FID);
2587 FID = SourceMgr->getMainFileID();
2592 return SourceMgr->getLocForStartOfFile(FID);
2595 llvm::iterator_range<PreprocessingRecord::iterator>
2599 Mod = Reader->getModuleManager().getPrimaryModule();
2600 return Reader->getModulePreprocessedEntities(Mod);
2604 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2613 Mod = Reader->getModuleManager().getPrimaryModule();
2614 for (
const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2615 if (!Fn(context, D))
2624 TL != TLEnd; ++TL) {
2625 if (!Fn(context, *TL))
2639 case serialization::MK_ImplicitModule:
2640 case serialization::MK_ExplicitModule:
2641 case serialization::MK_PrebuiltModule:
2643 case serialization::MK_PCH:
2646 case serialization::MK_Preamble:
2648 case serialization::MK_MainFile:
2668 if (LangOpts.OpenCL)
2670 else if (LangOpts.CUDA)
2672 else if (LangOpts.RenderScript)
2674 else if (LangOpts.CPlusPlus)
2690 ASTUnit::ConcurrencyState::ConcurrencyState() {
2691 Mutex =
new std::recursive_mutex;
2694 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2695 delete static_cast<std::recursive_mutex *
>(Mutex);
2698 void ASTUnit::ConcurrencyState::start() {
2699 bool acquired =
static_cast<std::recursive_mutex *
>(Mutex)->try_lock();
2700 assert(acquired &&
"Concurrent access to ASTUnit!");
2703 void ASTUnit::ConcurrencyState::finish() {
2704 static_cast<std::recursive_mutex *
>(Mutex)->unlock();
2709 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2710 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2711 void ASTUnit::ConcurrencyState::start() {}
2712 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()
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
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.
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.
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.
static std::unique_ptr< ASTUnit > create(std::shared_ptr< CompilerInvocation > CI, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, CaptureDiagsKind CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
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...
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.
Options for controlling the target.
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
IntrusiveRefCntPtr< ASTReader > getASTReader() 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.
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
Priority for a code pattern.
unsigned IncludeCodePatterns
Show code patterns in code completion results.
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)
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
Namespaces, declared with 'namespace foo {}'.
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, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, bool AllowPCHWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
const SourceLocation & getLocation() const
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.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
CaptureDiagsKind
Enumerates the available kinds for capturing diagnostics.
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.
Priority for a nested-name-specifier.
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)
Languages that the frontend can parse and compile.
Language
The language for the input, used to select and validate the language standard and possible actions...
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.
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...
Divide by this factor when a code-completion result's type exactly matches the type we expect...
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.
ASTFileSignature WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors=false, bool ShouldCacheASTInMemory=false)
Write a precompiled header for the given semantic analysis.
bool isModuleFile() const
Returns true if the ASTUnit was constructed from a serialized module file.
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.
static ASTUnit * LoadFromCommandLine(const char **ArgBegin, const char **ArgEnd, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, StringRef ResourceFilesPath, bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, 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, bool RetainExcludedConditionalBlocks=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 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()
bool isWrittenInMainFile(SourceLocation Loc) const
Returns true if the spelling location for the given location is in the main file buffer.
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.
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.
In-memory cache for modules.
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 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.
llvm::StringMap< unsigned > & getCachedCompletionTypes()
Retrieve the mapping from formatted type names to unique type identifiers.
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)
bool isAnyPointerType() const
Defines the clang::Module class, which describes a module in the source code.
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.
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.
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.
llvm::Error Execute()
Set the source manager's main input file, and run the action.
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
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, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, 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...
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.
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
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
ASTWriterData(InMemoryModuleCache &ModuleCache)
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.
std::unique_ptr< CompilerInvocation > createInvocationFromCommandLine(ArrayRef< const char *> Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >(), IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr, bool ShouldRecoverOnErrors=false, std::vector< std::string > *CC1Args=nullptr)
createInvocationFromCommandLine - Construct a compiler invocation object for a command line argument ...
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
static bool isInMainFile(const clang::Diagnostic &D)
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.
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
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
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()
bool RetainExcludedConditionalBlocks
When enabled, excluded conditional blocks retain in the main file.
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.
llvm::vfs::FileSystem & getVirtualFileSystem() const
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