65 #include "llvm/ADT/ArrayRef.h" 66 #include "llvm/ADT/DenseMap.h" 67 #include "llvm/ADT/IntrusiveRefCntPtr.h" 68 #include "llvm/ADT/None.h" 69 #include "llvm/ADT/Optional.h" 70 #include "llvm/ADT/STLExtras.h" 71 #include "llvm/ADT/SmallString.h" 72 #include "llvm/ADT/SmallVector.h" 73 #include "llvm/ADT/StringMap.h" 74 #include "llvm/ADT/StringRef.h" 75 #include "llvm/ADT/StringSet.h" 76 #include "llvm/ADT/Twine.h" 77 #include "llvm/ADT/iterator_range.h" 78 #include "llvm/Bitstream/BitstreamWriter.h" 79 #include "llvm/Support/Allocator.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CrashRecoveryContext.h" 82 #include "llvm/Support/DJB.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/ErrorOr.h" 85 #include "llvm/Support/FileSystem.h" 86 #include "llvm/Support/MemoryBuffer.h" 87 #include "llvm/Support/Mutex.h" 88 #include "llvm/Support/Timer.h" 89 #include "llvm/Support/VirtualFileSystem.h" 90 #include "llvm/Support/raw_ostream.h" 103 using namespace clang;
105 using llvm::TimeRecord;
115 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
117 Start = TimeRecord::getCurrentTime();
122 TimeRecord Elapsed = TimeRecord::getCurrentTime();
124 llvm::errs() << Output <<
':';
125 Elapsed.print(Elapsed, llvm::errs());
126 llvm::errs() <<
'\n';
130 void setOutput(
const Twine &Output) {
132 this->Output = Output.str();
139 static std::unique_ptr<T>
valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
142 return std::move(*Val);
149 Output = std::move(*Val);
155 static std::unique_ptr<llvm::MemoryBuffer>
157 llvm::vfs::FileSystem *VFS,
158 StringRef FilePath,
bool isVolatile) {
164 llvm::MemoryBuffer *Buffer =
nullptr;
165 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
166 auto FileStatus = VFS->status(FilePath);
168 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
171 for (
const auto &RF : PreprocessorOpts.RemappedFiles) {
172 std::string MPath(RF.first);
173 auto MPathStatus = VFS->status(MPath);
175 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
176 if (MainFileID == MID) {
178 BufferOwner =
valueOrNull(VFS->getBufferForFile(RF.second, -1,
true, isVolatile));
187 for (
const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
188 std::string MPath(RB.first);
189 auto MPathStatus = VFS->status(MPath);
191 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
192 if (MainFileID == MID) {
195 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
202 if (!Buffer && !BufferOwner) {
203 BufferOwner =
valueOrNull(VFS->getBufferForFile(FilePath, -1,
true, isVolatile));
212 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
221 : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
224 void ASTUnit::clearFileLevelDecls() {
225 llvm::DeleteContainerSeconds(FileDecls);
239 ASTUnit::ASTUnit(
bool _MainFileIsAST)
240 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv(
"LIBCLANG_TIMING")),
241 ShouldCacheCodeCompletionResults(
false),
242 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
243 UnsafeToFree(
false) {
244 if (getenv(
"LIBCLANG_OBJTRACKING"))
245 fprintf(stderr,
"+++ %u translation units\n", ++ActiveASTUnitObjects);
248 ASTUnit::~ASTUnit() {
254 clearFileLevelDecls();
260 if (Invocation && OwnsRemappedFileBuffers) {
266 ClearCachedCompletionResults();
268 if (getenv(
"LIBCLANG_OBJTRACKING"))
269 fprintf(stderr,
"--- %u translation units\n", --ActiveASTUnitObjects);
273 this->PP = std::move(PP);
278 "Bad context for source file");
286 bool &IsNestedNameSpecifier) {
287 IsNestedNameSpecifier =
false;
289 if (isa<UsingShadowDecl>(ND))
294 uint64_t Contexts = 0;
295 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
296 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
297 isa<TypeAliasTemplateDecl>(ND)) {
299 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
308 if (LangOpts.CPlusPlus)
313 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
317 if (
const auto *
ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
319 if (
ID->getDefinition())
325 if (isa<EnumDecl>(ND)) {
329 if (LangOpts.CPlusPlus11)
330 IsNestedNameSpecifier =
true;
331 }
else if (
const auto *Record = dyn_cast<RecordDecl>(ND)) {
332 if (Record->isUnion())
337 if (LangOpts.CPlusPlus)
338 IsNestedNameSpecifier =
true;
339 }
else if (isa<ClassTemplateDecl>(ND))
340 IsNestedNameSpecifier =
true;
341 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
347 }
else if (isa<ObjCProtocolDecl>(ND)) {
349 }
else if (isa<ObjCCategoryDecl>(ND)) {
351 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
355 IsNestedNameSpecifier =
true;
361 void ASTUnit::CacheCodeCompletionResults() {
365 SimpleTimer Timer(WantTiming);
366 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
369 ClearCachedCompletionResults();
374 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
376 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
380 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
383 for (
auto &R : Results) {
385 case Result::RK_Declaration: {
386 bool IsNestedNameSpecifier =
false;
387 CachedCodeCompletionResult CachedResult;
388 CachedResult.Completion = R.CreateCodeCompletionString(
389 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
390 IncludeBriefCommentsInCodeCompletion);
392 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
393 CachedResult.Priority = R.Priority;
394 CachedResult.Kind = R.CursorKind;
395 CachedResult.Availability = R.Availability;
402 CachedResult.Type = 0;
411 unsigned &TypeValue = CompletionTypes[CanUsageType];
412 if (TypeValue == 0) {
413 TypeValue = CompletionTypes.size();
418 CachedResult.Type = TypeValue;
421 CachedCompletionResults.push_back(CachedResult);
424 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
425 !R.StartsNestedNameSpecifier) {
441 if (isa<NamespaceDecl>(R.Declaration) ||
442 isa<NamespaceAliasDecl>(R.Declaration))
445 if (uint64_t RemainingContexts
446 = NNSContexts & ~CachedResult.ShowInContexts) {
450 R.StartsNestedNameSpecifier =
true;
451 CachedResult.Completion = R.CreateCodeCompletionString(
452 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
453 IncludeBriefCommentsInCodeCompletion);
454 CachedResult.ShowInContexts = RemainingContexts;
457 CachedResult.Type = 0;
458 CachedCompletionResults.push_back(CachedResult);
464 case Result::RK_Keyword:
465 case Result::RK_Pattern:
470 case Result::RK_Macro: {
471 CachedCodeCompletionResult CachedResult;
472 CachedResult.Completion = R.CreateCodeCompletionString(
473 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
474 IncludeBriefCommentsInCodeCompletion);
475 CachedResult.ShowInContexts
489 CachedResult.Priority = R.Priority;
490 CachedResult.Kind = R.CursorKind;
491 CachedResult.Availability = R.Availability;
493 CachedResult.Type = 0;
494 CachedCompletionResults.push_back(CachedResult);
501 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
504 void ASTUnit::ClearCachedCompletionResults() {
505 CachedCompletionResults.clear();
506 CachedCompletionTypes.clear();
507 CachedCompletionAllocator =
nullptr;
520 std::shared_ptr<TargetOptions> &TargetOpts;
521 IntrusiveRefCntPtr<TargetInfo> &
Target;
523 bool InitializedLanguage =
false;
529 std::shared_ptr<TargetOptions> &TargetOpts,
530 IntrusiveRefCntPtr<TargetInfo> &Target,
unsigned &Counter)
531 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
532 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
535 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
536 bool AllowCompatibleDifferences)
override {
537 if (InitializedLanguage)
541 InitializedLanguage =
true;
548 StringRef SpecificModuleCachePath,
549 bool Complain)
override {
550 this->HSOpts = HSOpts;
555 std::string &SuggestedPredefines)
override {
556 this->PPOpts = PPOpts;
560 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
561 bool AllowCompatibleDifferences)
override {
566 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
575 unsigned Value)
override {
581 if (!Target || !InitializedLanguage)
588 Target->adjust(LangOpt);
613 bool CaptureNonErrorsFromIncludes =
true;
618 FilterAndStoreDiagnosticConsumer(
621 bool CaptureNonErrorsFromIncludes)
622 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
623 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
624 assert((StoredDiags || StandaloneDiags) &&
625 "No output collections were passed to StoredDiagnosticConsumer.");
630 this->LangOpts = &LangOpts;
632 SourceMgr = &PP->getSourceManager();
641 class CaptureDroppedDiagnostics {
643 FilterAndStoreDiagnosticConsumer Client;
645 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
648 CaptureDroppedDiagnostics(
653 Client(StoredDiags, StandaloneDiags,
654 CaptureDiagnostics !=
664 ~CaptureDroppedDiagnostics() {
666 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
684 void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
700 StoredDiags->emplace_back(Level, Info);
701 ResultDiag = &StoredDiags->back();
704 if (StandaloneDiags) {
707 StoredDiag.emplace(Level, Info);
708 ResultDiag = StoredDiag.getPointer();
710 StandaloneDiags->push_back(
722 return &WriterData->Writer;
728 return &WriterData->Writer;
732 std::unique_ptr<llvm::MemoryBuffer>
735 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
737 return std::move(*Buffer);
739 *ErrorStr = Buffer.getError().message();
747 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
749 Diags->setClient(
new FilterAndStoreDiagnosticConsumer(
750 &AST.StoredDiagnostics,
nullptr,
760 bool UserFilesAreVolatile) {
761 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
764 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
765 ASTUnitCleanup(AST.get());
767 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
768 DiagCleanup(Diags.get());
770 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
772 AST->LangOpts = std::make_shared<LangOptions>();
773 AST->OnlyLocalDecls = OnlyLocalDecls;
774 AST->CaptureDiagnostics = CaptureDiagnostics;
775 AST->Diagnostics = Diags;
777 llvm::vfs::getRealFileSystem();
778 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
779 AST->UserFilesAreVolatile = UserFilesAreVolatile;
781 AST->getFileManager(),
782 UserFilesAreVolatile);
784 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
785 AST->HSOpts->ModuleFormat = PCHContainerRdr.
getFormat();
787 AST->getSourceManager(),
788 AST->getDiagnostics(),
791 AST->PPOpts = std::make_shared<PreprocessorOptions>();
801 AST->PP = std::make_shared<Preprocessor>(
802 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
803 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
809 AST->Ctx =
new ASTContext(*AST->LangOpts, AST->getSourceManager(),
810 PP.getIdentifierTable(), PP.getSelectorTable(),
811 PP.getBuiltinInfo());
813 bool disableValid =
false;
814 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
817 PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
819 disableValid, AllowPCHWithCompilerErrors);
821 AST->Reader->
setListener(llvm::make_unique<ASTInfoCollector>(
822 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
823 AST->TargetOpts, AST->Target, Counter));
831 AST->Ctx->setExternalSource(AST->Reader);
844 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
848 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
850 PP.setCounterValue(Counter);
858 AST->TheSema.reset(
new Sema(PP, *AST->Ctx, *AST->Consumer));
859 AST->TheSema->Initialize();
860 AST->Reader->InitializeSema(*AST->TheSema);
864 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
878 class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
882 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) {}
884 void MacroDefined(
const Token &MacroNameTok,
904 if (
const auto *ND = dyn_cast<NamedDecl>(D)) {
905 if (
const auto *EnumD = dyn_cast<EnumDecl>(D)) {
908 if (!EnumD->isScoped()) {
909 for (
const auto *EI : EnumD->enumerators()) {
910 if (EI->getIdentifier())
911 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
916 if (ND->getIdentifier())
917 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
919 std::string NameStr = Name.getAsString();
920 Hash = llvm::djbHash(NameStr, Hash);
925 if (
const auto *ImportD = dyn_cast<ImportDecl>(D)) {
926 if (
const Module *Mod = ImportD->getImportedModule()) {
927 std::string ModName = Mod->getFullModuleName();
928 Hash = llvm::djbHash(ModName, Hash);
936 class TopLevelDeclTrackerConsumer :
public ASTConsumer {
941 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
942 : Unit(_Unit), Hash(Hash) {
946 void handleTopLevelDecl(
Decl *D) {
954 if (isa<ObjCMethodDecl>(D))
960 handleFileLevelDecl(D);
963 void handleFileLevelDecl(
Decl *D) {
965 if (
auto *NSD = dyn_cast<NamespaceDecl>(D)) {
966 for (
auto *I : NSD->decls())
967 handleFileLevelDecl(I);
972 for (
auto *TopLevelDecl : D)
973 handleTopLevelDecl(TopLevelDecl);
980 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
981 for (
auto *TopLevelDecl : D)
982 handleTopLevelDecl(TopLevelDecl);
999 StringRef InFile)
override {
1001 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1003 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
1008 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
1010 bool hasCodeCompletionSupport()
const override {
return false; }
1019 unsigned getHash()
const {
return Hash; }
1021 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
1023 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1024 return std::move(TopLevelDeclIDs);
1027 void AfterPCHEmitted(
ASTWriter &Writer)
override {
1028 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1029 for (
const auto *D : TopLevelDecls) {
1031 if (D->isInvalidDecl())
1033 TopLevelDeclIDs.push_back(Writer.
getDeclID(D));
1038 for (
auto *D : DG) {
1043 if (isa<ObjCMethodDecl>(D))
1046 TopLevelDecls.push_back(D);
1050 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
1051 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1056 std::vector<Decl *> TopLevelDecls;
1057 std::vector<serialization::DeclID> TopLevelDeclIDs;
1072 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1084 for (
auto &SD : StoredDiagnostics) {
1085 if (SD.getLocation().isValid()) {
1087 SD.setLocation(Loc);
1097 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1098 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1104 assert(VFS == &FileMgr->getVirtualFileSystem() &&
1105 "VFS passed to Parse and VFS in FileMgr are different");
1107 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1108 if (OverrideMainBuffer) {
1110 "No preamble was built, but OverrideMainBuffer is not null");
1111 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1116 std::unique_ptr<CompilerInstance> Clang(
1122 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
1123 Clang->setFileManager(&*FileMgr);
1125 FileMgr = Clang->createFileManager(std::move(VFS));
1128 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1129 CICleanup(Clang.get());
1131 Clang->setInvocation(CCInvocation);
1132 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1140 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1141 if (!Clang->hasTarget())
1148 Clang->getTarget().adjust(Clang->getLangOpts());
1150 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1151 "Invocation must have exactly one source file!");
1152 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1154 "FIXME: AST inputs not yet supported here!");
1155 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1157 "IR inputs not support here!");
1160 LangOpts = Clang->getInvocation().LangOpts;
1161 FileSystemOpts = Clang->getFileSystemOpts();
1166 UserFilesAreVolatile);
1167 if (!OverrideMainBuffer) {
1169 TopLevelDeclsInPreamble.clear();
1180 if (OverrideMainBuffer) {
1189 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1192 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1193 new TopLevelDeclTrackerAction(*
this));
1196 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1197 ActCleanup(Act.get());
1199 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1202 if (SavedMainFileBuffer)
1204 PreambleDiagnostics, StoredDiagnostics);
1206 PreambleSrcLocCache.clear();
1209 consumeError(std::move(Err));
1213 transferASTDataFromCompilerInstance(*Clang);
1215 Act->EndSourceFile();
1217 FailedParseDiagnostics.clear();
1223 SavedMainFileBuffer =
nullptr;
1227 transferASTDataFromCompilerInstance(*Clang);
1228 FailedParseDiagnostics.swap(StoredDiagnostics);
1229 StoredDiagnostics.clear();
1230 NumStoredDiagnosticsFromDriver = 0;
1234 static std::pair<unsigned, unsigned>
1240 return std::make_pair(Offset, EndOffset);
1271 for (
const auto &Range : InDiag.
getRanges())
1299 std::unique_ptr<llvm::MemoryBuffer>
1300 ASTUnit::getMainBufferWithPrecompiledPreamble(
1301 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1304 unsigned MaxLines) {
1307 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1309 MainFilePath, UserFilesAreVolatile);
1310 if (!MainFileBuffer)
1315 MainFileBuffer.get(), MaxLines);
1320 if (
Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1331 PreambleRebuildCountdown = 1;
1332 return MainFileBuffer;
1335 PreambleDiagnostics.clear();
1336 TopLevelDeclsInPreamble.clear();
1337 PreambleSrcLocCache.clear();
1338 PreambleRebuildCountdown = 1;
1345 if (PreambleRebuildCountdown > 1) {
1346 --PreambleRebuildCountdown;
1350 assert(!
Preamble &&
"No Preamble should be stored at that point");
1360 ASTUnitPreambleCallbacks Callbacks;
1364 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1365 &NewPreambleDiagsStandalone);
1368 SimpleTimer PreambleTimer(WantTiming);
1369 PreambleTimer.setOutput(
"Precompiling preamble");
1371 const bool PreviousSkipFunctionBodies =
1377 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1378 PCHContainerOps,
false, Callbacks);
1381 PreviousSkipFunctionBodies;
1384 Preamble = std::move(*NewPreamble);
1385 PreambleRebuildCountdown = 1;
1387 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1390 PreambleRebuildCountdown = 1;
1400 llvm_unreachable(
"unexpected BuildPreambleError");
1404 assert(
Preamble &&
"Preamble wasn't built");
1406 TopLevelDecls.clear();
1407 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1408 PreambleTopLevelHashValue = Callbacks.getHash();
1413 StoredDiagnostics = std::move(NewPreambleDiags);
1414 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1419 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1420 CompletionCacheTopLevelHashValue = 0;
1421 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1424 return MainFileBuffer;
1427 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1428 assert(
Preamble &&
"Should only be called when preamble was built");
1430 std::vector<Decl *> Resolved;
1431 Resolved.reserve(TopLevelDeclsInPreamble.size());
1433 for (
const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1437 Resolved.push_back(D);
1439 TopLevelDeclsInPreamble.clear();
1440 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1463 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1468 return Input.
getBuffer()->getBufferIdentifier();
1473 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1474 return FE->getName();
1485 Mod = Reader->getModuleManager().getPrimaryModule();
1489 std::unique_ptr<ASTUnit>
1493 bool UserFilesAreVolatile) {
1494 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1495 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1498 AST->Diagnostics = Diags;
1499 AST->FileSystemOpts = CI->getFileSystemOpts();
1500 AST->Invocation = std::move(CI);
1501 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1502 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1503 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1504 UserFilesAreVolatile);
1511 std::shared_ptr<CompilerInvocation> CI,
1512 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1514 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1516 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1517 bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile,
1518 std::unique_ptr<ASTUnit> *ErrAST) {
1519 assert(CI &&
"A CompilerInvocation is required");
1521 std::unique_ptr<ASTUnit> OwnAST;
1525 OwnAST =
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1531 if (!ResourceFilesPath.empty()) {
1535 AST->OnlyLocalDecls = OnlyLocalDecls;
1536 AST->CaptureDiagnostics = CaptureDiagnostics;
1537 if (PrecompilePreambleAfterNParses > 0)
1538 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1540 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1541 AST->IncludeBriefCommentsInCodeCompletion
1542 = IncludeBriefCommentsInCodeCompletion;
1545 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1546 ASTUnitCleanup(OwnAST.get());
1548 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1549 DiagCleanup(Diags.get());
1552 CI->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1553 CI->getFrontendOpts().DisableFree =
false;
1557 std::unique_ptr<CompilerInstance> Clang(
1561 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1562 CICleanup(Clang.get());
1564 Clang->setInvocation(std::move(CI));
1565 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1573 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1574 if (!Clang->hasTarget())
1581 Clang->getTarget().adjust(Clang->getLangOpts());
1583 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1584 "Invocation must have exactly one source file!");
1585 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1587 "FIXME: AST inputs not yet supported here!");
1588 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1590 "IR inputs not support here!");
1593 AST->TheSema.reset();
1596 AST->Reader =
nullptr;
1606 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1608 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1609 Act = TrackerAct.get();
1613 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1614 ActCleanup(TrackerAct.get());
1616 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1617 AST->transferASTDataFromCompilerInstance(*Clang);
1618 if (OwnAST && ErrAST)
1619 ErrAST->swap(OwnAST);
1624 if (Persistent && !TrackerAct) {
1625 Clang->getPreprocessor().addPPCallbacks(
1626 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1628 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1629 if (Clang->hasASTConsumer())
1630 Consumers.push_back(Clang->takeASTConsumer());
1631 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1633 Clang->setASTConsumer(
1634 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1637 consumeError(std::move(Err));
1638 AST->transferASTDataFromCompilerInstance(*Clang);
1639 if (OwnAST && ErrAST)
1640 ErrAST->swap(OwnAST);
1646 AST->transferASTDataFromCompilerInstance(*Clang);
1651 return OwnAST.release();
1656 bool ASTUnit::LoadFromCompilerInvocation(
1657 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1658 unsigned PrecompilePreambleAfterNParses,
1663 assert(VFS &&
"VFS is null");
1666 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1667 Invocation->getFrontendOpts().DisableFree =
false;
1671 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1672 if (PrecompilePreambleAfterNParses > 0) {
1673 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1674 OverrideMainBuffer =
1675 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1680 SimpleTimer ParsingTimer(WantTiming);
1684 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1685 MemBufferCleanup(OverrideMainBuffer.get());
1687 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1690 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1691 std::shared_ptr<CompilerInvocation> CI,
1692 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1696 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1697 bool UserFilesAreVolatile) {
1699 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1700 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1701 AST->Diagnostics = Diags;
1702 AST->OnlyLocalDecls = OnlyLocalDecls;
1703 AST->CaptureDiagnostics = CaptureDiagnostics;
1704 AST->TUKind = TUKind;
1705 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1706 AST->IncludeBriefCommentsInCodeCompletion
1707 = IncludeBriefCommentsInCodeCompletion;
1708 AST->Invocation = std::move(CI);
1710 AST->FileMgr = FileMgr;
1711 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1714 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1715 ASTUnitCleanup(AST.get());
1717 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1718 DiagCleanup(Diags.get());
1720 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1721 PrecompilePreambleAfterNParses,
1722 &AST->FileMgr->getVirtualFileSystem()))
1728 const char **ArgBegin,
const char **ArgEnd,
1729 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1734 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1736 bool SingleFileParse,
bool UserFilesAreVolatile,
bool ForSerialization,
1739 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1743 std::shared_ptr<CompilerInvocation> CI;
1746 CaptureDroppedDiagnostics
Capture(CaptureDiagnostics, *Diags,
1747 &StoredDiagnostics,
nullptr);
1750 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1757 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1766 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1768 CI->getFrontendOpts().SkipFunctionBodies =
1772 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1775 std::unique_ptr<ASTUnit> AST;
1776 AST.reset(
new ASTUnit(
false));
1777 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1778 AST->StoredDiagnostics.swap(StoredDiagnostics);
1779 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1780 AST->Diagnostics = Diags;
1781 AST->FileSystemOpts = CI->getFileSystemOpts();
1783 VFS = llvm::vfs::getRealFileSystem();
1785 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1787 AST->OnlyLocalDecls = OnlyLocalDecls;
1788 AST->CaptureDiagnostics = CaptureDiagnostics;
1789 AST->TUKind = TUKind;
1790 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1791 AST->IncludeBriefCommentsInCodeCompletion
1792 = IncludeBriefCommentsInCodeCompletion;
1793 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1794 AST->Invocation = CI;
1795 AST->SkipFunctionBodies = SkipFunctionBodies;
1796 if (ForSerialization)
1797 AST->WriterData.reset(
new ASTWriterData(*AST->ModuleCache));
1803 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1804 ASTUnitCleanup(AST.get());
1806 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1807 PrecompilePreambleAfterNParses,
1812 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1818 return AST.release();
1828 assert(FileMgr &&
"FileMgr is null on Reparse call");
1829 VFS = &FileMgr->getVirtualFileSystem();
1832 clearFileLevelDecls();
1834 SimpleTimer ParsingTimer(WantTiming);
1844 Invocation->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1850 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1851 if (
Preamble || PreambleRebuildCountdown > 0)
1852 OverrideMainBuffer =
1853 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1859 if (OverrideMainBuffer)
1864 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1868 if (!Result && ShouldCacheCodeCompletionResults &&
1869 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1870 CacheCodeCompletionResults();
1880 SavedMainFileBuffer.reset();
1888 TopLevelDecls.clear();
1889 clearFileLevelDecls();
1902 uint64_t NormalContexts;
1935 unsigned NumResults)
override;
1937 void ProcessOverloadCandidates(
Sema &S,
unsigned CurrentArg,
1939 unsigned NumCandidates,
1960 unsigned NumResults,
1962 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1963 bool OnlyTagNames =
false;
1988 OnlyTagNames =
true;
2012 for (
unsigned I = 0; I != NumResults; ++I) {
2013 if (Results[I].
Kind != Result::RK_Declaration)
2019 bool Hiding =
false;
2028 Hiding = (IDNS & HiddenIDNS);
2042 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2045 unsigned NumResults) {
2047 bool AddedResult =
false;
2048 uint64_t InContexts =
2050 ? NormalContexts : (1LL << Context.
getKind());
2052 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2061 if ((
C->ShowInContexts & InContexts) == 0)
2068 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2075 HiddenNames.count(
C->Completion->getTypedText()))
2079 unsigned Priority =
C->Priority;
2086 }
else if (
C->Type) {
2091 if (ExpectedSTC ==
C->TypeClass) {
2093 llvm::StringMap<unsigned> &CachedCompletionTypes
2095 llvm::StringMap<unsigned>::iterator Pos
2097 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2117 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2124 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2128 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2133 StringRef File,
unsigned Line,
unsigned Column,
2135 bool IncludeCodePatterns,
bool IncludeBriefComments,
2137 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2144 SimpleTimer CompletionTimer(WantTiming);
2145 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2146 Twine(Line) +
":" + Twine(Column));
2148 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2155 CachedCompletionResults.empty();
2157 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2162 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2169 LangOpts = *CCInvocation->getLangOpts();
2172 LangOpts.SpellChecking =
false;
2173 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2175 std::unique_ptr<CompilerInstance> Clang(
2179 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2180 CICleanup(Clang.get());
2182 auto &Inv = *CCInvocation;
2183 Clang->setInvocation(std::move(CCInvocation));
2184 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2187 Clang->setDiagnostics(&Diag);
2189 Clang->getDiagnostics(),
2190 &StoredDiagnostics,
nullptr);
2195 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2196 if (!Clang->hasTarget()) {
2197 Clang->setInvocation(
nullptr);
2205 Clang->getTarget().adjust(Clang->getLangOpts());
2207 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2208 "Invocation must have exactly one source file!");
2209 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2211 "FIXME: AST inputs not yet supported here!");
2212 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2214 "IR inputs not support here!");
2217 Clang->setFileManager(&FileMgr);
2218 Clang->setSourceManager(&SourceMgr);
2230 AugmentedCodeCompleteConsumer *AugmentedConsumer
2231 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2232 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2238 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2240 std::string CompleteFilePath(File);
2243 auto CompleteFileStatus = VFS.status(CompleteFilePath);
2244 if (CompleteFileStatus) {
2245 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2247 std::string MainPath(OriginalSourceFile);
2248 auto MainStatus = VFS.status(MainPath);
2250 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2251 if (CompleteFileID == MainID && Line > 1)
2252 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2253 PCHContainerOps, Inv, &VFS,
false, Line - 1);
2260 if (OverrideMainBuffer) {
2262 "No preamble was built, but OverrideMainBuffer is not null");
2266 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2267 OverrideMainBuffer.get());
2272 OwnedBuffers.push_back(OverrideMainBuffer.release());
2279 if (!Clang->getLangOpts().Modules)
2282 std::unique_ptr<SyntaxOnlyAction> Act;
2284 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2286 consumeError(std::move(Err));
2288 Act->EndSourceFile();
2293 if (HadModuleLoaderFatalFailure)
2300 TempPath +=
"-%%%%%%%%";
2302 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2307 llvm::raw_fd_ostream Out(fd,
true);
2311 if (Out.has_error()) {
2316 if (llvm::sys::fs::rename(TempPath, File)) {
2329 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2332 if (!Buffer.empty())
2333 OS.write(Buffer.data(), Buffer.size());
2343 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2347 llvm::BitstreamWriter Stream(Buffer);
2349 ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2355 void ASTUnit::TranslateStoredDiagnostics(
2365 Result.reserve(Diags.size());
2367 for (
const auto &SD : Diags) {
2369 if (SD.Filename.empty())
2375 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2376 if (ItFileID == PreambleSrcLocCache.end()) {
2379 PreambleSrcLocCache[SD.Filename] = FileLoc;
2381 FileLoc = ItFileID->getValue();
2390 Ranges.reserve(SD.Ranges.size());
2391 for (
const auto &Range : SD.Ranges) {
2398 FixIts.reserve(SD.FixIts.size());
2399 for (
const auto &
FixIt : SD.FixIts) {
2409 SD.Message, Loc, Ranges, FixIts));
2435 if (FID.isInvalid())
2442 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2444 if (Decls->empty() || Decls->back().first <=
Offset) {
2445 Decls->push_back(LocDecl);
2449 LocDeclsTy::iterator I =
2450 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2452 Decls->insert(I, LocDecl);
2460 if (SourceMgr->isLoadedFileID(File)) {
2461 assert(Ctx->getExternalSource() &&
"No external source!");
2462 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2466 FileDeclsTy::iterator I = FileDecls.find(File);
2467 if (I == FileDecls.end())
2471 if (LocDecls.empty())
2474 LocDeclsTy::iterator BeginIt =
2475 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2476 return LD.first <
Offset;
2478 if (BeginIt != LocDecls.begin())
2484 while (BeginIt != LocDecls.begin() &&
2485 BeginIt->second->isTopLevelDeclInObjCContainer())
2488 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2489 LocDecls, std::make_pair(Offset + Length, (
Decl *)
nullptr),
2490 llvm::less_first());
2491 if (EndIt != LocDecls.end())
2494 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2495 Decls.push_back(DIt->second);
2499 unsigned Line,
unsigned Col)
const {
2518 PreambleID = SourceMgr->getPreambleFileID();
2524 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs <
Preamble->getBounds().Size) {
2526 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2539 PreambleID = SourceMgr->getPreambleFileID();
2545 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2546 Offs < Preamble->getBounds().Size) {
2547 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2557 FID = SourceMgr->getPreambleFileID();
2562 return SourceMgr->isInFileID(Loc, FID);
2568 FID = SourceMgr->getMainFileID();
2573 return SourceMgr->isInFileID(Loc, FID);
2579 FID = SourceMgr->getPreambleFileID();
2584 return SourceMgr->getLocForEndOfFile(FID);
2590 FID = SourceMgr->getMainFileID();
2595 return SourceMgr->getLocForStartOfFile(FID);
2598 llvm::iterator_range<PreprocessingRecord::iterator>
2602 Mod = Reader->getModuleManager().getPrimaryModule();
2603 return Reader->getModulePreprocessedEntities(Mod);
2607 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2616 Mod = Reader->getModuleManager().getPrimaryModule();
2617 for (
const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2618 if (!Fn(context, D))
2627 TL != TLEnd; ++TL) {
2628 if (!Fn(context, *TL))
2642 case serialization::MK_ImplicitModule:
2643 case serialization::MK_ExplicitModule:
2644 case serialization::MK_PrebuiltModule:
2646 case serialization::MK_PCH:
2649 case serialization::MK_Preamble:
2651 case serialization::MK_MainFile:
2671 if (LangOpts.OpenCL)
2673 else if (LangOpts.CUDA)
2675 else if (LangOpts.RenderScript)
2677 else if (LangOpts.CPlusPlus)
2693 ASTUnit::ConcurrencyState::ConcurrencyState() {
2694 Mutex =
new llvm::sys::MutexImpl(
true);
2697 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2698 delete static_cast<llvm::sys::MutexImpl *
>(Mutex);
2701 void ASTUnit::ConcurrencyState::start() {
2702 bool acquired =
static_cast<llvm::sys::MutexImpl *
>(Mutex)->tryacquire();
2703 assert(acquired &&
"Concurrent access to ASTUnit!");
2706 void ASTUnit::ConcurrencyState::finish() {
2707 static_cast<llvm::sys::MutexImpl *
>(Mutex)->release();
2712 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2713 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2714 void ASTUnit::ConcurrencyState::start() {}
2715 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.
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.
Divide by this factor when a code-completion result's type exactly matches the type we expect...
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
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.
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, 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...
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.
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 {}'.
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.
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.
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.
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.
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
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()
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.
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)
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.
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.
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.
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
Priority for a code pattern.
static bool isInMainFile(const clang::Diagnostic &D)
const SourceManager & getSourceManager() const
An unspecified code-completion context where we should also add macro completions.
Priority for a nested-name-specifier.
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
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.
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