39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/StringMap.h"
43 #include "llvm/ADT/TinyPtrVector.h"
44 #include "llvm/ADT/edit_distance.h"
45 #include "llvm/Support/ErrorHandling.h"
55 using namespace clang;
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 {
99 llvm::SmallPtrSet<DeclContext*, 8> visited;
102 UnqualUsingDirectiveSet() {}
104 void visitScopeChain(
Scope *
S,
Scope *InnermostFileScope) {
121 visit(I, InnermostFileDC);
134 if (!visited.insert(DC).second)
137 addUsingDirectives(DC, EffectiveDC);
145 if (!visited.insert(NS).second)
148 addUsingDirective(UD, EffectiveDC);
149 addUsingDirectives(NS, EffectiveDC);
160 if (visited.insert(NS).second) {
161 addUsingDirective(UD, EffectiveDC);
169 DC = queue.pop_back_val();
184 while (!Common->
Encloses(EffectiveDC))
192 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
195 typedef ListTy::const_iterator const_iterator;
197 const_iterator begin()
const {
return list.begin(); }
198 const_iterator end()
const {
return list.end(); }
200 llvm::iterator_range<const_iterator>
202 return llvm::make_range(std::equal_range(begin(), end(),
204 UnqualUsingEntry::Comparator()));
213 bool Redeclaration) {
233 assert(!Redeclaration &&
"cannot do redeclaration operator lookup");
272 assert(Redeclaration &&
"should only be used for redecl lookup");
291 void LookupResult::configure() {
293 isForRedeclaration());
298 switch (NameInfo.getName().getCXXOverloadedOperator()) {
302 case OO_Array_Delete:
303 getSema().DeclareGlobalNewDelete();
313 if (
unsigned BuiltinID = Id->getBuiltinID()) {
314 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
320 bool LookupResult::sanity()
const {
322 assert(ResultKind != NotFound || Decls.size() == 0);
323 assert(ResultKind != Found || Decls.size() == 1);
324 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
325 (Decls.size() == 1 &&
326 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
327 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
328 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
329 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
330 Ambiguity == AmbiguousBaseSubobjectTypes)));
331 assert((Paths !=
nullptr) == (ResultKind == Ambiguous &&
332 (Ambiguity == AmbiguousBaseSubobjectTypes ||
333 Ambiguity == AmbiguousBaseSubobjects)));
359 unsigned N = Decls.size();
363 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
370 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
371 if (isa<FunctionTemplateDecl>(D))
372 ResultKind = FoundOverloaded;
373 else if (isa<UnresolvedUsingValueDecl>(D))
374 ResultKind = FoundUnresolvedValue;
379 if (ResultKind == Ambiguous)
return;
381 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
382 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
384 bool Ambiguous =
false;
385 bool HasTag =
false, HasFunction =
false, HasNonFunction =
false;
386 bool HasFunctionTemplate =
false, HasUnresolved =
false;
388 unsigned UniqueTagIndex = 0;
397 Decls[I] = Decls[--N];
405 if (
TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
406 if (!TD->getDeclContext()->isRecord()) {
407 QualType T = getSema().Context.getTypeDeclType(TD);
411 Decls[I] = Decls[--N];
417 if (!Unique.insert(D).second) {
424 Decls[I] = Decls[--N];
430 if (isa<UnresolvedUsingValueDecl>(D)) {
431 HasUnresolved =
true;
432 }
else if (isa<TagDecl>(D)) {
437 }
else if (isa<FunctionTemplateDecl>(D)) {
439 HasFunctionTemplate =
true;
440 }
else if (isa<FunctionDecl>(D)) {
445 HasNonFunction =
true;
459 if (HideTags && HasTag && !Ambiguous &&
460 (HasFunction || HasNonFunction || HasUnresolved)) {
463 Decls[UniqueTagIndex] = Decls[--N];
470 if (HasNonFunction && (HasFunction || HasUnresolved))
475 else if (HasUnresolved)
477 else if (N > 1 || HasFunctionTemplate)
483 void LookupResult::addDeclsFromBasePaths(
const CXXBasePaths &
P) {
485 for (I = P.
begin(), E = P.
end(); I != E; ++I)
487 DE = I->Decls.end(); DI != DE; ++DI)
494 addDeclsFromBasePaths(*Paths);
496 setAmbiguous(AmbiguousBaseSubobjects);
502 addDeclsFromBasePaths(*Paths);
504 setAmbiguous(AmbiguousBaseSubobjectTypes);
508 Out << Decls.size() <<
" result(s)";
509 if (isAmbiguous()) Out <<
", ambiguous";
510 if (Paths) Out <<
", base paths present";
512 for (
iterator I = begin(), E = end(); I != E; ++I) {
577 DeclareImplicitDefaultConstructor(Class);
581 DeclareImplicitCopyConstructor(Class);
585 DeclareImplicitCopyAssignment(Class);
587 if (getLangOpts().CPlusPlus11) {
590 DeclareImplicitMoveConstructor(Class);
594 DeclareImplicitMoveAssignment(Class);
599 DeclareImplicitDestructor(Class);
630 if (
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
633 if (Record->needsImplicitDefaultConstructor())
635 if (Record->needsImplicitCopyConstructor())
638 Record->needsImplicitMoveConstructor())
644 if (
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
645 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
654 if (
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
657 if (Record->needsImplicitCopyAssignment())
660 Record->needsImplicitMoveAssignment())
697 !isa<CXXRecordDecl>(DC))
739 assert(ConvProto &&
"Nonsensical conversion function template type");
754 Specialization, Info)
769 assert(NS && NS->
isFileContext() &&
"CppNamespaceLookup() requires namespace!");
776 for (
const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
803 if (OuterS->getEntity()) {
804 Lexical = OuterS->getEntity();
831 if (!Lexical || !DC || !S->
getParent() ||
833 return std::make_pair(Lexical,
false);
839 while (OutermostTemplateScope->
getParent() &&
841 OutermostTemplateScope = OutermostTemplateScope->
getParent();
855 return std::make_pair(Semantic,
true);
857 return std::make_pair(Lexical,
false);
863 struct FindLocalExternScope {
865 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
866 Decl::IDNS_LocalExtern) {
872 ~FindLocalExternScope() {
876 bool OldFindLocalExtern;
881 assert(getLangOpts().
CPlusPlus &&
"Can perform only C++ lookup");
899 I = IdResolver.begin(Name),
900 IEnd = IdResolver.end();
920 UnqualUsingDirectiveSet UDirs;
921 bool VisitedUsingDirectives =
false;
922 bool LeftStartingScope =
false;
926 FindLocalExternScope FindLocals(R);
935 if (NameKind == LookupRedeclarationWithLinkage) {
938 if (!LeftStartingScope && !Initial->
isDeclScope(*I))
939 LeftStartingScope =
true;
944 if (LeftStartingScope && !((*I)->hasLinkage()) &&
945 !(*I)->isTemplateParameter()) {
958 if (
CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
963 if (NameKind == LookupLocalFriendName && !S->
isClassScope()) {
979 Ctx = OutsideOfTemplateParamDC;
980 OutsideOfTemplateParamDC =
nullptr;
985 bool SearchAfterTemplateScope;
987 if (SearchAfterTemplateScope)
988 OutsideOfTemplateParamDC = OuterCtx;
1007 if (
ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1026 if (!VisitedUsingDirectives) {
1029 if (UCtx->isTransparentContext())
1032 UDirs.visit(UCtx, UCtx);
1037 Scope *InnermostFileScope =
S;
1038 while (InnermostFileScope &&
1040 InnermostFileScope = InnermostFileScope->
getParent();
1041 UDirs.visitScopeChain(Initial, InnermostFileScope);
1045 VisitedUsingDirectives =
true;
1062 if (LookupQualifiedName(R, Ctx,
true))
1070 if (!S)
return false;
1073 if (NameKind == LookupMemberName)
1081 if (!VisitedUsingDirectives) {
1082 UDirs.visitScopeChain(Initial, S);
1089 FindLocals.restore();
1122 Ctx = OutsideOfTemplateParamDC;
1123 OutsideOfTemplateParamDC =
nullptr;
1128 bool SearchAfterTemplateScope;
1130 if (SearchAfterTemplateScope)
1131 OutsideOfTemplateParamDC = OuterCtx;
1145 "We should have been looking only at file context here already.");
1178 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1181 "hidden entity from AST file has no owning module");
1183 if (!getLangOpts().ModulesLocalVisibility) {
1189 assert(Parent->isHidden() &&
"unexpectedly hidden decl");
1190 return getOwningModule(Parent);
1198 if (
auto *Containing =
1199 PP.getModuleContainingLocation(Entity->
getLocation())) {
1204 cast<NamedDecl>(Entity)->setHidden(
false);
1209 if (!CachedFakeTopLevelModule) {
1210 CachedFakeTopLevelModule =
1211 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1212 "<top-level>",
nullptr,
false,
false).first;
1214 auto &SrcMgr = PP.getSourceManager();
1216 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1218 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1219 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1222 M = CachedFakeTopLevelModule;
1231 if (
auto *M = PP.getModuleContainingLocation(Loc))
1239 if (
auto *TD = dyn_cast<TemplateDecl>(ND))
1240 for (
auto *Param : *TD->getTemplateParameters())
1241 makeMergedDefinitionVisible(Param, Loc);
1246 if (
FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1251 }
else if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1254 }
else if (
EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1257 }
else if (
VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1272 unsigned N = ActiveTemplateInstantiations.size();
1273 for (
unsigned I = ActiveTemplateInstantiationLookupModules.size();
1277 if (M && !LookupModulesCache.insert(M).second)
1279 ActiveTemplateInstantiationLookupModules.push_back(M);
1281 return LookupModulesCache;
1286 if (isModuleVisible(Merged))
1291 template<
typename ParmDecl>
1295 if (!D->hasDefaultArgument())
1299 auto &DefaultArg = D->getDefaultArgStorage();
1300 if (!DefaultArg.isInherited() && S.
isVisible(D))
1303 if (!DefaultArg.isInherited() && Modules) {
1304 auto *NonConstD =
const_cast<ParmDecl*
>(D);
1307 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1311 D = DefaultArg.getInheritedFrom();
1318 if (
auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1320 if (
auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1334 bool LookupResult::isVisibleSlow(
Sema &SemaRef,
NamedDecl *D) {
1335 assert(D->
isHidden() &&
"should not call this: not in slow case");
1339 assert(!D->
isHidden() &&
"hidden decl not from a module");
1350 if (SemaRef.
getLangOpts().ModulesLocalVisibility &&
1364 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1365 : SemaRef.hasVisibleDefinition(cast<
NamedDecl>(DC))) {
1380 if (LookupModules.empty())
1384 if (LookupModules.count(DeclModule))
1394 E = LookupModules.end();
1396 if ((*I)->isModuleVisible(DeclModule))
1401 bool Sema::isVisibleSlow(
const NamedDecl *D) {
1416 for (
auto RD : D->
redecls()) {
1417 if (
auto ND = dyn_cast<NamedDecl>(RD)) {
1463 if (!Name)
return false;
1478 FindLocalExternScope FindLocals(R);
1484 bool LeftStartingScope =
false;
1487 IEnd = IdResolver.end();
1490 if (NameKind == LookupRedeclarationWithLinkage) {
1494 LeftStartingScope =
true;
1498 if (LeftStartingScope && !((*I)->hasLinkage())) {
1503 else if (NameKind == LookupObjCImplicitSelfParam &&
1504 !isa<ImplicitParamDecl>(*I))
1529 for (++LastI; LastI != IEnd; ++LastI) {
1554 if (CppLookupName(R, S))
1568 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1600 assert(StartDC->
isFileContext() &&
"start context is not a file context");
1603 if (UsingDirectives.begin() == UsingDirectives.end())
return false;
1606 llvm::SmallPtrSet<DeclContext*, 8> Visited;
1607 Visited.insert(StartDC);
1615 for (
auto *I : UsingDirectives) {
1616 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
1617 if (Visited.insert(ND).second)
1618 Queue.push_back(ND);
1625 bool FoundTag =
false;
1626 bool FoundNonTag =
false;
1631 while (!Queue.empty()) {
1636 bool UseLocal = !R.
empty();
1665 if (Visited.insert(Nom).second)
1666 Queue.push_back(Nom);
1671 if (FoundTag && FoundNonTag)
1693 template<
typename InputIterator>
1696 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1699 if (isa<CXXMethodDecl>(D)) {
1701 bool AllMethodsAreStatic =
true;
1702 for(; First !=
Last; ++First) {
1703 D = (*First)->getUnderlyingDecl();
1705 if (!isa<CXXMethodDecl>(D)) {
1706 assert(isa<TagDecl>(D) &&
"Non-function must be a tag decl");
1710 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1711 AllMethodsAreStatic =
false;
1716 if (AllMethodsAreStatic)
1746 bool InUnqualifiedLookup) {
1747 assert(LookupCtx &&
"Sema::LookupQualifiedName requires a lookup context");
1753 assert((!isa<TagDecl>(LookupCtx) ||
1755 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1756 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
1757 "Declaration context must already be complete!");
1762 if (isa<CXXRecordDecl>(LookupCtx))
1807 case LookupObjCImplicitSelfParam:
1808 case LookupOrdinaryName:
1809 case LookupMemberName:
1810 case LookupRedeclarationWithLinkage:
1811 case LookupLocalFriendName:
1823 case LookupUsingDeclName:
1826 case LookupOperatorName:
1827 case LookupNamespaceName:
1828 case LookupObjCProtocolName:
1833 case LookupNestedNameSpecifierName:
1851 int SubobjectNumber = 0;
1855 Path != PathEnd; ++Path) {
1860 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1863 if (SubobjectType.
isNull()) {
1880 while (FirstD != FirstPath->Decls.end() &&
1881 CurrentD != Path->Decls.end()) {
1882 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1883 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1890 if (FirstD == FirstPath->Decls.end() &&
1891 CurrentD == Path->Decls.end())
1946 return LookupInSuper(R, NNS->getAsRecordDecl());
1949 return LookupQualifiedName(R, LookupCtx);
1972 bool AllowBuiltinCreation,
bool EnteringContext) {
1979 if (SS && SS->
isSet()) {
1984 if (
DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1991 return LookupQualifiedName(R, DC);
2003 return LookupName(R, S, AllowBuiltinCreation);
2016 for (
const auto &BaseSpec : Class->
bases()) {
2018 BaseSpec.getType()->castAs<
RecordType>()->getDecl());
2021 LookupQualifiedName(
Result, RD);
2036 assert(Result.
isAmbiguous() &&
"Lookup result must be ambiguous");
2045 QualType SubobjectType = Paths->
front().back().Base->getType();
2046 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2047 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2051 while (isa<CXXMethodDecl>(*Found) &&
2052 cast<CXXMethodDecl>(*Found)->isStatic())
2055 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2060 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2061 << Name << LookupRange;
2064 std::set<Decl *> DeclsPrinted;
2066 PathEnd = Paths->
end();
2067 Path != PathEnd; ++Path) {
2068 Decl *D = Path->Decls.front();
2069 if (DeclsPrinted.insert(D).second)
2076 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2078 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
2080 for (
auto *D : Result)
2081 if (
TagDecl *TD = dyn_cast<TagDecl>(D)) {
2082 TagDecls.insert(TD);
2083 Diag(TD->getLocation(), diag::note_hidden_tag);
2086 for (
auto *D : Result)
2087 if (!isa<TagDecl>(D))
2093 if (TagDecls.count(F.
next()))
2101 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2103 for (
auto *D : Result)
2111 struct AssociatedLookup {
2115 : S(S), Namespaces(Namespaces), Classes(Classes),
2116 InstantiationLoc(InstantiationLoc) {
2173 DeclContext *Ctx = ClassTemplate->getDeclContext();
2174 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2175 Result.Classes.insert(EnclosingClass);
2205 if (Class->
getDeclName() == Result.S.VAListTagName)
2218 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2219 Result.Classes.insert(EnclosingClass);
2229 if (!Result.Classes.insert(Class).second)
2242 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2243 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2244 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2245 Result.Classes.insert(EnclosingClass);
2250 for (
unsigned I = 0, N = TemplateArgs.
size(); I != N; ++I)
2261 Bases.push_back(Class);
2262 while (!Bases.empty()) {
2264 Class = Bases.pop_back_val();
2267 for (
const auto &
Base : Class->
bases()) {
2278 if (Result.Classes.insert(BaseDecl).second) {
2285 Bases.push_back(BaseDecl);
2313 #define TYPE(Class, Base)
2314 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2315 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2316 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2317 #define ABSTRACT_TYPE(Class, Base)
2318 #include "clang/AST/TypeNodes.def"
2329 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2331 case Type::ConstantArray:
2332 case Type::IncompleteArray:
2333 case Type::VariableArray:
2347 case Type::Record: {
2348 Result.S.RequireCompleteType(Result.InstantiationLoc,
QualType(T, 0),
2351 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2361 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2364 if (
CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2365 Result.Classes.insert(EnclosingClass);
2376 case Type::FunctionProto: {
2379 Queue.push_back(Arg.getTypePtr());
2382 case Type::FunctionNoProto: {
2397 case Type::MemberPointer: {
2401 Queue.push_back(MemberPtr->
getClass());
2409 case Type::BlockPointer:
2410 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2415 case Type::LValueReference:
2416 case Type::RValueReference:
2417 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2422 case Type::ExtVector:
2433 case Type::ObjCObject:
2434 case Type::ObjCInterface:
2435 case Type::ObjCObjectPointer:
2436 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2442 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2448 T = Queue.pop_back_val();
2463 AssociatedNamespaces.clear();
2464 AssociatedClasses.clear();
2466 AssociatedLookup
Result(*
this, InstantiationLoc,
2467 AssociatedNamespaces, AssociatedClasses);
2476 for (
unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2477 Expr *Arg = Args[ArgIdx];
2494 Arg = unaryOp->getSubExpr();
2499 for (
const auto *D : ULE->
decls()) {
2523 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2524 LookupObjCProtocolName, Redecl);
2525 return cast_or_null<ObjCProtocolDecl>(D);
2539 LookupName(Operators, S);
2541 assert(!Operators.
isAmbiguous() &&
"Operator lookup cannot be ambiguous");
2551 bool VolatileThis) {
2553 "doing special member lookup into record that isn't fully complete");
2555 if (RValueThis || ConstThis || VolatileThis)
2556 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2557 "constructors and destructors always have unqualified lvalue this");
2558 if (ConstArg || VolatileArg)
2559 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2560 "parameter-less special members can't have qualified arguments");
2562 llvm::FoldingSetNodeID
ID;
2565 ID.AddInteger(ConstArg);
2566 ID.AddInteger(VolatileArg);
2567 ID.AddInteger(RValueThis);
2568 ID.AddInteger(ConstThis);
2569 ID.AddInteger(VolatileThis);
2573 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2581 SpecialMemberCache.InsertNode(Result, InsertPoint);
2583 if (SM == CXXDestructor) {
2585 DeclareImplicitDestructor(RD);
2587 assert(DD &&
"record without a destructor");
2590 SpecialMemberOverloadResult::NoMemberOrDeleted :
2591 SpecialMemberOverloadResult::Success);
2599 Expr *Arg =
nullptr;
2605 if (SM == CXXDefaultConstructor) {
2609 DeclareImplicitDefaultConstructor(RD);
2611 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2614 DeclareImplicitCopyConstructor(RD);
2616 DeclareImplicitMoveConstructor(RD);
2620 DeclareImplicitCopyAssignment(RD);
2622 DeclareImplicitMoveAssignment(RD);
2637 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2645 if (SM != CXXDefaultConstructor) {
2671 assert(SM == CXXDefaultConstructor &&
2672 "lookup for a constructor or assignment operator was empty");
2674 Result->
setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2682 for (
auto *Cand : Candidates) {
2683 if (Cand->isInvalidDecl())
2691 Cand = U->getTargetDecl();
2693 if (Cand->isInvalidDecl())
2698 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2700 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2704 llvm::makeArrayRef(&Arg, NumArgs), OCS,
true);
2706 dyn_cast<FunctionTemplateDecl>(Cand)) {
2707 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2709 RD,
nullptr, ThisTy, Classification,
2710 llvm::makeArrayRef(&Arg, NumArgs),
2714 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
2717 assert(isa<UsingDecl>(Cand) &&
"illegal Kind of operator = Decl");
2724 Result->
setMethod(cast<CXXMethodDecl>(Best->Function));
2725 Result->
setKind(SpecialMemberOverloadResult::Success);
2729 Result->
setMethod(cast<CXXMethodDecl>(Best->Function));
2730 Result->
setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2735 Result->
setKind(SpecialMemberOverloadResult::Ambiguous);
2740 Result->
setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2750 LookupSpecialMember(Class, CXXDefaultConstructor,
false,
false,
false,
2753 return cast_or_null<CXXConstructorDecl>(Result->
getMethod());
2760 "non-const, non-volatile qualifiers for copy ctor arg");
2765 return cast_or_null<CXXConstructorDecl>(Result->
getMethod());
2775 return cast_or_null<CXXConstructorDecl>(Result->
getMethod());
2783 DeclareImplicitDefaultConstructor(Class);
2785 DeclareImplicitCopyConstructor(Class);
2787 DeclareImplicitMoveConstructor(Class);
2792 return Class->
lookup(Name);
2797 unsigned Quals,
bool RValueThis,
2798 unsigned ThisQuals) {
2800 "non-const, non-volatile qualifiers for copy assignment arg");
2802 "non-const, non-volatile qualifiers for copy assignment this");
2806 ThisQuals & Qualifiers::Const,
2807 ThisQuals & Qualifiers::Volatile);
2816 unsigned ThisQuals) {
2818 "non-const, non-volatile qualifiers for copy assignment this");
2822 ThisQuals & Qualifiers::Const,
2823 ThisQuals & Qualifiers::Volatile);
2835 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2836 false,
false,
false,
2837 false,
false)->getMethod());
2849 bool AllowRaw,
bool AllowTemplate,
2850 bool AllowStringTemplate) {
2853 "literal operator lookup can't be ambiguous");
2858 bool FoundRaw =
false;
2859 bool FoundTemplate =
false;
2860 bool FoundStringTemplate =
false;
2861 bool FoundExactMatch =
false;
2863 while (F.hasNext()) {
2866 D = USD->getTargetDecl();
2875 bool IsTemplate =
false;
2876 bool IsStringTemplate =
false;
2877 bool IsExactMatch =
false;
2880 if (FD->getNumParams() == 1 &&
2881 FD->getParamDecl(0)->getType()->getAs<
PointerType>())
2883 else if (FD->getNumParams() == ArgTys.size()) {
2884 IsExactMatch =
true;
2885 for (
unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2886 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2888 IsExactMatch =
false;
2896 if (Params->
size() == 1)
2899 IsStringTemplate =
true;
2903 FoundExactMatch =
true;
2905 AllowTemplate =
false;
2906 AllowStringTemplate =
false;
2907 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
2911 FoundRaw = FoundTemplate = FoundStringTemplate =
false;
2913 }
else if (AllowRaw && IsRaw) {
2915 }
else if (AllowTemplate && IsTemplate) {
2916 FoundTemplate =
true;
2917 }
else if (AllowStringTemplate && IsStringTemplate) {
2918 FoundStringTemplate =
true;
2929 if (FoundExactMatch)
2934 if (FoundRaw && FoundTemplate) {
2937 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
2945 return LOLR_Template;
2947 if (FoundStringTemplate)
2948 return LOLR_StringTemplate;
2953 << (ArgTys.size() == 2 ? ArgTys[1] :
QualType()) << AllowRaw
2954 << (AllowTemplate || AllowStringTemplate);
2963 if (Old ==
nullptr || Old == New) {
2978 if (!Cursor)
return;
2981 if (Cursor == OldFD)
break;
2995 FindAssociatedClassesAndNamespaces(Loc, Args,
2996 AssociatedNamespaces,
3010 for (
auto *NS : AssociatedNamespaces) {
3031 bool DeclaredInAssociatedClass =
false;
3034 if (isa<CXXRecordDecl>(LexDC) &&
3035 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
3036 DeclaredInAssociatedClass =
true;
3040 if (!DeclaredInAssociatedClass)
3044 if (isa<UsingShadowDecl>(D))
3045 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3047 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
3067 class ShadowContextRAII;
3069 class VisibleDeclsRecord {
3074 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3079 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3082 std::list<ShadowMap> ShadowMaps;
3085 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3087 friend class ShadowContextRAII;
3093 return !VisitedContexts.insert(Ctx).second;
3097 return VisitedContexts.count(Ctx);
3109 ShadowMaps.back()[ND->
getDeclName()].push_back(ND);
3114 class ShadowContextRAII {
3115 VisibleDeclsRecord &Visible;
3117 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3120 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3121 Visible.ShadowMaps.emplace_back();
3124 ~ShadowContextRAII() {
3125 Visible.ShadowMaps.pop_back();
3136 std::list<ShadowMap>::reverse_iterator
SM = ShadowMaps.rbegin();
3137 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3138 SM != SMEnd; ++
SM) {
3139 ShadowMap::iterator Pos = SM->find(ND->
getDeclName());
3140 if (Pos == SM->end())
3143 for (
auto *D : Pos->second) {
3161 SM == ShadowMaps.rbegin())
3173 bool QualifiedNameLookup,
3176 VisibleDeclsRecord &Visited) {
3185 if (isa<TranslationUnitDecl>(Ctx) &&
3188 auto &Idents = S.Context.Idents;
3192 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3193 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3198 for (
const auto &Ident : Idents) {
3199 for (
auto I = S.IdResolver.begin(Ident.getValue()),
3200 E = S.IdResolver.end();
3202 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3204 Consumer.
FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3221 Consumer.
FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3228 if (QualifiedNameLookup) {
3229 ShadowContextRAII Shadow(Visited);
3232 QualifiedNameLookup, InBaseClass, Consumer, Visited);
3238 if (!Record->hasDefinition())
3241 for (
const auto &B : Record->bases()) {
3273 ShadowContextRAII Shadow(Visited);
3275 true, Consumer, Visited);
3282 for (
auto *Cat : IFace->visible_categories()) {
3283 ShadowContextRAII Shadow(Visited);
3289 for (
auto *I : IFace->all_referenced_protocols()) {
3290 ShadowContextRAII Shadow(Visited);
3296 if (IFace->getSuperClass()) {
3297 ShadowContextRAII Shadow(Visited);
3299 true, Consumer, Visited);
3304 if (IFace->getImplementation()) {
3305 ShadowContextRAII Shadow(Visited);
3307 QualifiedNameLookup, InBaseClass, Consumer, Visited);
3310 for (
auto *I : Protocol->protocols()) {
3311 ShadowContextRAII Shadow(Visited);
3316 for (
auto *I : Category->protocols()) {
3317 ShadowContextRAII Shadow(Visited);
3323 if (Category->getImplementation()) {
3324 ShadowContextRAII Shadow(Visited);
3326 QualifiedNameLookup,
true, Consumer, Visited);
3332 UnqualUsingDirectiveSet &UDirs,
3334 VisibleDeclsRecord &Visited) {
3340 !Visited.alreadyVisitedContext(S->
getEntity())) ||
3342 FindLocalExternScope FindLocals(Result);
3344 for (
auto *D : S->
decls()) {
3345 if (
NamedDecl *ND = dyn_cast<NamedDecl>(D))
3347 Consumer.
FoundDecl(ND, Visited.checkHidden(ND),
nullptr,
false);
3365 if (Method->isInstanceMethod()) {
3371 false, Consumer, Visited);
3385 false, Consumer, Visited);
3399 false, Consumer, Visited);
3405 for (
const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3408 false, Consumer, Visited);
3412 ShadowContextRAII Shadow(Visited);
3418 bool IncludeGlobalScope) {
3422 UnqualUsingDirectiveSet UDirs;
3428 UDirs.visitScopeChain(Initial, S);
3435 VisibleDeclsRecord Visited;
3436 if (!IncludeGlobalScope)
3438 ShadowContextRAII Shadow(Visited);
3444 bool IncludeGlobalScope) {
3447 VisibleDeclsRecord Visited;
3448 if (!IncludeGlobalScope)
3450 ShadowContextRAII Shadow(Visited);
3452 false, Consumer, Visited);
3467 Scope *S = CurScope;
3468 PushOnScopeChains(Res, S,
true);
3469 return cast<LabelDecl>(Res);
3473 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3482 assert(S &&
"Not in a function?");
3483 PushOnScopeChains(Res, S,
true);
3485 return cast<LabelDecl>(Res);
3503 bool EnteringContext,
3504 bool isObjCIvarLookup,
3516 for (; DI != DE; ++DI)
3524 bool AnyVisibleDecls = !NewDecls.empty();
3526 for (; DI != DE; ++DI) {
3532 if (!AnyVisibleDecls) {
3534 AnyVisibleDecls =
true;
3537 NewDecls.push_back(VisibleDecl);
3538 }
else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3539 NewDecls.push_back(*DI);
3542 if (NewDecls.empty())
3559 Identifiers.clear();
3589 Identifiers.push_back(II);
3617 addName(Name,
nullptr);
3623 addName(Keyword,
nullptr,
nullptr,
true);
3626 void TypoCorrectionConsumer::addName(StringRef Name,
NamedDecl *ND,
3630 StringRef TypoStr =
Typo->getName();
3631 unsigned MinED = abs((
int)Name.size() - (int)TypoStr.size());
3632 if (MinED && TypoStr.size() / MinED < 3)
3637 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3638 unsigned ED = TypoStr.edit_distance(Name,
true, UpperBound);
3639 if (ED >= UpperBound)
return;
3643 TC.setCorrectionRange(
nullptr,
Result.getLookupNameInfo());
3650 StringRef TypoStr =
Typo->getName();
3656 if (TypoStr.size() < 3 &&
3657 (Name != TypoStr || Correction.
getEditDistance(
true) > TypoStr.size()))
3670 if (!CList.empty() && !CList.back().isResolved())
3674 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3675 RI != RIEnd; ++RI) {
3680 if (RI->getCorrectionDecl() == NewND) {
3681 if (CorrectionStr < RI->getAsString(SemaRef.
getLangOpts()))
3687 if (CList.empty() || Correction.
isResolved())
3688 CList.push_back(Correction);
3691 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3695 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3696 SearchNamespaces =
true;
3698 for (
auto KNPair : KnownNamespaces)
3699 Namespaces.addNameSpecifier(KNPair.first);
3701 bool SSIsTemplate =
false;
3703 (SS && SS->isValid()) ? SS->getScopeRep() :
nullptr) {
3704 if (
const Type *T = NNS->getAsType())
3705 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3709 CD = CD->getCanonicalDecl();
3710 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3711 !CD->isUnion() && CD->getIdentifier() &&
3712 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3713 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3714 Namespaces.addNameSpecifier(CD);
3720 if (++CurrentTCIndex < ValidatedCorrections.size())
3721 return ValidatedCorrections[CurrentTCIndex];
3723 CurrentTCIndex = ValidatedCorrections.size();
3724 while (!CorrectionResults.empty()) {
3725 auto DI = CorrectionResults.
begin();
3726 if (DI->second.empty()) {
3727 CorrectionResults.erase(DI);
3731 auto RI = DI->second.begin();
3732 if (RI->second.empty()) {
3733 DI->second.erase(RI);
3734 performQualifiedLookups();
3740 ValidatedCorrections.push_back(TC);
3741 return ValidatedCorrections[CurrentTCIndex];
3744 return ValidatedCorrections[0];
3747 bool TypoCorrectionConsumer::resolveCorrection(
TypoCorrection &Candidate) {
3754 CorrectionValidator->IsObjCIvarLookup,
3756 switch (
Result.getResultKind()) {
3766 if (TempMemberContext) {
3769 TempMemberContext =
nullptr;
3772 if (SearchNamespaces)
3773 QualifiedResults.push_back(Candidate);
3783 for (
auto *TRD : Result)
3787 if (SearchNamespaces)
3788 QualifiedResults.push_back(Candidate);
3797 void TypoCorrectionConsumer::performQualifiedLookups() {
3798 unsigned TypoLen =
Typo->getName().size();
3799 for (
auto QR : QualifiedResults) {
3800 for (
auto NSI : Namespaces) {
3802 const Type *NSType = NSI.NameSpecifier->getAsType();
3809 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3814 TC.ClearCorrectionDecls();
3815 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3816 TC.setQualifierDistance(NSI.EditDistance);
3817 TC.setCallbackDistance(0);
3822 unsigned TmpED = TC.getEditDistance(
true);
3823 if (QR.getCorrectionAsIdentifierInfo() !=
Typo && TmpED &&
3824 TypoLen / TmpED < 3)
3828 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3834 switch (Result.getResultKind()) {
3837 if (SS && SS->isValid()) {
3838 std::string NewQualified = TC.getAsString(SemaRef.
getLangOpts());
3839 std::string OldQualified;
3840 llvm::raw_string_ostream OldOStream(OldQualified);
3842 OldOStream <<
Typo->getName();
3846 if (OldOStream.str() == NewQualified)
3850 TRD != TRDEnd; ++TRD) {
3855 TC.addCorrectionDecl(*TRD);
3857 if (TC.isResolved()) {
3858 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
3871 QualifiedResults.clear();
3874 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3876 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
3878 CurScopeSpec ? CurScopeSpec->
getScopeRep() :
nullptr) {
3879 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3887 for (DeclContextList::reverse_iterator
C = CurContextChain.rbegin(),
3888 CEnd = CurContextChain.rend();
3897 DistanceMap[1].push_back(SI);
3900 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3902 assert(Start &&
"Building a context chain from a null context");
3903 DeclContextList Chain;
3915 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3917 unsigned NumSpecifiers = 0;
3918 for (DeclContextList::reverse_iterator
C = DeclChain.rbegin(),
3919 CEnd = DeclChain.rend();
3924 }
else if (
RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*
C)) {
3926 RD->getTypeForDecl());
3930 return NumSpecifiers;
3933 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3936 unsigned NumSpecifiers = 0;
3937 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
3938 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3941 for (DeclContextList::reverse_iterator
C = CurContextChain.rbegin(),
3942 CEnd = CurContextChain.rend();
3943 C != CEnd && !NamespaceDeclChain.empty() &&
3944 NamespaceDeclChain.back() == *
C; ++
C) {
3945 NamespaceDeclChain.pop_back();
3949 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
3952 if (NamespaceDeclChain.empty()) {
3956 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
3958 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
3960 bool SameNameSpecifier =
false;
3961 if (std::find(CurNameSpecifierIdentifiers.begin(),
3962 CurNameSpecifierIdentifiers.end(),
3963 Name) != CurNameSpecifierIdentifiers.end()) {
3964 std::string NewNameSpecifier;
3965 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3969 SpecifierOStream.flush();
3970 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
3972 if (SameNameSpecifier ||
3973 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3974 Name) != CurContextIdentifiers.end()) {
3978 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
3986 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3989 NumSpecifiers = llvm::ComputeEditDistance(
3990 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3991 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
3994 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3995 DistanceMap[NumSpecifiers].push_back(SI);
4004 bool EnteringContext,
4005 bool isObjCIvarLookup,
4011 if (MemberContext) {
4013 if (isObjCIvarLookup) {
4014 if (
ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4038 if (Method->isInstanceMethod() && Method->getClassInterface() &&
4043 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4055 bool AfterNestedNameSpecifier) {
4056 if (AfterNestedNameSpecifier) {
4069 static const char *
const CTypeSpecs[] = {
4070 "char",
"const",
"double",
"enum",
"float",
"int",
"long",
"short",
4071 "signed",
"struct",
"union",
"unsigned",
"void",
"volatile",
4072 "_Complex",
"_Imaginary",
4074 "extern",
"inline",
"static",
"typedef"
4077 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4078 for (
unsigned I = 0; I != NumCTypeSpecs; ++I)
4105 static const char *
const CastableTypeSpecs[] = {
4106 "char",
"double",
"float",
"int",
"long",
"short",
4107 "signed",
"unsigned",
"void"
4109 for (
auto *kw : CastableTypeSpecs)
4128 static const char *
const CXXExprs[] = {
4129 "delete",
"new",
"operator",
"throw",
"typeid"
4131 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4132 for (
unsigned I = 0; I != NumCXXExprs; ++I)
4135 if (isa<CXXMethodDecl>(SemaRef.
CurContext) &&
4136 cast<CXXMethodDecl>(SemaRef.
CurContext)->isInstance())
4155 static const char *
const CStmts[] = {
4156 "do",
"else",
"for",
"goto",
"if",
"return",
"switch",
"while" };
4157 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4158 for (
unsigned I = 0; I != NumCStmts; ++I)
4202 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4205 std::unique_ptr<CorrectionCandidateCallback> CCC,
4242 locs->second.count(TypoName.
getLoc()))
4269 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4270 *
this, TypoName, LookupKind,
S, SS, std::move(CCC), MemberContext,
4274 bool IsUnqualifiedLookup =
false;
4276 if (MemberContext) {
4281 for (
auto *I : OPT->
quals())
4284 }
else if (SS && SS->isSet()) {
4291 IsUnqualifiedLookup =
true;
4296 bool SearchNamespaces
4298 (IsUnqualifiedLookup || (SS && SS->isSet()));
4300 if (IsUnqualifiedLookup || SearchNamespaces) {
4304 for (
const auto &I : Context.
Idents)
4311 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4313 StringRef Name = Iter->Next();
4326 if (SearchNamespaces) {
4328 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4330 LoadedExternalKnownNamespaces =
true;
4332 for (
auto *N : ExternalKnownNamespaces)
4333 KnownNamespaces[N] =
true;
4336 Consumer->addNamespaces(KnownNamespaces);
4376 std::unique_ptr<CorrectionCandidateCallback> CCC,
4379 bool EnteringContext,
4381 bool RecordFailure) {
4382 assert(CCC &&
"CorrectTypo requires a CorrectionCandidateCallback");
4386 if (ExternalSource) {
4388 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
4396 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
4399 auto Consumer = makeTypoCorrectionConsumer(
4400 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4408 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
4412 unsigned ED =
Consumer->getBestEditDistance(
true);
4413 unsigned TypoLen = Typo->
getName().size();
4414 if (ED > 0 && TypoLen / ED < 3)
4415 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
4420 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
4422 ED = BestTC.getEditDistance();
4424 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
4428 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
4432 if (!SecondBestTC ||
4433 SecondBestTC.
getEditDistance(
false) > BestTC.getEditDistance(
false)) {
4439 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
4445 }
else if (SecondBestTC && ObjCMessageReceiver) {
4449 if (BestTC.getCorrection().getAsString() !=
"super") {
4451 BestTC = SecondBestTC;
4452 else if ((*
Consumer)[
"super"].front().isKeyword())
4453 BestTC = (*
Consumer)[
"super"].front();
4457 if (BestTC.getEditDistance() == 0 ||
4458 BestTC.getCorrection().getAsString() !=
"super")
4459 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure);
4468 return FailedCorrection(Typo, TypoName.
getLoc(), RecordFailure && !SecondBestTC);
4512 std::unique_ptr<CorrectionCandidateCallback> CCC,
4516 assert(CCC &&
"CorrectTypoDelayed requires a CorrectionCandidateCallback");
4519 auto Consumer = makeTypoCorrectionConsumer(
4520 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4528 unsigned ED =
Consumer->getBestEditDistance(
true);
4530 if (ED > 0 && Typo->
getName().size() / ED < 3)
4534 return createDelayedTypo(std::move(
Consumer), std::move(TDG), std::move(TRC));
4541 CorrectionDecls.clear();
4545 if (!CorrectionName)
4550 if (CorrectionNameSpec) {
4551 std::string tmpBuffer;
4552 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4554 PrefixOStream << CorrectionName;
4555 return PrefixOStream.str();
4570 bool HasNonType =
false;
4571 bool HasStaticMethod =
false;
4572 bool HasNonStaticMethod =
false;
4573 for (
Decl *D : candidate) {
4575 D = FTD->getTemplatedDecl();
4577 if (Method->isStatic())
4578 HasStaticMethod =
true;
4580 HasNonStaticMethod =
true;
4582 if (!isa<TypeDecl>(D))
4587 !candidate.getCorrectionSpecifier())
4594 bool HasExplicitTemplateArgs,
4596 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
4597 CurContext(SemaRef.CurContext), MemberFn(ME) {
4607 for (
auto *
C : candidate) {
4611 FD = FTD->getTemplatedDecl();
4612 if (!HasExplicitTemplateArgs && !FD) {
4613 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4617 QualType ValType = cast<ValueDecl>(ND)->getType();
4621 if (FPT->getNumParams() == NumArgs)
4637 if (MemberFn || !MD->isStatic()) {
4640 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->
getMemberDecl())
4641 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
4656 bool ErrorRecovery) {
4664 if (
VarDecl *VD = dyn_cast<VarDecl>(D))
4665 return VD->getDefinition();
4666 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4667 return FD->isDefined(FD) ?
const_cast<FunctionDecl*
>(FD) :
nullptr;
4668 if (
TagDecl *TD = dyn_cast<TagDecl>(D))
4669 return TD->getDefinition();
4671 return ID->getDefinition();
4673 return PD->getDefinition();
4680 bool NeedDefinition,
bool Recover) {
4681 assert(!
isVisible(Decl) &&
"missing import for non-hidden decl?");
4692 assert(Owner &&
"definition of hidden declaration is not in a module");
4695 OwningModules.push_back(Owner);
4697 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4709 assert(!Modules.empty());
4711 if (Modules.size() > 1) {
4712 std::string ModuleList;
4714 for (
Module *M : Modules) {
4715 ModuleList +=
"\n ";
4716 if (++N == 5 && N != Modules.size()) {
4717 ModuleList +=
"[...]";
4720 ModuleList += M->getFullModuleName();
4723 Diag(UseLoc, diag::err_module_unimported_use_multiple)
4724 << (int)MIK << Decl << ModuleList;
4726 Diag(UseLoc, diag::err_module_unimported_use)
4727 << (int)MIK << Decl << Modules[0]->getFullModuleName();
4733 DiagID = diag::note_previous_declaration;
4736 DiagID = diag::note_previous_definition;
4739 DiagID = diag::note_default_argument_declared_here;
4742 Diag(DeclLoc, DiagID);
4764 bool ErrorRecovery) {
4773 assert(Decl &&
"import required but no declaration to import");
4776 false, ErrorRecovery);
4781 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo :
FixItHint());
4786 Diag(ChosenDecl->getLocation(), PrevNote)
4787 << CorrectedQuotedStr << (ErrorRecovery ?
FixItHint() : FixTypo);
4790 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4791 TypoDiagnosticGenerator TDG,
4792 TypoRecoveryCallback TRC) {
4793 assert(TCC &&
"createDelayedTypo requires a valid TypoCorrectionConsumer");
4795 auto &
State = DelayedTypos[TE];
4796 State.Consumer = std::move(TCC);
4797 State.DiagHandler = std::move(TDG);
4798 State.RecoveryHandler = std::move(TRC);
4803 auto Entry = DelayedTypos.find(TE);
4804 assert(Entry != DelayedTypos.end() &&
4805 "Failed to get the state for a TypoExpr!");
4806 return Entry->second;
4810 DelayedTypos.erase(TE);
unsigned getFlags() const
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Defines the clang::ASTContext interface.
Module * getOwningModule(Decl *Entity)
Get the module owning an entity.
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs, MemberExpr *ME=nullptr)
Name lookup found a set of overloaded functions that met the criteria.
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.
bool isTransparentContext() const
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
bool isTemplateParameter() const
void setOrigin(CXXRecordDecl *Rec)
no exception specification
IdentifierInfo * getSuperIdentifier() const
llvm::iterator_range< pack_iterator > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Simple class containing the result of Sema::CorrectTypo.
void setHidden(bool Hide)
Set whether this declaration is hidden from name lookup.
ExtInfo withCallingConv(CallingConv cc) const
QualType getType() const
Retrieves the type of the base class.
virtual unsigned RankCandidate(const TypoCorrection &candidate)
Method used by Sema::CorrectTypo to assign an "edit distance" rank to a candidate (where a lower valu...
Template argument deduction was successful.
IdentifierInfo * getIdentifier() const
const LangOptions & getLangOpts() const
void setLookupName(DeclarationName Name)
Sets the name to look up.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
const Scope * getFnParent() const
DeclClass * getAsSingle() const
Look up the name of an Objective-C protocol.
Filter makeFilter()
Create a filter for this result set.
CXXMethodDecl * LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the moving assignment operator for the given class.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
Provides information about an attempted template argument deduction, whose success or failure was des...
const Scope * getParent() const
void addConst()
addConst - add the specified type qualifier to this QualType.
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void erase()
Erase the last element returned from this iterator.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc", where we know the signature a priori.
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
Defines the C++ template declaration subclasses.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void swap(CXXBasePaths &Other)
Swap this data structure's contents with another CXXBasePaths object.
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
bool hasDefinition() const
QualType getPointeeType() const
IdentifierInfo * getAsIdentifierInfo() const
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
QualType getRecordType(const RecordDecl *Decl) const
NamespaceDecl - Represent a C++ namespace.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs. a reference).
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
Ambiguous candidates found.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
void makeKeyword()
Mark this TypoCorrection as being a keyword. Since addCorrectionDeclsand setCorrectionDecl don't allo...
IdentifierInfo * getFloat128Identifier() const
Scope * getContinueParent()
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
LiteralOperatorLookupResult
The possible outcomes of name lookup for a literal operator.
Represents a C++ constructor within a class.
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
Consumes visible declarations found when searching for all visible names within a given scope or cont...
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
An identifier, stored as an IdentifierInfo*.
CXXConstructorDecl * LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the moving constructor for the given class.
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
DeclContext::lookup_result Decls
The set of declarations found inside this base class subobject.
static bool LookupBuiltin(Sema &S, LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
CXXMethodDecl * LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the copying assignment operator for the given class.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
SmallVector< SwitchStmt *, 8 > SwitchStack
static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, bool QualifiedNameLookup, bool InBaseClass, VisibleDeclConsumer &Consumer, VisibleDeclsRecord &Visited)
DiagnosticsEngine & Diags
static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last)
Determine whether the given set of member declarations contains only static members, nested types, and enumerators.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Represents an empty template argument, e.g., one that has not been deduced.
ExtProtoInfo - Extra information about a function prototype.
AccessSpecifier getAccess() const
static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class)
Determine whether we can declare a special member function within the class at this point...
void setNotFoundInCurrentInstantiation()
Note that while no result was found in the current instantiation, there were dependent base classes t...
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
A namespace, stored as a NamespaceDecl*.
udir_range using_directives() const
SpecialMemberOverloadResult * LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Describes how types, statements, expressions, and declarations should be printed. ...
virtual TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, int LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool isSingleTagDecl() const
Asks if the result is a single tag decl.
Defines the clang::Expr interface and subclasses for C++ expressions.
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated. Returns null if this cl...
void addKeywordResult(StringRef Keyword)
bool WantExpressionKeywords
std::list< CXXBasePath >::const_iterator const_paths_iterator
void setMethod(CXXMethodDecl *MD)
static Decl * getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo)
Find the declaration that a class temploid member specialization was instantiated from...
static bool hasVisibleDefaultArgument(Sema &S, const ParmDecl *D, llvm::SmallVectorImpl< Module * > *Modules)
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class)
Perform qualified name lookup into all base classes of the given class.
DeclarationName getName() const
getName - Returns the embedded declaration name.
FunctionType::ExtInfo ExtInfo
Represents a class template specialization, which refers to a class template with a given set of temp...
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
IdentifierInfo * getCorrectionAsIdentifierInfo() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
The results of name lookup within a DeclContext. This is either a single result (with no stable stora...
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
bool isReferenceType() const
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P)
Make these results show that the name was found in base classes of different types.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
bool isCompleteDefinition() const
void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope=true)
bool isAnyPointerType() const
IdentifierSourceLocations TypoCorrectionFailures
A cache containing identifiers for which typo correction failed and their locations, so that repeated attempts to correct an identifier in a given location are ignored if typo correction already failed for it.
void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override
Invoked each time Sema::LookupVisibleDecls() finds a declaration visible from the current scope or co...
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
SourceRange getContextRange() const
unsigned getIdentifierNamespace() const
CXXRecordDecl * getDefinition() const
bool isTranslationUnit() const
unsigned size() const
Retrieve the number of template arguments in this template argument list.
void addCorrectionDecl(NamedDecl *CDecl)
Add the given NamedDecl to the list of NamedDecls that are the declarations associated with the Decla...
bool isInlineNamespace() const
static DeclarationName getFromOpaquePtr(void *P)
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared...
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Describes a module or submodule.
void setCallbackDistance(unsigned ED)
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
param_type_range param_types() const
Look up implicit 'self' parameter of an objective-c method.
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Represents the results of name lookup.
void setAmbiguousBaseSubobjects(CXXBasePaths &P)
Make these results show that the name was found in distinct base classes of the same type...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
ObjCMethodDecl * getCurMethodDecl()
static void LookupPotentialTypoResult(Sema &SemaRef, LookupResult &Res, IdentifierInfo *Name, Scope *S, CXXScopeSpec *SS, DeclContext *MemberContext, bool EnteringContext, bool isObjCIvarLookup, bool FindHidden)
Perform name lookup for a possible result for typo correction.
Succeeded, but refers to a deleted function.
unsigned getDiagID() const
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
static void DeclareImplicitMemberFunctionsWithName(Sema &S, DeclarationName Name, const DeclContext *DC)
If there are any implicit member functions with the given name that need to be declared in the given ...
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
QualType getReturnType() const
unsigned getMinRequiredArguments() const
static NamedDecl * getDefinitionToImport(NamedDecl *D)
const CXXRecordDecl * getParent() const
AmbiguityKind getAmbiguityKind() const
virtual bool includeHiddenDecls() const
Determine whether hidden declarations (from unimported modules) should be given to this consumer...
A set of unresolved declarations.
RecordDecl * getDecl() const
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate)
static unsigned getIDNS(Sema::LookupNameKind NameKind, bool CPlusPlus, bool Redeclaration)
std::function< ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback
void DiagnoseAmbiguousLookup(LookupResult &Result)
Produce a diagnostic describing the ambiguity that resulted from name lookup.
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
std::string getQuoted(const LangOptions &LO) const
using_directives_range using_directives()
void append(iterator I, iterator E)
Represents a C++ nested-name-specifier or a global scope specifier.
TypeClass getTypeClass() const
base_class_iterator bases_begin()
CXXBasePaths * getBasePaths() const
Return the base paths structure that's associated with these results, or null if none is...
Represents an Objective-C protocol declaration.
DeclContext * getLexicalDeclContext()
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation())
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
Labels, declared with 'x:' and referenced with 'goto x'.
void setLocalOwningModule(Module *M)
Module * getLocalOwningModule() const
Get the local owning module, if known. Returns nullptr if owner is not yet known or declaration is no...
const TypoCorrection & getNextCorrection()
Return the next typo correction that passes all internal filters and is deemed valid by the consumer'...
Represents an ObjC class declaration.
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access. Does not test the acceptance criteria...
QualType getCanonicalTypeInternal() const
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
CXXMethodDecl * getMethod() const
static const unsigned InvalidDistance
CXXSpecialMember
Kinds of C++ special members.
bool WantRemainingKeywords
Sema - This implements semantic analysis and AST building for C.
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass)=0
Invoked each time Sema::LookupVisibleDecls() finds a declaration visible from the current scope or co...
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
llvm::iterator_range< decls_iterator > decls() const
ArrayRef< Module * > getModulesWithMergedDefinition(NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
The return type of classify(). Represents the C++11 expression taxonomy.
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
DeclarationNameTable DeclarationNames
Provides lookups to, and iteration over, IdentiferInfo objects.
ID
Defines the set of possible language-specific address spaces.
lookups_range lookups() const
QualType getPointeeType() const
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
std::function< void(const TypoCorrection &)> TypoDiagnosticGenerator
virtual void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces)
Load the set of namespaces that are known to the external source, which will be used during typo corr...
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, DeclContext *StartDC)
Perform qualified name lookup in the namespaces nominated by using directives by the given context...
bool isDeleted() const
Whether this function has been deleted.
Defines the clang::LangOptions interface.
DeclarationName getLookupName() const
Gets the name to look up.
LookupNameKind
Describes the kind of name lookup to perform.
StringRef getName() const
Return the actual identifier string.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
bool hasFatalErrorOccurred() const
llvm::iterator_range< udir_iterator > udir_range
bool isDeclScope(Decl *D)
int SubobjectNumber
Identifies which base class subobject (of type Base->getType()) this base path element refers to...
SourceLocation getNameLoc() const
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
bool isModuleVisible(Module *M)
conversion_iterator conversion_end() const
Represents a C++ destructor within a class.
TranslationUnitDecl * getTranslationUnitDecl() const
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup. Asserts that one was found.
Defines the clang::Preprocessor interface.
SmallVectorImpl< OverloadCandidate >::iterator iterator
void setRequiresImport(bool Req)
ArgKind getKind() const
Return the kind of stored template argument.
ExtProtoInfo getExtProtoInfo() const
DeclContext * getDeclContext()
Overload resolution succeeded.
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Represents a C++ template name within the type system.
A namespace alias, stored as a NamespaceAliasDecl*.
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
const SourceRange & getRange() const
static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, void *UserData)
Base-class lookup callback that determines whether there exists a member with the given name that can...
bool isDependentType() const
llvm::SmallPtrSet< CXXRecordDecl *, 16 > AssociatedClassSet
bool isFunctionOrMethod() const
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
static NamedDecl * findAcceptableDecl(Sema &SemaRef, NamedDecl *D)
Retrieve the visible declaration corresponding to D, if any.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
QualType getCXXNameType() const
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
void addCorrection(TypoCorrection Correction)
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
DeclarationName getDeclName() const
DiagnosticsEngine & getDiagnostics() const
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
The result type of a method or function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration. Return null if the results were absent...
A type, stored as a Type*.
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo. If Normalized is true, scale the distance down by the CharDistanceWeight to return the edit distance in terms of single-character edits.
const clang::PrintingPolicy & getPrintingPolicy() const
const TypoExprState & getTypoExprState(TypoExpr *TE) const
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
virtual bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc)=0
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name)
Determine whether this is the name of an implicitly-declared special member function.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const CXXBaseSpecifier * Base
The base specifier that states the link from a derived class to a base class, which will be followed ...
static Module * getDefiningModule(Sema &S, Decl *Entity)
Find the module in which the given declaration was defined.
DeclContext * getEntity() const
NamedDecl * getInstantiatedFrom() const
Retrieve the member declaration from which this member was instantiated.
void setCorrectionDecls(ArrayRef< NamedDecl * > Decls)
Clears the list of NamedDecls and adds the given set.
bool hasTagIdentifierNamespace() const
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
void addVolatile()
addVolatile - add the specified type qualifier to this QualType.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
unsigned getNumParams() const
const Type * getTypePtr() const
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
bool isValid() const
Return true if this is a valid SourceLocation object.
OverloadedOperatorKind getCXXOverloadedOperator() const
static void getNestedNameSpecifierIdentifiers(NestedNameSpecifier *NNS, SmallVectorImpl< const IdentifierInfo * > &Identifiers)
TagDecl - Represents the declaration of a struct/union/class/enum.
bool BaseMatchesCallback(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, void *UserData)
Function type used by lookupInBases() to determine whether a specific base class subobject matches th...
ASTContext & getASTContext() const
void FoundName(StringRef Name)
bool hasVisibleMergedDefinition(NamedDecl *Def)
Represents a static or instance method of a struct/union/class.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Name lookup found an unresolvable value declaration and cannot yet complete. This only happens in C++...
llvm::DenseSet< Module * > & getLookupModules()
Get the set of additional modules that should be checked during name lookup. A module and its imports...
bool isTemplateParamScope() const
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
Look up any declaration with any name.
Represents one property declaration in an Objective-C interface.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
ObjCProtocolDecl * LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl=NotForRedeclaration)
Find the protocol with the given name, if any.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
SourceLocation getBegin() const
llvm::SmallPtrSet< DeclContext *, 16 > AssociatedNamespaceSet
lookup_result lookup(DeclarationName Name) const
No entity found met the criteria.
bool isFileContext() const
sema::FunctionScopeInfo * getCurFunction() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
A class for storing results from argument-dependent lookup.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery...
Represents an element in a path from a derived class to a base class.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Represents a template argument.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl. It will iterate at least once ...
static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, DeclContext *Ctx)
static DeclContext * getContextForScopeMatching(Decl *D)
QualType getAsType() const
Retrieve the type for a type template argument.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
void print(raw_ostream &OS, const PrintingPolicy &Policy) const
Print this nested name specifier to the given output stream.
void setAllowHidden(bool AH)
Specify whether hidden declarations are visible, e.g., for recovery reasons.
static const Type * getElementType(const Expr *BaseExpr)
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
SourceLocation getLocStart() const LLVM_READONLY
static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC)
Check whether the declarations found for a typo correction are visible, and if none of them are...
static void AddKeywordsToConsumer(Sema &SemaRef, TypoCorrectionConsumer &Consumer, Scope *S, CorrectionCandidateCallback &CCC, bool AfterNestedNameSpecifier)
Add keywords to the consumer as possible typo corrections.
The base class of all kinds of template declarations (e.g., class, function, etc.).
void setContextRange(SourceRange SR)
Sets a 'context' source range.
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
bool lookupInBases(BaseMatchesCallback *BaseMatches, void *UserData, CXXBasePaths &Paths) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
unsigned getIdentifierNamespace() const
Returns the identifier namespace mask for this lookup.
bool isExplicitSpecialization() const
bool isInvalidDecl() const
void setAmbiguousQualifiedTagHiding()
Make these results show that the name was found in different contexts and a tag decl was hidden by an...
void clearDelayedTypo(TypoExpr *TE)
Clears the state of the given TypoExpr.
void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc)
Make a merged definition of an existing hidden definition ND visible at the specified location...
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
void insert(NamedDecl *D)
Adds a new ADL candidate to this map.
void setShadowed()
Note that we found and ignored a declaration while performing lookup.
bool isDefinedOutsideFunctionOrMethod() const
static const unsigned MaxTypoDistanceResultSets
bool isSingleResult() const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
A type that was preceded by the 'template' keyword, stored as a Type*.
NamedDecl * getCurFunctionOrMethodDecl()
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions)
bool empty() const
Return true if no decls were found.
Name lookup found a single declaration that met the criteria. getFoundDecl() will return this declara...
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
bool isInObjcMethodScope() const
void * getAsOpaquePtr() const
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
static bool isFunctionOrMethod(const Decl *D)
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, bool NeedDefinition, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
DeclContext * getRedeclContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
std::string getAsString(const LangOptions &LO) const
The template argument is a type.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Represents a base class of a C++ class.
This is a scope that can contain a declaration. Some scopes just contain loop constructs but don't co...
TypeDecl * getFloat128StubType() const
Retrieve the declaration for a 128-bit float stub type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
A template argument list.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
SourceRange getCorrectionRange() const
const Type * getClass() const
static bool isNamespaceOrTranslationUnitScope(Scope *S)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Represents a C++ struct/union/class.
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
type_const_range types() const
Provides information a specialization of a member of a class template, which may be a member function...
base_class_iterator bases_end()
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
void setCorrectionRange(CXXScopeSpec *SS, const DeclarationNameInfo &TypoName)
void print(raw_ostream &)
AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found)
Checks access to a member.
Builtin::Context & BuiltinInfo
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Declaration of a class template.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
TypoExpr * CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
LookupResultKind getResultKind() const
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
static bool LookupAnyMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, void *Name)
Callback that looks for any member of a class with the given name.
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
void addNamespaces(const llvm::MapVector< NamespaceDecl *, bool > &KnownNamespaces)
Set-up method to add to the consumer the set of namespaces to use in performing corrections to nested...
virtual ~VisibleDeclConsumer()
Destroys the visible declaration consumer.
static bool FindTagMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, void *Name)
Base-class lookup callback that determines whether there exists a tag with the given name...
conversion_iterator conversion_begin() const
static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T)
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
DeclContext * getPrimaryContext()
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
No viable function found.
void suppressDiagnostics()
static std::pair< DeclContext *, bool > findOuterContext(Scope *S)
An l-value expression is a reference to an object with independent storage.
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
Represents C++ using-directive.
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, DeclContext *NS, UnqualUsingDirectiveSet &UDirs)
The global specifier '::'. There is no stored value.
bool requiresImport() const
Returns whether this typo correction is correcting to a declaration that was declared in a module tha...
static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC)
void WillReplaceSpecifier(bool ForceReplacement)
bool WantFunctionLikeCasts
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined...
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
ExceptionSpecInfo ExceptionSpec
Defines enum values for all the target-independent builtin functions.
Declaration of a template function.
void clear()
Clears out any current state.
void setFindLocalExtern(bool FindLocalExtern)
std::list< CXXBasePath >::iterator paths_iterator
IdentifierInfoLookup * getExternalIdentifierLookup() const
Retrieve the external identifier lookup object, if any.
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, void *Name)
Base-class lookup callback that determines whether there exists a member with the given name...
static bool isCandidateViable(CorrectionCandidateCallback &CCC, TypoCorrection &Candidate)
Expr * IgnoreParens() LLVM_READONLY
bool isHidden() const
Determine whether this declaration is hidden from name lookup.
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.