39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/TinyPtrVector.h"
42#include "llvm/ADT/edit_distance.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
53#include "OpenCLBuiltins.inc"
59 class UnqualUsingEntry {
66 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
70 return CommonAncestor;
79 bool operator()(
const UnqualUsingEntry &L,
const UnqualUsingEntry &R) {
80 return L.getCommonAncestor() < R.getCommonAncestor();
83 bool operator()(
const UnqualUsingEntry &E,
const DeclContext *DC) {
84 return E.getCommonAncestor() < DC;
87 bool operator()(
const DeclContext *DC,
const UnqualUsingEntry &E) {
88 return DC < E.getCommonAncestor();
95 class UnqualUsingDirectiveSet {
104 UnqualUsingDirectiveSet(
Sema &SemaRef) : SemaRef(SemaRef) {}
106 void visitScopeChain(
Scope *S,
Scope *InnermostFileScope) {
114 for (; S; S = S->getParent()) {
122 for (
auto *I : S->using_directives())
124 visit(I, InnermostFileDC);
137 if (!visited.insert(DC).second)
140 addUsingDirectives(DC, EffectiveDC);
148 if (!visited.insert(NS).second)
151 addUsingDirective(UD, EffectiveDC);
152 addUsingDirectives(NS, EffectiveDC);
163 if (SemaRef.
isVisible(UD) && visited.insert(NS).second) {
164 addUsingDirective(UD, EffectiveDC);
172 DC = queue.pop_back_val();
187 while (!Common->
Encloses(EffectiveDC))
194 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
196 typedef ListTy::const_iterator const_iterator;
198 const_iterator begin()
const {
return list.begin(); }
199 const_iterator end()
const {
return list.end(); }
201 llvm::iterator_range<const_iterator>
203 return llvm::make_range(std::equal_range(begin(), end(),
205 UnqualUsingEntry::Comparator()));
214 bool Redeclaration) {
235 assert(!Redeclaration &&
"cannot do redeclaration operator lookup");
274 assert(Redeclaration &&
"should only be used for redecl lookup");
301void LookupResult::configure() {
312 case OO_Array_Delete:
323 if (
unsigned BuiltinID =
Id->getBuiltinID()) {
330bool LookupResult::checkDebugAssumptions()
const {
333 assert(ResultKind !=
Found || Decls.
size() == 1);
335 (Decls.
size() == 1 &&
336 isa<FunctionTemplateDecl>((*
begin())->getUnderlyingDecl())));
341 assert((Paths !=
nullptr) == (ResultKind ==
Ambiguous &&
374 !isa<UsingShadowDecl>(Existing))
388 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
389 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
390 bool HaveTag = isa<TagDecl>(EUnderlying);
393 return HaveTag != WantTag;
400 if (
auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
401 auto *EFD = cast<FunctionDecl>(EUnderlying);
402 unsigned DMin = DFD->getMinRequiredArguments();
403 unsigned EMin = EFD->getMinRequiredArguments();
412 if (
auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
413 auto *ETD = cast<TemplateDecl>(EUnderlying);
414 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
415 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
424 for (
unsigned I = DMin, N = DTD->getTemplateParameters()->size();
427 ETD->getTemplateParameters()->getParam(I)) &&
429 DTD->getTemplateParameters()->getParam(I)))
436 if (
VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
437 VarDecl *EVD = cast<VarDecl>(EUnderlying);
439 !DVD->getType()->isIncompleteType()) {
447 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
456 if (Prev == EUnderlying)
476 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
477 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
478 isa<UnresolvedUsingValueDecl>(D);
483 unsigned N = Decls.
size();
496 if (isa<FunctionTemplateDecl>(D))
498 else if (isa<UnresolvedUsingValueDecl>(D))
506 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
507 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
510 bool HasTag =
false, HasFunction =
false;
511 bool HasFunctionTemplate =
false, HasUnresolved =
false;
516 unsigned UniqueTagIndex = 0;
520 NamedDecl *D = Decls[I]->getUnderlyingDecl();
525 if ((D->
isInvalidDecl() || isa<HLSLBufferDecl>(D)) && !(I == 0 && N == 1)) {
526 Decls[I] = Decls[--N];
530 std::optional<unsigned> ExistingI;
536 if (
TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
538 auto UniqueResult = UniqueTypes.insert(
540 if (!UniqueResult.second) {
542 ExistingI = UniqueResult.first->second;
549 auto UniqueResult = Unique.insert(std::make_pair(D, I));
550 if (!UniqueResult.second) {
552 ExistingI = UniqueResult.first->second;
561 Decls[*ExistingI] = Decls[I];
562 Decls[I] = Decls[--N];
568 if (isa<UnresolvedUsingValueDecl>(D)) {
569 HasUnresolved =
true;
570 }
else if (isa<TagDecl>(D)) {
575 }
else if (isa<FunctionTemplateDecl>(D)) {
577 HasFunctionTemplate =
true;
578 }
else if (isa<FunctionDecl>(D)) {
581 if (HasNonFunction) {
586 if (
getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
588 EquivalentNonFunctions.push_back(D);
589 Decls[I] = Decls[--N];
609 if (N > 1 && HideTags && HasTag && !
Ambiguous &&
610 (HasFunction || HasNonFunction || HasUnresolved)) {
611 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
612 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
616 Decls[UniqueTagIndex] = Decls[--N];
623 if (!EquivalentNonFunctions.empty() && !
Ambiguous)
625 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
629 if (HasNonFunction && (HasFunction || HasUnresolved))
634 else if (HasUnresolved)
636 else if (N > 1 || HasFunctionTemplate)
642void LookupResult::addDeclsFromBasePaths(
const CXXBasePaths &
P) {
644 for (I =
P.begin(), E =
P.end(); I != E; ++I)
653 addDeclsFromBasePaths(*Paths);
661 addDeclsFromBasePaths(*Paths);
667 Out << Decls.
size() <<
" result(s)";
669 if (Paths) Out <<
", base paths present";
686 llvm::StringRef Name) {
688 << TypeClass << Name;
730 Sema &S,
const OpenCLBuiltinStruct &OpenCLBuiltin,
unsigned &GenTypeMaxCnt,
734 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
735 OCL2Qual(S, TypeTable[Sig], RetTypes);
736 GenTypeMaxCnt = RetTypes.size();
740 for (
unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
742 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
744 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
745 ArgTypes.push_back(std::move(Ty));
768 if (RetTypes.size() == 0)
772 for (
unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
775 for (
unsigned A = 0; A < ArgTypes.size(); A++) {
777 if (ArgTypes[A].size() == 0)
783 assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
784 "argument type count not compatible with gentype type count");
785 unsigned Idx = IGenType % ArgTypes[A].size();
786 ArgList.push_back(ArgTypes[A][Idx]);
790 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
805 const unsigned FctIndex,
806 const unsigned Len) {
808 bool HasGenType =
false;
812 unsigned GenTypeMaxCnt;
816 for (
unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
817 const OpenCLBuiltinStruct &OpenCLBuiltin =
818 BuiltinTable[FctIndex + SignatureIndex];
822 if (!isOpenCLVersionContainedInMask(Context.
getLangOpts(),
823 OpenCLBuiltin.Versions))
829 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
830 if (!Extensions.empty()) {
832 Extensions.split(ExtVec,
" ");
833 bool AllExtensionsDefined =
true;
834 for (StringRef Ext : ExtVec) {
836 AllExtensionsDefined =
false;
840 if (!AllExtensionsDefined)
850 if (GenTypeMaxCnt > 1) {
855 std::vector<QualType> FunctionList;
863 for (
const auto &FTy : FunctionList) {
867 FTy->isFunctionProtoType());
872 const auto *FP = cast<FunctionProtoType>(FTy);
874 for (
unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
877 nullptr, FP->getParamType(IParm),
nullptr,
SC_None,
nullptr);
879 ParmList.push_back(Parm);
881 NewOpenCLBuiltin->setParams(ParmList);
884 if (OpenCLBuiltin.IsPure)
885 NewOpenCLBuiltin->
addAttr(PureAttr::CreateImplicit(Context));
886 if (OpenCLBuiltin.IsConst)
887 NewOpenCLBuiltin->
addAttr(ConstAttr::CreateImplicit(Context));
888 if (OpenCLBuiltin.IsConv)
889 NewOpenCLBuiltin->
addAttr(ConvergentAttr::CreateImplicit(Context));
892 NewOpenCLBuiltin->
addAttr(OverloadableAttr::CreateImplicit(Context));
899 if (Len > 1 || HasGenType)
927 auto Index = isOpenCLBuiltin(II->
getName());
936 if (!RVIntrinsicManager)
939 if (RVIntrinsicManager->CreateIntrinsicIfFound(R, II,
PP))
978 if (ID == Builtin::BIobjc_msgSendSuper)
986 if (!Class->getDefinition() || Class->isDependentContext())
990 return !Class->isBeingDefined();
998 if (Class->needsImplicitDefaultConstructor())
1002 if (Class->needsImplicitCopyConstructor())
1006 if (Class->needsImplicitCopyAssignment())
1011 if (Class->needsImplicitMoveConstructor())
1015 if (Class->needsImplicitMoveAssignment())
1020 if (Class->needsImplicitDestructor())
1027 switch (Name.getNameKind()) {
1033 return Name.getCXXOverloadedOperator() == OO_Equal;
1051 switch (Name.getNameKind()) {
1053 if (
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1056 if (Record->needsImplicitDefaultConstructor())
1058 if (Record->needsImplicitCopyConstructor())
1061 Record->needsImplicitMoveConstructor())
1067 if (
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1068 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1074 if (Name.getCXXOverloadedOperator() != OO_Equal)
1077 if (
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
1080 if (Record->needsImplicitCopyAssignment())
1083 Record->needsImplicitMoveAssignment())
1123 !isa<CXXRecordDecl>(DC))
1131 if (!Record->isCompleteDefinition())
1137 auto *ContainedDeducedType =
1141 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
1145 UEnd = Record->conversion_end();
U != UEnd; ++
U) {
1175 assert(ConvProto &&
"Nonsensical conversion function template type");
1202 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
1204 assert(NS && NS->
isFileContext() &&
"CppNamespaceLookup() requires namespace!");
1211 for (
const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1230 for (
Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1239struct FindLocalExternScope {
1241 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1242 Decl::IDNS_LocalExtern) {
1249 ~FindLocalExternScope() {
1253 bool OldFindLocalExtern;
1297 UnqualUsingDirectiveSet UDirs(*
this);
1298 bool VisitedUsingDirectives =
false;
1299 bool LeftStartingScope =
false;
1302 FindLocalExternScope FindLocals(R);
1305 bool SearchNamespaceScope =
true;
1307 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1310 !(*I)->isTemplateParameter()) {
1316 if (!LeftStartingScope && !Initial->
isDeclScope(*I))
1317 LeftStartingScope =
true;
1321 if (LeftStartingScope && !((*I)->hasLinkage())) {
1328 SearchNamespaceScope =
false;
1333 if (!SearchNamespaceScope) {
1335 if (S->isClassScope())
1337 dyn_cast_or_null<CXXRecordDecl>(S->getEntity()))
1367 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1371 Name.getAsIdentifierInfo(),
1389 if (!VisitedUsingDirectives) {
1392 if (UCtx->isTransparentContext())
1395 UDirs.visit(UCtx, UCtx);
1400 Scope *InnermostFileScope = S;
1401 while (InnermostFileScope &&
1403 InnermostFileScope = InnermostFileScope->
getParent();
1404 UDirs.visitScopeChain(Initial, InnermostFileScope);
1408 VisitedUsingDirectives =
true;
1433 if (!S)
return false;
1444 if (!VisitedUsingDirectives) {
1445 UDirs.visitScopeChain(Initial, S);
1452 FindLocals.restore();
1458 for (; S; S = S->getParent()) {
1461 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1472 if (Found && S->isTemplateParamScope()) {
1490 if (!(Found && S->isTemplateParamScope())) {
1492 "We should have been looking only at file context here already.");
1525 if (
auto *TD = dyn_cast<TemplateDecl>(ND))
1526 for (
auto *Param : *TD->getTemplateParameters())
1532 if (
FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1537 }
else if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1540 }
else if (
EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1541 if (
auto *Pattern = ED->getTemplateInstantiationPattern())
1543 }
else if (
VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1551 if (Context->isFileContext())
1571bool Sema::isUsableModule(
const Module *M) {
1572 assert(M &&
"We shouldn't check nullness for module here");
1574 if (UsableModuleUnitsCache.count(M))
1582 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment ||
1583 M == TheExportedImplicitGlobalModuleFragment ||
1598 llvm::StringRef(
getLangOpts().CurrentModule).split(
':').first) {
1599 UsableModuleUnitsCache.insert(M);
1615 if (isUsableModule(Merged))
1620template <
typename ParmDecl>
1625 if (!D->hasDefaultArgument())
1629 while (D && Visited.insert(D).second) {
1630 auto &DefaultArg = D->getDefaultArgStorage();
1631 if (!DefaultArg.isInherited() && S.
isAcceptable(D, Kind))
1634 if (!DefaultArg.isInherited() && Modules) {
1635 auto *NonConstD =
const_cast<ParmDecl*
>(D);
1641 D = DefaultArg.getInheritedFrom();
1649 if (
auto *
P = dyn_cast<TemplateTypeParmDecl>(D))
1650 return ::hasAcceptableDefaultArgument(*
this,
P, Modules, Kind);
1652 if (
auto *
P = dyn_cast<NonTypeTemplateParmDecl>(D))
1653 return ::hasAcceptableDefaultArgument(*
this,
P, Modules, Kind);
1655 return ::hasAcceptableDefaultArgument(
1656 *
this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1671template <
typename Filter>
1676 bool HasFilteredRedecls =
false;
1678 for (
auto *Redecl : D->
redecls()) {
1679 auto *R = cast<NamedDecl>(Redecl);
1686 HasFilteredRedecls =
true;
1689 Modules->push_back(R->getOwningModule());
1693 if (HasFilteredRedecls)
1706 if (
auto *RD = dyn_cast<CXXRecordDecl>(D))
1707 return RD->getTemplateSpecializationKind() ==
1709 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1710 return FD->getTemplateSpecializationKind() ==
1712 if (
auto *VD = dyn_cast<VarDecl>(D))
1713 return VD->getTemplateSpecializationKind() ==
1715 llvm_unreachable(
"unknown explicit specialization kind");
1722 return ::hasAcceptableExplicitSpecialization(*
this, D, Modules,
1728 return ::hasAcceptableExplicitSpecialization(*
this, D, Modules,
1737 "not a member specialization");
1775bool LookupResult::isAcceptableSlow(
Sema &SemaRef,
NamedDecl *D,
1778 "should not call this: not in slow case");
1781 assert(DeclModule &&
"hidden decl has no owning module");
1791 auto IsEffectivelyFileContext = [](
const DeclContext *DC) {
1793 isa<ExportDecl>(DC);
1799 if (DC && !IsEffectivelyFileContext(DC)) {
1807 bool AcceptableWithinParent;
1809 bool SearchDefinitions =
true;
1810 if (
const auto *DCD = dyn_cast<Decl>(DC)) {
1811 if (
const auto *TD = DCD->getDescribedTemplate()) {
1814 SearchDefinitions = Index >= TPL->
size() || TPL->
getParam(Index) != D;
1817 if (SearchDefinitions)
1818 AcceptableWithinParent =
1821 AcceptableWithinParent =
1823 }
else if (isa<ParmVarDecl>(D) ||
1824 (isa<FunctionDecl>(DC) && !SemaRef.
getLangOpts().CPlusPlus))
1825 AcceptableWithinParent =
isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1829 AcceptableWithinParent =
false;
1832 AcceptableWithinParent =
true;
1836 }
while (!IsEffectivelyFileContext(DC));
1838 AcceptableWithinParent =
1850 return AcceptableWithinParent;
1857 "Additional Sema::AcceptableKind?");
1858 return isReachableSlow(SemaRef, D);
1864 if (ModulePrivate && isUsableModule(M))
1869 if (!ModulePrivate && VisibleModules.
isVisible(M))
1877 if (LookupModules.empty())
1887 if (LookupModules.count(M))
1895 return llvm::any_of(LookupModules, [&](
const Module *LookupM) {
1902bool LookupResult::isReachableSlow(
Sema &SemaRef,
NamedDecl *D) {
1903 assert(!
isVisible(SemaRef, D) &&
"Shouldn't call the slow case.\n");
1906 assert(DeclModule &&
"hidden decl has no owning module");
1979 "should not have hidden, non-externally-declarable result here");
2013 for (
auto *RD : D->
redecls()) {
2018 auto ND = cast<NamedDecl>(RD);
2022 if (ND->isInIdentifierNamespace(IDNS) &&
2032 assert(!
isVisible(D) &&
"not in slow case");
2034 *
this, D, Modules, [](
const NamedDecl *) {
return true; },
2042 *
this, D, Modules, [](
const NamedDecl *) {
return true; },
2047 if (
auto *ND = dyn_cast<NamespaceDecl>(D)) {
2055 if (
auto *Acceptable =
getSema().VisibleNamespaceCache.lookup(Key))
2109 if (
auto *FD = dyn_cast<FunctionDecl>(ND);
2110 FD && FD->isReservedGlobalPlacementOperator())
2139 if (
auto *TD = dyn_cast<TagDecl>(DC))
2174 bool ForceNoCPlusPlus) {
2176 if (!Name)
return false;
2186 (S->getEntity() && S->getEntity()->isTransparentContext()))
2191 FindLocalExternScope FindLocals(R);
2197 bool LeftStartingScope =
false;
2206 if (!LeftStartingScope && !S->isDeclScope(*I))
2207 LeftStartingScope =
true;
2211 if (LeftStartingScope && !((*I)->hasLinkage())) {
2217 !isa<ImplicitParamDecl>(*I))
2227 while (S && !S->isDeclScope(D))
2242 for (++LastI; LastI != IEnd; ++LastI) {
2245 if (!S->isDeclScope(*LastI))
2267 if (CppLookupName(R, S))
2281 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2313 assert(StartDC->
isFileContext() &&
"start context is not a file context");
2321 Visited.insert(StartDC);
2326 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2327 if (S.
isVisible(I) && Visited.insert(ND).second)
2328 Queue.push_back(ND);
2335 bool FoundTag =
false;
2336 bool FoundNonTag =
false;
2341 while (!Queue.empty()) {
2346 bool UseLocal = !R.
empty();
2375 if (S.
isVisible(I) && Visited.insert(Nom).second)
2376 Queue.push_back(Nom);
2381 if (FoundTag && FoundNonTag)
2413 bool InUnqualifiedLookup) {
2414 assert(LookupCtx &&
"Sema::LookupQualifiedName requires a lookup context");
2420 assert((!isa<TagDecl>(LookupCtx) ||
2422 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2423 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2424 "Declaration context must already be complete!");
2426 struct QualifiedLookupInScope {
2430 QualifiedLookupInScope(
DeclContext *ctx) : Context(ctx) {
2433 ~QualifiedLookupInScope() {
2434 Context->setUseQualifiedLookup(oldVal);
2440 if (isa<CXXRecordDecl>(LookupCtx))
2463 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2496 for (Path.Decls = BaseRecord->
lookup(Name).
begin();
2497 Path.Decls != Path.Decls.
end(); ++Path.Decls) {
2498 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2505 Paths.setOrigin(LookupRec);
2518 int SubobjectNumber = 0;
2524 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2536 using Result =
const void *;
2538 auto Next = [&](Iterator &It, Iterator End) ->
Result {
2552 if (TemplateNameLookup)
2571 Iterator AIt = A, BIt = B, AEnd, BEnd;
2573 Result AResult = Next(AIt, AEnd);
2574 Result BResult = Next(BIt, BEnd);
2575 if (!AResult && !BResult)
2577 if (!AResult || !BResult)
2579 if (AResult != BResult) {
2582 llvm::SmallDenseMap<Result, bool, 32> AResults;
2583 for (; AResult; AResult = Next(AIt, AEnd))
2584 AResults.insert({AResult,
false});
2586 for (; BResult; BResult = Next(BIt, BEnd)) {
2587 auto It = AResults.find(BResult);
2588 if (It == AResults.end())
2595 return AResults.size() == Found;
2601 Path != PathEnd; ++Path) {
2606 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2609 if (SubobjectType.isNull()) {
2616 if (SubobjectType !=
2624 if (HasOnlyStaticMembers(Path->Decls) &&
2625 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2628 R.setAmbiguousBaseSubobjectTypes(Paths);
2642 if (HasOnlyStaticMembers(Path->Decls))
2647 R.setAmbiguousBaseSubobjects(Paths);
2658 if (
NamedDecl *ND = R.getAcceptableDecl(*I))
2710 bool AllowBuiltinCreation,
bool EnteringContext) {
2717 if (SS && SS->
isSet()) {
2741 return LookupName(R, S, AllowBuiltinCreation);
2758 for (
const auto &BaseSpec : Class->bases()) {
2767 for (
auto I =
Result.begin(), E =
Result.end(); I != E; ++I) {
2773 Result.suppressDiagnostics();
2787 assert(
Result.isAmbiguous() &&
"Lookup result must be ambiguous");
2793 switch (
Result.getAmbiguityKind()) {
2796 QualType SubobjectType = Paths->front().back().Base->getType();
2797 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2802 while (isa<CXXMethodDecl>(*Found) &&
2803 cast<CXXMethodDecl>(*Found)->isStatic())
2806 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2811 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2812 << Name << LookupRange;
2815 std::set<const NamedDecl *> DeclsPrinted;
2817 PathEnd = Paths->end();
2818 Path != PathEnd; ++Path) {
2822 if (DeclsPrinted.insert(D).second) {
2825 << TD->getUnderlyingType();
2837 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2842 if (
TagDecl *TD = dyn_cast<TagDecl>(D)) {
2843 TagDecls.insert(TD);
2844 Diag(TD->getLocation(), diag::note_hidden_tag);
2848 if (!isa<TagDecl>(D))
2854 if (TagDecls.count(F.
next()))
2862 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2872 struct AssociatedLookup {
2876 : S(S), Namespaces(Namespaces), Classes(Classes),
2877 InstantiationLoc(InstantiationLoc) {
2882 return ClassesTransitive.insert(RD);
2950 DeclContext *Ctx = ClassTemplate->getDeclContext();
2951 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2952 Result.Classes.insert(EnclosingClass);
2981 if (Class->getDeclName() ==
Result.S.VAListTagName)
2994 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2995 Result.Classes.insert(EnclosingClass);
3010 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
3011 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3012 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3013 Result.Classes.insert(EnclosingClass);
3018 for (
unsigned I = 0, N = TemplateArgs.
size(); I != N; ++I)
3024 if (!
Result.addClassTransitive(Class))
3029 Result.S.Context.getRecordType(Class)))
3035 Bases.push_back(Class);
3036 while (!Bases.empty()) {
3038 Class = Bases.pop_back_val();
3041 for (
const auto &
Base : Class->bases()) {
3052 if (
Result.addClassTransitive(BaseDecl)) {
3059 Bases.push_back(BaseDecl);
3087#define TYPE(Class, Base)
3088#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3089#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3090#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3091#define ABSTRACT_TYPE(Class, Base)
3092#include "clang/AST/TypeNodes.inc"
3105 case Type::ConstantArray:
3106 case Type::IncompleteArray:
3107 case Type::VariableArray:
3108 T = cast<ArrayType>(T)->getElementType().getTypePtr();
3121 case Type::Record: {
3123 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
3136 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3137 Result.Classes.insert(EnclosingClass);
3148 case Type::FunctionProto: {
3151 Queue.push_back(Arg.getTypePtr());
3155 case Type::FunctionNoProto: {
3170 case Type::MemberPointer: {
3174 Queue.push_back(MemberPtr->
getClass());
3182 case Type::BlockPointer:
3188 case Type::LValueReference:
3189 case Type::RValueReference:
3195 case Type::ExtVector:
3196 case Type::ConstantMatrix:
3203 case Type::DeducedTemplateSpecialization:
3209 case Type::ObjCObject:
3210 case Type::ObjCInterface:
3211 case Type::ObjCObjectPointer:
3212 Result.Namespaces.insert(
Result.S.Context.getTranslationUnitDecl());
3218 T = cast<AtomicType>(T)->getValueType().getTypePtr();
3221 T = cast<PipeType>(T)->getElementType().getTypePtr();
3227 T = Queue.pop_back_val();
3242 AssociatedNamespaces.clear();
3243 AssociatedClasses.clear();
3245 AssociatedLookup
Result(*
this, InstantiationLoc,
3246 AssociatedNamespaces, AssociatedClasses);
3255 for (
unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3256 Expr *Arg = Args[ArgIdx];
3298 return cast_or_null<ObjCProtocolDecl>(D);
3313 assert(!Operators.
isAmbiguous() &&
"Operator lookup cannot be ambiguous");
3323 bool VolatileThis) {
3325 "doing special member lookup into record that isn't fully complete");
3327 if (RValueThis || ConstThis || VolatileThis)
3329 "constructors and destructors always have unqualified lvalue this");
3330 if (ConstArg || VolatileArg)
3332 "parameter-less special members can't have qualified arguments");
3337 llvm::FoldingSetNodeID ID;
3340 ID.AddInteger(ConstArg);
3341 ID.AddInteger(VolatileArg);
3342 ID.AddInteger(RValueThis);
3343 ID.AddInteger(ConstThis);
3344 ID.AddInteger(VolatileThis);
3361 DeclareImplicitDestructor(RD);
3376 Expr *Arg =
nullptr;
3387 DeclareImplicitDefaultConstructor(RD);
3395 DeclareImplicitCopyConstructor(RD);
3400 DeclareImplicitMoveConstructor(RD);
3407 DeclareImplicitCopyAssignment(RD);
3412 DeclareImplicitMoveAssignment(RD);
3464 "lookup for a constructor or assignment operator was empty");
3465 Result->setMethod(
nullptr);
3474 for (
NamedDecl *CandDecl : Candidates) {
3475 if (CandDecl->isInvalidDecl())
3499 CtorInfo.FoundDecl,
nullptr,
3505 assert(isa<UsingDecl>(Cand.
getDecl()) &&
3506 "illegal Kind of operator = Decl");
3513 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3518 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3523 Result->setMethod(
nullptr);
3528 Result->setMethod(
nullptr);
3542 return cast_or_null<CXXConstructorDecl>(
Result.getMethod());
3549 "non-const, non-volatile qualifiers for copy ctor arg");
3554 return cast_or_null<CXXConstructorDecl>(
Result.getMethod());
3564 return cast_or_null<CXXConstructorDecl>(
Result.getMethod());
3572 if (Class->needsImplicitDefaultConstructor())
3573 DeclareImplicitDefaultConstructor(Class);
3574 if (Class->needsImplicitCopyConstructor())
3575 DeclareImplicitCopyConstructor(Class);
3576 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3577 DeclareImplicitMoveConstructor(Class);
3583 return Class->lookup(Name);
3588 unsigned Quals,
bool RValueThis,
3589 unsigned ThisQuals) {
3591 "non-const, non-volatile qualifiers for copy assignment arg");
3593 "non-const, non-volatile qualifiers for copy assignment this");
3600 return Result.getMethod();
3607 unsigned ThisQuals) {
3609 "non-const, non-volatile qualifiers for copy assignment this");
3616 return Result.getMethod();
3626 return cast_or_null<CXXDestructorDecl>(
3641 bool AllowTemplate,
bool AllowStringTemplatePack,
3645 "literal operator lookup can't be ambiguous");
3650 bool AllowCooked =
true;
3651 bool FoundRaw =
false;
3652 bool FoundTemplate =
false;
3653 bool FoundStringTemplatePack =
false;
3654 bool FoundCooked =
false;
3659 D = USD->getTargetDecl();
3668 bool IsTemplate =
false;
3669 bool IsStringTemplatePack =
false;
3670 bool IsCooked =
false;
3673 if (FD->getNumParams() == 1 &&
3674 FD->getParamDecl(0)->getType()->getAs<
PointerType>())
3676 else if (FD->getNumParams() == ArgTys.size()) {
3678 for (
unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3679 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3689 if (Params->
size() == 1) {
3712 IsStringTemplatePack =
true;
3716 if (AllowTemplate && StringLit && IsTemplate) {
3717 FoundTemplate =
true;
3719 AllowCooked =
false;
3720 AllowStringTemplatePack =
false;
3721 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3723 FoundRaw = FoundCooked = FoundStringTemplatePack =
false;
3725 }
else if (AllowCooked && IsCooked) {
3728 AllowTemplate = StringLit;
3729 AllowStringTemplatePack =
false;
3730 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3734 FoundRaw = FoundTemplate = FoundStringTemplatePack =
false;
3736 }
else if (AllowRaw && IsRaw) {
3738 }
else if (AllowTemplate && IsTemplate) {
3739 FoundTemplate =
true;
3740 }
else if (AllowStringTemplatePack && IsStringTemplatePack) {
3741 FoundStringTemplatePack =
true;
3751 if (StringLit && FoundTemplate)
3762 if (FoundRaw && FoundTemplate) {
3775 if (FoundStringTemplatePack)
3779 if (DiagnoseMissing) {
3782 << (ArgTys.size() == 2 ? ArgTys[1] :
QualType()) << AllowRaw
3783 << (AllowTemplate || AllowStringTemplatePack);
3795 if (Old ==
nullptr || Old == New) {
3806 Cursor = Cursor->getPreviousDecl();
3810 if (!Cursor)
return;
3813 if (Cursor == OldFD)
break;
3828 AssociatedNamespaces,
3842 for (
auto *
NS : AssociatedNamespaces) {
3862 auto *Underlying = D;
3863 if (
auto *USD = dyn_cast<UsingShadowDecl>(D))
3864 Underlying = USD->getTargetDecl();
3866 if (!isa<FunctionDecl>(Underlying) &&
3867 !isa<FunctionTemplateDecl>(Underlying))
3892 "bad export context");
3896 llvm::any_of(AssociatedClasses, [&](
auto *E) {
3900 if (!E->hasOwningModule() ||
3901 E->getOwningModule()->getTopLevelModuleName() !=
3926 if (AssociatedClasses.count(RD) &&
isReachable(D)) {
3935 Result.insert(Underlying);
3949class ShadowContextRAII;
3951class VisibleDeclsRecord {
3956 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3961 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3964 std::list<ShadowMap> ShadowMaps;
3969 friend class ShadowContextRAII;
3975 return !VisitedContexts.insert(Ctx).second;
3979 return VisitedContexts.count(Ctx);
3991 ShadowMaps.back()[ND->
getDeclName()].push_back(ND);
3996class ShadowContextRAII {
3997 VisibleDeclsRecord &Visible;
3999 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
4002 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
4003 Visible.ShadowMaps.emplace_back();
4006 ~ShadowContextRAII() {
4007 Visible.ShadowMaps.pop_back();
4015 std::list<ShadowMap>::reverse_iterator
SM = ShadowMaps.rbegin();
4016 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4017 SM != SMEnd; ++
SM) {
4019 if (Pos ==
SM->end())
4022 for (
auto *D : Pos->second) {
4040 SM == ShadowMaps.rbegin())
4045 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4046 cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4058class LookupVisibleHelper {
4062 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4063 LoadExternal(LoadExternal) {}
4066 bool IncludeGlobalScope) {
4070 UnqualUsingDirectiveSet UDirs(SemaRef);
4076 UDirs.visitScopeChain(Initial, S);
4082 Result.setAllowHidden(Consumer.includeHiddenDecls());
4083 if (!IncludeGlobalScope)
4085 ShadowContextRAII Shadow(Visited);
4086 lookupInScope(Initial, Result, UDirs);
4092 Result.setAllowHidden(Consumer.includeHiddenDecls());
4093 if (!IncludeGlobalScope)
4096 ShadowContextRAII Shadow(Visited);
4097 lookupInDeclContext(Ctx, Result,
true,
4103 bool QualifiedNameLookup,
bool InBaseClass) {
4111 Consumer.EnteredContext(Ctx);
4114 if (isa<TranslationUnitDecl>(Ctx) &&
4116 auto &S = Result.getSema();
4122 Idents.getExternalIdentifierLookup()) {
4123 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4124 for (StringRef Name = Iter->Next(); !Name.empty();
4125 Name = Iter->Next())
4130 for (
const auto &Ident : Idents) {
4135 if (
NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4136 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4147 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4151 bool Load = LoadExternal ||
4152 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4158 if (
auto *ND = Result.getAcceptableDecl(D)) {
4163 DeclsToVisit.push_back(ND);
4168 for (
auto *ND : DeclsToVisit) {
4169 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4172 DeclsToVisit.clear();
4175 if (QualifiedNameLookup) {
4176 ShadowContextRAII Shadow(Visited);
4178 if (!Result.getSema().isVisible(I))
4180 lookupInDeclContext(I->getNominatedNamespace(), Result,
4181 QualifiedNameLookup, InBaseClass);
4187 if (!
Record->hasDefinition())
4190 for (
const auto &B :
Record->bases()) {
4195 if (!IncludeDependentBases) {
4208 RD = TD->getTemplatedDecl();
4236 ShadowContextRAII Shadow(Visited);
4237 lookupInDeclContext(RD, Result, QualifiedNameLookup,
4245 for (
auto *Cat : IFace->visible_categories()) {
4246 ShadowContextRAII Shadow(Visited);
4247 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4252 for (
auto *I : IFace->all_referenced_protocols()) {
4253 ShadowContextRAII Shadow(Visited);
4254 lookupInDeclContext(I, Result, QualifiedNameLookup,
4259 if (IFace->getSuperClass()) {
4260 ShadowContextRAII Shadow(Visited);
4261 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4267 if (IFace->getImplementation()) {
4268 ShadowContextRAII Shadow(Visited);
4269 lookupInDeclContext(IFace->getImplementation(), Result,
4270 QualifiedNameLookup, InBaseClass);
4273 for (
auto *I :
Protocol->protocols()) {
4274 ShadowContextRAII Shadow(Visited);
4275 lookupInDeclContext(I, Result, QualifiedNameLookup,
4279 for (
auto *I :
Category->protocols()) {
4280 ShadowContextRAII Shadow(Visited);
4281 lookupInDeclContext(I, Result, QualifiedNameLookup,
4286 if (
Category->getImplementation()) {
4287 ShadowContextRAII Shadow(Visited);
4288 lookupInDeclContext(
Category->getImplementation(), Result,
4289 QualifiedNameLookup,
true);
4295 UnqualUsingDirectiveSet &UDirs) {
4298 assert(!IncludeDependentBases &&
"Unsupported flag for lookupInScope");
4303 if (!S->getEntity() ||
4304 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4305 (S->getEntity())->isFunctionOrMethod()) {
4306 FindLocalExternScope FindLocals(Result);
4310 for (
Decl *D : ScopeDecls) {
4311 if (
NamedDecl *ND = dyn_cast<NamedDecl>(D))
4312 if ((ND = Result.getAcceptableDecl(ND))) {
4313 Consumer.FoundDecl(ND, Visited.checkHidden(ND),
nullptr,
false);
4329 if (Method->isInstanceMethod()) {
4331 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4332 Result.getNameLoc(),
4335 lookupInDeclContext(IFace, IvarResult,
4350 lookupInDeclContext(Ctx, Result,
false,
4353 }
else if (!S->getParent()) {
4365 lookupInDeclContext(Entity, Result,
false,
4372 for (
const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4373 lookupInDeclContext(
4374 const_cast<DeclContext *
>(UUE.getNominatedNamespace()), Result,
4380 ShadowContextRAII Shadow(Visited);
4381 lookupInScope(S->getParent(), Result, UDirs);
4385 VisibleDeclsRecord Visited;
4387 bool IncludeDependentBases;
4394 bool IncludeGlobalScope,
bool LoadExternal) {
4395 LookupVisibleHelper H(
Consumer,
false,
4397 H.lookupVisibleDecls(*
this, S, Kind, IncludeGlobalScope);
4402 bool IncludeGlobalScope,
4403 bool IncludeDependentBases,
bool LoadExternal) {
4404 LookupVisibleHelper H(
Consumer, IncludeDependentBases, LoadExternal);
4405 H.lookupVisibleDecls(*
this, Ctx, Kind, IncludeGlobalScope);
4420 Scope *S = CurScope;
4422 return cast<LabelDecl>(Res);
4435 assert(S &&
"Not in a function?");
4438 return cast<LabelDecl>(Res);
4456 bool EnteringContext,
4457 bool isObjCIvarLookup,
4466 for (; DI != DE; ++DI)
4476 bool AnyVisibleDecls = !NewDecls.empty();
4478 for (; DI != DE; ++DI) {
4480 if (!AnyVisibleDecls) {
4482 AnyVisibleDecls =
true;
4485 NewDecls.push_back(*DI);
4486 }
else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4487 NewDecls.push_back(*DI);
4490 if (NewDecls.empty())
4507 Identifiers.clear();
4537 Identifiers.push_back(II);
4564 addName(Name,
nullptr);
4570 addName(Keyword,
nullptr,
nullptr,
true);
4573void TypoCorrectionConsumer::addName(StringRef Name,
NamedDecl *ND,
4577 StringRef TypoStr = Typo->
getName();
4578 unsigned MinED =
abs((
int)Name.size() - (
int)TypoStr.size());
4579 if (MinED && TypoStr.size() / MinED < 3)
4584 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4585 unsigned ED = TypoStr.edit_distance(Name,
true, UpperBound);
4586 if (ED > UpperBound)
return;
4589 if (isKeyword) TC.makeKeyword();
4590 TC.setCorrectionRange(
nullptr, Result.getLookupNameInfo());
4597 StringRef TypoStr = Typo->
getName();
4603 if (TypoStr.size() < 3 &&
4604 (Name != TypoStr || Correction.
getEditDistance(
true) > TypoStr.size()))
4617 if (!CList.empty() && !CList.back().isResolved())
4620 auto RI = llvm::find_if(CList, [NewND](
const TypoCorrection &TypoCorr) {
4623 if (RI != CList.end()) {
4627 auto IsDeprecated = [](
Decl *D) {
4638 std::pair<bool, std::string> NewKey = {
4642 std::pair<bool, std::string> PrevKey = {
4643 IsDeprecated(RI->getFoundDecl()),
4646 if (NewKey < PrevKey)
4651 if (CList.empty() || Correction.
isResolved())
4652 CList.push_back(Correction);
4655 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4659 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4660 SearchNamespaces =
true;
4662 for (
auto KNPair : KnownNamespaces)
4663 Namespaces.addNameSpecifier(KNPair.first);
4665 bool SSIsTemplate =
false;
4667 (SS && SS->isValid()) ? SS->getScopeRep() :
nullptr) {
4669 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4675 for (
unsigned I = 0; I != Types.size(); ++I) {
4676 const auto *TI = Types[I];
4678 CD = CD->getCanonicalDecl();
4679 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4680 !CD->isUnion() && CD->getIdentifier() &&
4681 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4682 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4683 Namespaces.addNameSpecifier(CD);
4689 if (++CurrentTCIndex < ValidatedCorrections.size())
4690 return ValidatedCorrections[CurrentTCIndex];
4692 CurrentTCIndex = ValidatedCorrections.size();
4693 while (!CorrectionResults.empty()) {
4694 auto DI = CorrectionResults.begin();
4695 if (DI->second.empty()) {
4696 CorrectionResults.erase(DI);
4700 auto RI = DI->second.begin();
4701 if (RI->second.empty()) {
4702 DI->second.erase(RI);
4703 performQualifiedLookups();
4709 ValidatedCorrections.push_back(TC);
4710 return ValidatedCorrections[CurrentTCIndex];
4713 return ValidatedCorrections[0];
4716bool TypoCorrectionConsumer::resolveCorrection(
TypoCorrection &Candidate) {
4723 CorrectionValidator->IsObjCIvarLookup,
4725 switch (Result.getResultKind()) {
4735 if (TempMemberContext) {
4738 TempMemberContext =
nullptr;
4741 if (SearchNamespaces)
4742 QualifiedResults.push_back(Candidate);
4752 for (
auto *TRD : Result)
4756 if (SearchNamespaces)
4757 QualifiedResults.push_back(Candidate);
4766void TypoCorrectionConsumer::performQualifiedLookups() {
4767 unsigned TypoLen = Typo->
getName().size();
4769 for (
const auto &NSI : Namespaces) {
4771 const Type *NSType = NSI.NameSpecifier->getAsType();
4779 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4784 TC.ClearCorrectionDecls();
4785 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4786 TC.setQualifierDistance(NSI.EditDistance);
4787 TC.setCallbackDistance(0);
4792 unsigned TmpED = TC.getEditDistance(
true);
4793 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4794 TypoLen / TmpED < 3)
4798 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4804 switch (Result.getResultKind()) {
4807 if (SS && SS->isValid()) {
4808 std::string NewQualified = TC.getAsString(SemaRef.
getLangOpts());
4809 std::string OldQualified;
4810 llvm::raw_string_ostream OldOStream(OldQualified);
4812 OldOStream << Typo->
getName();
4816 if (OldOStream.str() == NewQualified)
4820 TRD != TRDEnd; ++TRD) {
4825 TC.addCorrectionDecl(*TRD);
4827 if (TC.isResolved()) {
4828 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4841 QualifiedResults.clear();
4844TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4846 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4848 CurScopeSpec ? CurScopeSpec->
getScopeRep() :
nullptr) {
4849 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4857 for (
DeclContext *
C : llvm::reverse(CurContextChain)) {
4858 if (
auto *ND = dyn_cast_or_null<NamespaceDecl>(
C))
4865 DistanceMap[1].push_back(SI);
4868auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4870 assert(Start &&
"Building a context chain from a null context");
4871 DeclContextList Chain;
4883TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4885 unsigned NumSpecifiers = 0;
4887 if (
auto *ND = dyn_cast_or_null<NamespaceDecl>(
C)) {
4890 }
else if (
auto *RD = dyn_cast_or_null<RecordDecl>(
C)) {
4896 return NumSpecifiers;
4899void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4902 unsigned NumSpecifiers = 0;
4903 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4904 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4907 for (
DeclContext *
C : llvm::reverse(CurContextChain)) {
4908 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() !=
C)
4910 NamespaceDeclChain.pop_back();
4914 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4917 if (NamespaceDeclChain.empty()) {
4921 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4923 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4925 bool SameNameSpecifier =
false;
4926 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4927 std::string NewNameSpecifier;
4928 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4932 SpecifierOStream.flush();
4933 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4935 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
4939 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4947 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4951 llvm::ComputeEditDistance(
llvm::ArrayRef(CurNameSpecifierIdentifiers),
4955 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4956 DistanceMap[NumSpecifiers].push_back(SI);
4965 bool EnteringContext,
4966 bool isObjCIvarLookup,
4972 if (MemberContext) {
4974 if (isObjCIvarLookup) {
4975 if (
ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
5000 if (Method->isInstanceMethod() && Method->getClassInterface() &&
5005 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
5017 bool AfterNestedNameSpecifier) {
5018 if (AfterNestedNameSpecifier) {
5031 static const char *
const CTypeSpecs[] = {
5032 "char",
"const",
"double",
"enum",
"float",
"int",
"long",
"short",
5033 "signed",
"struct",
"union",
"unsigned",
"void",
"volatile",
5034 "_Complex",
"_Imaginary",
5036 "extern",
"inline",
"static",
"typedef"
5039 for (
const auto *CTS : CTypeSpecs)
5066 static const char *
const CastableTypeSpecs[] = {
5067 "char",
"double",
"float",
"int",
"long",
"short",
5068 "signed",
"unsigned",
"void"
5070 for (
auto *kw : CastableTypeSpecs)
5089 static const char *
const CXXExprs[] = {
5090 "delete",
"new",
"operator",
"throw",
"typeid"
5092 for (
const auto *CE : CXXExprs)
5095 if (isa<CXXMethodDecl>(SemaRef.
CurContext) &&
5096 cast<CXXMethodDecl>(SemaRef.
CurContext)->isInstance())
5115 static const char *
const CStmts[] = {
5116 "do",
"else",
"for",
"goto",
"if",
"return",
"switch",
"while" };
5117 for (
const auto *CS : CStmts)
5125 if (S && S->getBreakParent())
5128 if (S && S->getContinueParent())
5142 if (S && S->isClassScope()) {
5162std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5200 locs->second.count(TypoName.
getLoc()))
5230 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.
clone();
5231 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5232 *
this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5236 bool IsUnqualifiedLookup =
false;
5238 if (MemberContext) {
5243 for (
auto *I : OPT->
quals())
5246 }
else if (SS && SS->
isSet()) {
5253 IsUnqualifiedLookup =
true;
5258 bool SearchNamespaces
5260 (IsUnqualifiedLookup || (SS && SS->
isSet()));
5262 if (IsUnqualifiedLookup || SearchNamespaces) {
5273 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5275 StringRef Name = Iter->Next();
5285 *
Consumer->getCorrectionValidator(),
5290 if (SearchNamespaces) {
5292 if (ExternalSource && !LoadedExternalKnownNamespaces) {
5294 LoadedExternalKnownNamespaces =
true;
5295 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5296 for (
auto *N : ExternalKnownNamespaces)
5297 KnownNamespaces[N] =
true;
5300 Consumer->addNamespaces(KnownNamespaces);
5343 bool EnteringContext,
5345 bool RecordFailure) {
5348 if (ExternalSource) {
5350 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5351 MemberContext, EnteringContext, OPT))
5362 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5363 MemberContext, EnteringContext,
5371 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
5375 unsigned ED =
Consumer->getBestEditDistance(
true);
5376 unsigned TypoLen = Typo->getName().size();
5377 if (ED > 0 && TypoLen / ED < 3)
5378 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
5383 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
5387 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5391 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
5395 if (!SecondBestTC ||
5401 if (ED == 0 &&
Result.isKeyword())
5402 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);