blob: a41eef39edfc7d2ffcc4b3c6e072dff24dda092d [file] [log] [blame]
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
Douglas Gregor34074322009-01-14 22:20:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Hans Wennborgdcfba332015-10-06 23:40:43 +000014
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Richard Smith42413142015-05-15 20:05:43 +000026#include "clang/Lex/HeaderSearch.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000027#include "clang/Lex/ModuleLoader.h"
Richard Smith4caa4492015-05-15 02:34:32 +000028#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Sema/DeclSpec.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000030#include "clang/Sema/Lookup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Overload.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000040#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000041#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000042#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000043#include <algorithm>
44#include <iterator>
Douglas Gregor2d435302009-12-30 17:04:44 +000045#include <list>
Nick Lewycky13668f22012-04-03 20:26:45 +000046#include <set>
47#include <utility>
48#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000049
50using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000051using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053namespace {
54 class UnqualUsingEntry {
55 const DeclContext *Nominated;
56 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 public:
59 UnqualUsingEntry(const DeclContext *Nominated,
60 const DeclContext *CommonAncestor)
61 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 const DeclContext *getCommonAncestor() const {
65 return CommonAncestor;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 const DeclContext *getNominatedNamespace() const {
69 return Nominated;
70 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 // Sort by the pointer value of the common ancestor.
73 struct Comparator {
74 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
75 return L.getCommonAncestor() < R.getCommonAncestor();
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
79 return E.getCommonAncestor() < DC;
80 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
83 return DC < E.getCommonAncestor();
84 }
85 };
86 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 /// A collection of using directives, as used by C++ unqualified
89 /// lookup.
90 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000091 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 ListTy list;
94 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000095
John McCallf6c8a4e2009-11-10 07:01:13 +000096 public:
97 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000100 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 // During unqualified name lookup, the names appear as if they
102 // were declared in the nearest enclosing namespace which contains
103 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000104 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000106
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000108 // C++ [namespace.udir]p1:
109 // A using-directive shall not appear in class scope, but may
110 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000111 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000112 if (Ctx && Ctx->isFileContext()) {
113 visit(Ctx, Ctx);
114 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000115 for (auto *I : S->using_directives())
116 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000117 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000118 }
119 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000120
121 // Visits a context and collect all of its using directives
122 // recursively. Treats all using directives as if they were
123 // declared in the context.
124 //
125 // A given context is only every visited once, so it is important
126 // that contexts be visited from the inside out in order to get
127 // the effective DCs right.
128 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000129 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000130 return;
131
132 addUsingDirectives(DC, EffectiveDC);
133 }
134
135 // Visits a using directive and collects all of its using
136 // directives recursively. Treats all using directives as if they
137 // were declared in the effective DC.
138 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
139 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000140 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000141 return;
142
143 addUsingDirective(UD, EffectiveDC);
144 addUsingDirectives(NS, EffectiveDC);
145 }
146
147 // Adds all the using directives in a context (and those nominated
148 // by its using directives, transitively) as if they appeared in
149 // the given effective context.
150 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000151 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000152 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000153 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000155 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 addUsingDirective(UD, EffectiveDC);
157 queue.push_back(NS);
158 }
159 }
160
161 if (queue.empty())
162 return;
163
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000164 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000165 }
166 }
167
168 // Add a using directive as if it had been declared in the given
169 // context. This helps implement C++ [namespace.udir]p3:
170 // The using-directive is transitive: if a scope contains a
171 // using-directive that nominates a second namespace that itself
172 // contains using-directives, the effect is as if the
173 // using-directives from the second namespace also appeared in
174 // the first.
175 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
176 // Find the common ancestor between the effective context and
177 // the nominated namespace.
178 DeclContext *Common = UD->getNominatedNamespace();
179 while (!Common->Encloses(EffectiveDC))
180 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000181 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000182
John McCallf6c8a4e2009-11-10 07:01:13 +0000183 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
184 }
185
186 void done() {
187 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
188 }
189
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000191
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 const_iterator begin() const { return list.begin(); }
193 const_iterator end() const { return list.end(); }
194
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000195 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000197 return llvm::make_range(std::equal_range(begin(), end(),
198 DC->getPrimaryContext(),
199 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000200 }
201 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000202} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000203
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204// Retrieve the set of identifier namespaces that correspond to a
205// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000206static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
207 bool CPlusPlus,
208 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209 unsigned IDNS = 0;
210 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000211 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000213 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000214 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000216 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000218 if (Redeclaration)
219 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000220 }
Richard Smith541b38b2013-09-20 01:15:31 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000223 break;
224
John McCallb9467b62010-04-24 01:30:58 +0000225 case Sema::LookupOperatorName:
226 // Operator lookup is its own crazy thing; it is not the same
227 // as (e.g.) looking up an operator name for redeclaration.
228 assert(!Redeclaration && "cannot do redeclaration operator lookup");
229 IDNS = Decl::IDNS_NonMemberOperator;
230 break;
231
Douglas Gregor889ceb72009-02-03 19:21:40 +0000232 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000233 if (CPlusPlus) {
234 IDNS = Decl::IDNS_Type;
235
236 // When looking for a redeclaration of a tag name, we add:
237 // 1) TagFriend to find undeclared friend decls
238 // 2) Namespace because they can't "overload" with tag decls.
239 // 3) Tag because it includes class templates, which can't
240 // "overload" with tag decls.
241 if (Redeclaration)
242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
243 } else {
244 IDNS = Decl::IDNS_Tag;
245 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000246 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000247
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000248 case Sema::LookupLabel:
249 IDNS = Decl::IDNS_Label;
250 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000251
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 case Sema::LookupMemberName:
253 IDNS = Decl::IDNS_Member;
254 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000255 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000256 break;
257
258 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000259 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
260 break;
261
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000265
John McCall84d87672009-12-10 09:41:52 +0000266 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000267 assert(Redeclaration && "should only be used for redecl lookup");
268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
269 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
270 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000271 break;
272
Douglas Gregor79947a22009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000277 case Sema::LookupOMPReductionName:
278 IDNS = Decl::IDNS_OMPReduction;
279 break;
280
Douglas Gregor39982192010-08-15 06:18:01 +0000281 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000283 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
284 | Decl::IDNS_Type;
285 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000286 }
287 return IDNS;
288}
289
John McCallea305ed2009-12-18 10:40:03 +0000290void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000291 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000292 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000293
Richard Smithbdd14642014-02-04 01:14:30 +0000294 // If we're looking for one of the allocation or deallocation
295 // operators, make sure that the implicitly-declared new and delete
296 // operators can be found.
297 switch (NameInfo.getName().getCXXOverloadedOperator()) {
298 case OO_New:
299 case OO_Delete:
300 case OO_Array_New:
301 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000302 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000303 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000304
Richard Smithbdd14642014-02-04 01:14:30 +0000305 default:
306 break;
307 }
Douglas Gregor15197662013-04-03 23:06:26 +0000308
Richard Smithbdd14642014-02-04 01:14:30 +0000309 // Compiler builtins are always visible, regardless of where they end
310 // up being declared.
311 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
312 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000313 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000314 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000315 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000316 }
John McCallea305ed2009-12-18 10:40:03 +0000317}
318
Alp Tokerc1086762013-12-07 13:51:35 +0000319bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000320 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000321 assert(ResultKind != NotFound || Decls.size() == 0);
322 assert(ResultKind != Found || Decls.size() == 1);
323 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
324 (Decls.size() == 1 &&
325 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
326 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
327 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000328 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
329 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000330 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
331 (Ambiguity == AmbiguousBaseSubobjectTypes ||
332 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000333 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000334}
John McCall19c1bfd2010-08-25 05:32:35 +0000335
John McCall9f3059a2009-10-09 21:13:30 +0000336// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000337void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000338 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000339}
340
Richard Smith3876cc82013-10-30 01:02:04 +0000341/// Get a representative context for a declaration such that two declarations
342/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000343static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000344 // For function-local declarations, use that function as the context. This
345 // doesn't account for scopes within the function; the caller must deal with
346 // those.
347 DeclContext *DC = D->getLexicalDeclContext();
348 if (DC->isFunctionOrMethod())
349 return DC;
350
351 // Otherwise, look at the semantic context of the declaration. The
352 // declaration must have been found there.
353 return D->getDeclContext()->getRedeclContext();
354}
355
Richard Smith826711d2015-07-29 23:38:25 +0000356/// \brief Determine whether \p D is a better lookup result than \p Existing,
357/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000358static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000359 NamedDecl *D, NamedDecl *Existing) {
360 // When looking up redeclarations of a using declaration, prefer a using
361 // shadow declaration over any other declaration of the same entity.
362 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
363 !isa<UsingShadowDecl>(Existing))
364 return true;
365
366 auto *DUnderlying = D->getUnderlyingDecl();
367 auto *EUnderlying = Existing->getUnderlyingDecl();
368
Richard Smith990668b2015-11-12 22:04:34 +0000369 // If they have different underlying declarations, prefer a typedef over the
370 // original type (this happens when two type declarations denote the same
371 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
372 // might carry additional semantic information, such as an alignment override.
373 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
374 // declaration over a typedef.
Richard Smith826711d2015-07-29 23:38:25 +0000375 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
376 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
Richard Smith990668b2015-11-12 22:04:34 +0000377 bool HaveTag = isa<TagDecl>(EUnderlying);
378 bool WantTag = Kind == Sema::LookupTagName;
379 return HaveTag != WantTag;
Richard Smith826711d2015-07-29 23:38:25 +0000380 }
381
Richard Smithcd31b852015-08-22 21:37:34 +0000382 // Pick the function with more default arguments.
383 // FIXME: In the presence of ambiguous default arguments, we should keep both,
384 // so we can diagnose the ambiguity if the default argument is needed.
385 // See C++ [over.match.best]p3.
386 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
387 auto *EFD = cast<FunctionDecl>(EUnderlying);
388 unsigned DMin = DFD->getMinRequiredArguments();
389 unsigned EMin = EFD->getMinRequiredArguments();
390 // If D has more default arguments, it is preferred.
391 if (DMin != EMin)
392 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000393 // FIXME: When we track visibility for default function arguments, check
394 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000395 }
396
397 // Pick the template with more default template arguments.
398 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
399 auto *ETD = cast<TemplateDecl>(EUnderlying);
400 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
401 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000402 // If D has more default arguments, it is preferred. Note that default
403 // arguments (and their visibility) is monotonically increasing across the
404 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000405 if (DMin != EMin)
406 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000407 // If D has more *visible* default arguments, it is preferred. Note, an
408 // earlier default argument being visible does not imply that a later
409 // default argument is visible, so we can't just check the first one.
410 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
411 I != N; ++I) {
412 if (!S.hasVisibleDefaultArgument(
413 ETD->getTemplateParameters()->getParam(I)) &&
414 S.hasVisibleDefaultArgument(
415 DTD->getTemplateParameters()->getParam(I)))
416 return true;
417 }
Richard Smithcd31b852015-08-22 21:37:34 +0000418 }
419
Vassil Vassilev4d75e8d2016-02-28 19:08:24 +0000420 // VarDecl can have incomplete array types, prefer the one with more complete
421 // array type.
422 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
423 VarDecl *EVD = cast<VarDecl>(EUnderlying);
424 if (EVD->getType()->isIncompleteType() &&
425 !DVD->getType()->isIncompleteType()) {
426 // Prefer the decl with a more complete type if visible.
427 return S.isVisible(DVD);
428 }
429 return false; // Avoid picking up a newer decl, just because it was newer.
430 }
431
Richard Smithcd31b852015-08-22 21:37:34 +0000432 // For most kinds of declaration, it doesn't really matter which one we pick.
433 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
434 // If the existing declaration is hidden, prefer the new one. Otherwise,
435 // keep what we've got.
436 return !S.isVisible(Existing);
437 }
438
439 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000440 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
441 Prev = Prev->getPreviousDecl())
442 if (Prev == EUnderlying)
443 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000444 return false;
445}
446
Richard Smith990668b2015-11-12 22:04:34 +0000447/// Determine whether \p D can hide a tag declaration.
448static bool canHideTag(NamedDecl *D) {
449 // C++ [basic.scope.declarative]p4:
450 // Given a set of declarations in a single declarative region [...]
451 // exactly one declaration shall declare a class name or enumeration name
452 // that is not a typedef name and the other declarations shall all refer to
453 // the same variable or enumerator, or all refer to functions and function
454 // templates; in this case the class name or enumeration name is hidden.
455 // C++ [basic.scope.hiding]p2:
456 // A class name or enumeration name can be hidden by the name of a
457 // variable, data member, function, or enumerator declared in the same
458 // scope.
459 D = D->getUnderlyingDecl();
460 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
461 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D);
462}
463
John McCall283b9012009-11-22 00:44:51 +0000464/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000465void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000466 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000467
John McCall9f3059a2009-10-09 21:13:30 +0000468 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000469 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000470 assert(ResultKind == NotFound ||
471 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000472 return;
473 }
474
John McCall283b9012009-11-22 00:44:51 +0000475 // If there's a single decl, we need to examine it to decide what
476 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000477 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000478 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
479 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000480 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000481 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000482 ResultKind = FoundUnresolvedValue;
483 return;
484 }
John McCall9f3059a2009-10-09 21:13:30 +0000485
John McCall6538c932009-10-10 05:48:19 +0000486 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000487 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000488
Richard Smitha534a312015-07-21 23:54:07 +0000489 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000490 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491
John McCall9f3059a2009-10-09 21:13:30 +0000492 bool Ambiguous = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000493 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000494 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000495 NamedDecl *HasNonFunction = nullptr;
496
497 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000498
499 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
John McCall9f3059a2009-10-09 21:13:30 +0000501 unsigned I = 0;
502 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000503 NamedDecl *D = Decls[I]->getUnderlyingDecl();
504 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000505
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000506 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000507 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000508 Decls[I] = Decls[--N];
509 continue;
510 }
511
Richard Smith826711d2015-07-29 23:38:25 +0000512 llvm::Optional<unsigned> ExistingI;
513
Douglas Gregor13e65872010-08-11 14:45:53 +0000514 // Redeclarations of types via typedef can occur both within a scope
515 // and, through using declarations and directives, across scopes. There is
516 // no ambiguity if they all refer to the same type, so unique based on the
517 // canonical type.
518 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith990668b2015-11-12 22:04:34 +0000519 QualType T = getSema().Context.getTypeDeclType(TD);
520 auto UniqueResult = UniqueTypes.insert(
521 std::make_pair(getSema().Context.getCanonicalType(T), I));
522 if (!UniqueResult.second) {
523 // The type is not unique.
524 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000525 }
526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Richard Smith826711d2015-07-29 23:38:25 +0000528 // For non-type declarations, check for a prior lookup result naming this
529 // canonical declaration.
530 if (!ExistingI) {
531 auto UniqueResult = Unique.insert(std::make_pair(D, I));
532 if (!UniqueResult.second) {
533 // We've seen this entity before.
534 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000535 }
Richard Smith826711d2015-07-29 23:38:25 +0000536 }
537
538 if (ExistingI) {
539 // This is not a unique lookup result. Pick one of the results and
540 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000541 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000542 Decls[*ExistingI]))
543 Decls[*ExistingI] = Decls[I];
544 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000545 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546 }
547
Douglas Gregor13e65872010-08-11 14:45:53 +0000548 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000549
Douglas Gregor13e65872010-08-11 14:45:53 +0000550 if (isa<UnresolvedUsingValueDecl>(D)) {
551 HasUnresolved = true;
552 } else if (isa<TagDecl>(D)) {
553 if (HasTag)
554 Ambiguous = true;
555 UniqueTagIndex = I;
556 HasTag = true;
557 } else if (isa<FunctionTemplateDecl>(D)) {
558 HasFunction = true;
559 HasFunctionTemplate = true;
560 } else if (isa<FunctionDecl>(D)) {
561 HasFunction = true;
562 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000563 if (HasNonFunction) {
564 // If we're about to create an ambiguity between two declarations that
565 // are equivalent, but one is an internal linkage declaration from one
566 // module and the other is an internal linkage declaration from another
567 // module, just skip it.
568 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
569 D)) {
570 EquivalentNonFunctions.push_back(D);
571 Decls[I] = Decls[--N];
572 continue;
573 }
574
Douglas Gregor13e65872010-08-11 14:45:53 +0000575 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000576 }
577 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000578 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000579 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000580 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000581
John McCall9f3059a2009-10-09 21:13:30 +0000582 // C++ [basic.scope.hiding]p2:
583 // A class name or enumeration name can be hidden by the name of
584 // an object, function, or enumerator declared in the same
585 // scope. If a class or enumeration name and an object, function,
586 // or enumerator are declared in the same scope (in any order)
587 // with the same name, the class or enumeration name is hidden
588 // wherever the object, function, or enumerator name is visible.
589 // But it's still an error if there are distinct tag types found,
590 // even if they're not visible. (ref?)
Richard Smith990668b2015-11-12 22:04:34 +0000591 if (N > 1 && HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000592 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith990668b2015-11-12 22:04:34 +0000593 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
594 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
595 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
596 getContextForScopeMatching(OtherDecl)) &&
597 canHideTag(OtherDecl))
Douglas Gregore63d0872010-10-23 16:06:17 +0000598 Decls[UniqueTagIndex] = Decls[--N];
599 else
600 Ambiguous = true;
601 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000602
Richard Smith2dbe4042015-11-04 19:26:32 +0000603 // FIXME: This diagnostic should really be delayed until we're done with
604 // the lookup result, in case the ambiguity is resolved by the caller.
605 if (!EquivalentNonFunctions.empty() && !Ambiguous)
606 getSema().diagnoseEquivalentInternalLinkageDeclarations(
607 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
608
John McCall9f3059a2009-10-09 21:13:30 +0000609 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000610
John McCall80053822009-12-03 00:58:24 +0000611 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000612 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000613
John McCall9f3059a2009-10-09 21:13:30 +0000614 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000615 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000616 else if (HasUnresolved)
617 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000618 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000619 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000620 else
John McCall27b18f82009-11-17 02:14:36 +0000621 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000622}
623
John McCall5cebab12009-11-18 07:57:50 +0000624void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000625 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000626 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000627 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
628 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000629 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000630}
631
John McCall5cebab12009-11-18 07:57:50 +0000632void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000633 Paths = new CXXBasePaths;
634 Paths->swap(P);
635 addDeclsFromBasePaths(*Paths);
636 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000637 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000638}
639
John McCall5cebab12009-11-18 07:57:50 +0000640void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000641 Paths = new CXXBasePaths;
642 Paths->swap(P);
643 addDeclsFromBasePaths(*Paths);
644 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000645 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000646}
647
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000648void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000649 Out << Decls.size() << " result(s)";
650 if (isAmbiguous()) Out << ", ambiguous";
651 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652
John McCall9f3059a2009-10-09 21:13:30 +0000653 for (iterator I = begin(), E = end(); I != E; ++I) {
654 Out << "\n";
655 (*I)->print(Out, 2);
656 }
657}
658
Richard Smithba3a4f92016-01-12 21:59:26 +0000659LLVM_DUMP_METHOD void LookupResult::dump() {
660 llvm::errs() << "lookup results for " << getLookupName().getAsString()
661 << ":\n";
662 for (NamedDecl *D : *this)
663 D->dump();
664}
665
Douglas Gregord3a59182010-02-12 05:48:04 +0000666/// \brief Lookup a builtin function, when name lookup would otherwise
667/// fail.
668static bool LookupBuiltin(Sema &S, LookupResult &R) {
669 Sema::LookupNameKind NameKind = R.getLookupKind();
670
671 // If we didn't find a use of this identifier, and if the identifier
672 // corresponds to a compiler builtin, create the decl object for the builtin
673 // now, injecting it into translation unit scope, and return it.
674 if (NameKind == Sema::LookupOrdinaryName ||
675 NameKind == Sema::LookupRedeclarationWithLinkage) {
676 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
677 if (II) {
Eric Fiselier6ad68552016-07-01 01:24:09 +0000678 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
679 if (II == S.getASTContext().getMakeIntegerSeqName()) {
680 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
681 return true;
682 } else if (II == S.getASTContext().getTypePackElementName()) {
683 R.addDecl(S.getASTContext().getTypePackElementDecl());
684 return true;
685 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000686 }
Nico Webere1687c52013-06-20 21:44:55 +0000687
Douglas Gregord3a59182010-02-12 05:48:04 +0000688 // If this is a builtin on this (or all) targets, create the decl.
689 if (unsigned BuiltinID = II->getBuiltinID()) {
Anastasia Stulovab607e0f2016-02-02 11:29:43 +0000690 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
691 // library functions like 'malloc'. Instead, we'll just error.
692 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000693 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
694 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
696 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
697 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000698 R.isForRedeclaration(),
699 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000700 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000701 return true;
702 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000703 }
704 }
705 }
706
707 return false;
708}
709
Douglas Gregor7454c562010-07-02 20:37:36 +0000710/// \brief Determine whether we can declare a special member function within
711/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000712static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000713 // We need to have a definition for the class.
714 if (!Class->getDefinition() || Class->isDependentContext())
715 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Douglas Gregor7454c562010-07-02 20:37:36 +0000717 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000718 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000719}
720
721void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000722 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000723 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000724
725 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000726 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000727 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Douglas Gregora6d69502010-07-02 23:41:54 +0000729 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000730 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000731 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000732
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000733 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000734 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000735 DeclareImplicitCopyAssignment(Class);
736
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000737 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000738 // If the move constructor has not yet been declared, do so now.
739 if (Class->needsImplicitMoveConstructor())
Richard Smitha87b7662016-05-13 18:48:05 +0000740 DeclareImplicitMoveConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000741
742 // If the move assignment operator has not yet been declared, do so now.
743 if (Class->needsImplicitMoveAssignment())
Richard Smitha87b7662016-05-13 18:48:05 +0000744 DeclareImplicitMoveAssignment(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000745 }
746
Douglas Gregor7454c562010-07-02 20:37:36 +0000747 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000748 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000750}
751
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000753/// special member function.
754static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
755 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000756 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000757 case DeclarationName::CXXDestructorName:
758 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000760 case DeclarationName::CXXOperatorName:
761 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000763 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000765 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000766
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000767 return false;
768}
769
770/// \brief If there are any implicit member functions with the given name
771/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000772static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000773 DeclarationName Name,
774 const DeclContext *DC) {
775 if (!DC)
776 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000778 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000779 case DeclarationName::CXXConstructorName:
780 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000781 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000782 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000783 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000784 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000785 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000786 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000787 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000788 Record->needsImplicitMoveConstructor())
789 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000790 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000791 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000792
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000793 case DeclarationName::CXXDestructorName:
794 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000795 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000796 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000797 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000798 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000800 case DeclarationName::CXXOperatorName:
801 if (Name.getCXXOverloadedOperator() != OO_Equal)
802 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803
Sebastian Redl22653ba2011-08-30 19:58:05 +0000804 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000805 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000806 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000807 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000808 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000809 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000810 Record->needsImplicitMoveAssignment())
811 S.DeclareImplicitMoveAssignment(Class);
812 }
813 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000814 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000816 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000818 }
819}
Douglas Gregor7454c562010-07-02 20:37:36 +0000820
John McCall9f3059a2009-10-09 21:13:30 +0000821// Adds all qualifying matches for a name within a decl context to the
822// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000823static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000824 bool Found = false;
825
Douglas Gregor7454c562010-07-02 20:37:36 +0000826 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000827 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000828 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829
Douglas Gregor7454c562010-07-02 20:37:36 +0000830 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000831 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
832 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000833 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000834 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000835 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000836 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000837 Found = true;
838 }
839 }
John McCall9f3059a2009-10-09 21:13:30 +0000840
Douglas Gregord3a59182010-02-12 05:48:04 +0000841 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
842 return true;
843
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000844 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000845 != DeclarationName::CXXConversionFunctionName ||
846 R.getLookupName().getCXXNameType()->isDependentType() ||
847 !isa<CXXRecordDecl>(DC))
848 return Found;
849
850 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000852 // name lookup. Instead, any conversion function templates visible in the
853 // context of the use are considered. [...]
854 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000855 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000856 return Found;
857
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000858 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
859 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000860 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
861 if (!ConvTemplate)
862 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863
Chandler Carruth3a693b72010-01-31 11:44:02 +0000864 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000865 // add the conversion function template. When we deduce template
866 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000867 // type of the new declaration with the type of the function template.
868 if (R.isForRedeclaration()) {
869 R.addDecl(ConvTemplate);
870 Found = true;
871 continue;
872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000873
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000874 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875 // [...] For each such operator, if argument deduction succeeds
876 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000877 // name lookup.
878 //
879 // When referencing a conversion function for any purpose other than
880 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000882 // specialization into the result set. We do this to avoid forcing all
883 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000884 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000885 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886
887 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000888 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
889 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000890
Chandler Carruth3a693b72010-01-31 11:44:02 +0000891 // Compute the type of the function that we would expect the conversion
892 // function to have, if it were to match the name given.
893 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000894 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000895 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000896 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000897 QualType ExpectedType
898 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000899 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Chandler Carruth3a693b72010-01-31 11:44:02 +0000901 // Perform template argument deduction against the type that we would
902 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000903 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000904 Specialization, Info)
905 == Sema::TDK_Success) {
906 R.addDecl(Specialization);
907 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000908 }
909 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000910
John McCall9f3059a2009-10-09 21:13:30 +0000911 return Found;
912}
913
John McCallf6c8a4e2009-11-10 07:01:13 +0000914// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000915static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000917 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000918
919 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
920
John McCallf6c8a4e2009-11-10 07:01:13 +0000921 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000922 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000923
John McCallf6c8a4e2009-11-10 07:01:13 +0000924 // Perform direct name lookup into the namespaces nominated by the
925 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000926 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
927 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000928 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000929
930 R.resolveKind();
931
932 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000933}
934
935static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000936 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000937 return Ctx->isFileContext();
938 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000939}
Douglas Gregored8f2882009-01-30 01:04:22 +0000940
Douglas Gregor66230062010-03-15 14:33:29 +0000941// Find the next outer declaration context from this scope. This
942// routine actually returns the semantic outer context, which may
943// differ from the lexical context (encoded directly in the Scope
944// stack) when we are parsing a member of a class template. In this
945// case, the second element of the pair will be true, to indicate that
946// name lookup should continue searching in this semantic context when
947// it leaves the current template parameter scope.
948static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000949 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000950 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000952 OuterS = OuterS->getParent()) {
953 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000954 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000955 break;
956 }
957 }
958
959 // C++ [temp.local]p8:
960 // In the definition of a member of a class template that appears
961 // outside of the namespace containing the class template
962 // definition, the name of a template-parameter hides the name of
963 // a member of this namespace.
964 //
965 // Example:
966 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967 // namespace N {
968 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000969 //
970 // template<class T> class B {
971 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000973 // }
974 //
975 // template<class C> void N::B<C>::f(C) {
976 // C b; // C is the template parameter, not N::C
977 // }
978 //
979 // In this example, the lexical context we return is the
980 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000981 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000982 !S->getParent()->isTemplateParamScope())
983 return std::make_pair(Lexical, false);
984
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000986 // For the example, this is the scope for the template parameters of
987 // template<class C>.
988 Scope *OutermostTemplateScope = S->getParent();
989 while (OutermostTemplateScope->getParent() &&
990 OutermostTemplateScope->getParent()->isTemplateParamScope())
991 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
Douglas Gregor66230062010-03-15 14:33:29 +0000993 // Find the namespace context in which the original scope occurs. In
994 // the example, this is namespace N.
995 DeclContext *Semantic = DC;
996 while (!Semantic->isFileContext())
997 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000998
Douglas Gregor66230062010-03-15 14:33:29 +0000999 // Find the declaration context just outside of the template
1000 // parameter scope. This is the context in which the template is
1001 // being lexically declaration (a namespace context). In the
1002 // example, this is the global scope.
1003 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1004 Lexical->Encloses(Semantic))
1005 return std::make_pair(Semantic, true);
1006
1007 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +00001008}
1009
Richard Smith541b38b2013-09-20 01:15:31 +00001010namespace {
1011/// An RAII object to specify that we want to find block scope extern
1012/// declarations.
1013struct FindLocalExternScope {
1014 FindLocalExternScope(LookupResult &R)
1015 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1016 Decl::IDNS_LocalExtern) {
1017 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
1018 }
1019 void restore() {
1020 R.setFindLocalExtern(OldFindLocalExtern);
1021 }
1022 ~FindLocalExternScope() {
1023 restore();
1024 }
1025 LookupResult &R;
1026 bool OldFindLocalExtern;
1027};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001028} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +00001029
John McCall27b18f82009-11-17 02:14:36 +00001030bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001031 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001032
1033 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001034 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001035
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001036 // If this is the name of an implicitly-declared special member function,
1037 // go through the scope stack to implicitly declare
1038 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1039 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001040 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001041 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
1042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001043
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001044 // Implicitly declare member functions with the name we're looking for, if in
1045 // fact we are in a scope where it matters.
1046
Douglas Gregor889ceb72009-02-03 19:21:40 +00001047 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001048 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001049 I = IdResolver.begin(Name),
1050 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001051
Douglas Gregor889ceb72009-02-03 19:21:40 +00001052 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001053 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001054 // ...During unqualified name lookup (3.4.1), the names appear as if
1055 // they were declared in the nearest enclosing namespace which contains
1056 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001057 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001058 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001059 //
1060 // For example:
1061 // namespace A { int i; }
1062 // void foo() {
1063 // int i;
1064 // {
1065 // using namespace A;
1066 // ++i; // finds local 'i', A::i appears at global scope
1067 // }
1068 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001069 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001070 UnqualUsingDirectiveSet UDirs;
1071 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001072 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001073 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001074
1075 // When performing a scope lookup, we want to find local extern decls.
1076 FindLocalExternScope FindLocals(R);
1077
Douglas Gregor700792c2009-02-05 19:25:20 +00001078 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001079 DeclContext *Ctx = S->getEntity();
Olivier Goffart12b221982016-06-16 21:39:46 +00001080 bool SearchNamespaceScope = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001081 // Check whether the IdResolver has anything in this scope.
John McCall48871652010-08-21 09:40:31 +00001082 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001083 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Olivier Goffart12b221982016-06-16 21:39:46 +00001084 if (NameKind == LookupRedeclarationWithLinkage &&
1085 !(*I)->isTemplateParameter()) {
1086 // If it's a template parameter, we still find it, so we can diagnose
1087 // the invalid redeclaration.
1088
Richard Smith1c34fb72013-08-13 18:18:50 +00001089 // Determine whether this (or a previous) declaration is
1090 // out-of-scope.
1091 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1092 LeftStartingScope = true;
1093
1094 // If we found something outside of our starting scope that
Olivier Goffart12b221982016-06-16 21:39:46 +00001095 // does not have linkage, skip it.
1096 if (LeftStartingScope && !((*I)->hasLinkage())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001097 R.setShadowed();
1098 continue;
1099 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001100 } else {
1101 // We found something in this scope, we should not look at the
1102 // namespace scope
1103 SearchNamespaceScope = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001104 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001105 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001106 }
1107 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001108 if (!SearchNamespaceScope) {
John McCall9f3059a2009-10-09 21:13:30 +00001109 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001110 if (S->isClassScope())
1111 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1112 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001113 return true;
1114 }
1115
Richard Smith1c34fb72013-08-13 18:18:50 +00001116 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001117 // C++11 [class.friend]p11:
1118 // If a friend declaration appears in a local class and the name
1119 // specified is an unqualified name, a prior declaration is
1120 // looked up without considering scopes that are outside the
1121 // innermost enclosing non-class scope.
1122 return false;
1123 }
1124
Douglas Gregor66230062010-03-15 14:33:29 +00001125 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1126 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1127 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001128 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001129 // lexical and semantic declaration contexts returned by
1130 // findOuterContext(). This implements the name lookup behavior
1131 // of C++ [temp.local]p8.
1132 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001133 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001134 }
1135
1136 if (Ctx) {
1137 DeclContext *OuterCtx;
1138 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001139 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001140 if (SearchAfterTemplateScope)
1141 OutsideOfTemplateParamDC = OuterCtx;
1142
Douglas Gregorea166062010-03-15 15:26:48 +00001143 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001144 // We do not directly look into transparent contexts, since
1145 // those entities will be found in the nearest enclosing
1146 // non-transparent context.
1147 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001148 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001149
1150 // We do not look directly into function or method contexts,
1151 // since all of the local variables and parameters of the
1152 // function/method are present within the Scope.
1153 if (Ctx->isFunctionOrMethod()) {
1154 // If we have an Objective-C instance method, look for ivars
1155 // in the corresponding interface.
1156 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1157 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1158 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1159 ObjCInterfaceDecl *ClassDeclared;
1160 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001161 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001162 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001163 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1164 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001165 R.resolveKind();
1166 return true;
1167 }
1168 }
1169 }
1170 }
1171
1172 continue;
1173 }
1174
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001175 // If this is a file context, we need to perform unqualified name
1176 // lookup considering using directives.
1177 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001178 // If we haven't handled using directives yet, do so now.
1179 if (!VisitedUsingDirectives) {
1180 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001181 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1182 if (UCtx->isTransparentContext())
1183 continue;
1184
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001185 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001186 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001187
1188 // Find the innermost file scope, so we can add using directives
1189 // from local scopes.
1190 Scope *InnermostFileScope = S;
1191 while (InnermostFileScope &&
1192 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1193 InnermostFileScope = InnermostFileScope->getParent();
1194 UDirs.visitScopeChain(Initial, InnermostFileScope);
1195
1196 UDirs.done();
1197
1198 VisitedUsingDirectives = true;
1199 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001200
1201 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1202 R.resolveKind();
1203 return true;
1204 }
1205
1206 continue;
1207 }
1208
Douglas Gregor7f737c02009-09-10 16:57:35 +00001209 // Perform qualified name lookup into this context.
1210 // FIXME: In some cases, we know that every name that could be found by
1211 // this qualified name lookup will also be on the identifier chain. For
1212 // example, inside a class without any base classes, we never need to
1213 // perform qualified lookup because all of the members are on top of the
1214 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001215 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001216 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001217 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001218 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001219 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001220
John McCallf6c8a4e2009-11-10 07:01:13 +00001221 // Stop if we ran out of scopes.
1222 // FIXME: This really, really shouldn't be happening.
1223 if (!S) return false;
1224
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001225 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001226 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001227 return false;
1228
Douglas Gregor700792c2009-02-05 19:25:20 +00001229 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001230 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001231 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001232 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1233 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001234 if (!VisitedUsingDirectives) {
1235 UDirs.visitScopeChain(Initial, S);
1236 UDirs.done();
1237 }
Richard Smith541b38b2013-09-20 01:15:31 +00001238
1239 // If we're not performing redeclaration lookup, do not look for local
1240 // extern declarations outside of a function scope.
1241 if (!R.isForRedeclaration())
1242 FindLocals.restore();
1243
Douglas Gregor700792c2009-02-05 19:25:20 +00001244 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001245 // Unqualified name lookup in C++ requires looking into scopes
1246 // that aren't strictly lexical, and therefore we walk through the
1247 // context as well as walking through the scopes.
1248 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001249 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001250 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001251 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001252 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001253 // We found something. Look for anything else in our scope
1254 // with this same name and in an acceptable identifier
1255 // namespace, so that we can construct an overload set if we
1256 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001257 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001258 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001259 }
1260 }
1261
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001262 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001263 R.resolveKind();
1264 return true;
1265 }
1266
Ted Kremenekc37877d2013-10-08 17:08:03 +00001267 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001268 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1269 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1270 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001271 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001272 // lexical and semantic declaration contexts returned by
1273 // findOuterContext(). This implements the name lookup behavior
1274 // of C++ [temp.local]p8.
1275 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001276 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001279 if (Ctx) {
1280 DeclContext *OuterCtx;
1281 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001282 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001283 if (SearchAfterTemplateScope)
1284 OutsideOfTemplateParamDC = OuterCtx;
1285
1286 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1287 // We do not directly look into transparent contexts, since
1288 // those entities will be found in the nearest enclosing
1289 // non-transparent context.
1290 if (Ctx->isTransparentContext())
1291 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001293 // If we have a context, and it's not a context stashed in the
1294 // template parameter scope for an out-of-line definition, also
1295 // look into that context.
1296 if (!(Found && S && S->isTemplateParamScope())) {
1297 assert(Ctx->isFileContext() &&
1298 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001299
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001300 // Look into context considering using-directives.
1301 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1302 Found = true;
1303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001305 if (Found) {
1306 R.resolveKind();
1307 return true;
1308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001309
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001310 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1311 return false;
1312 }
1313 }
1314
Douglas Gregor3ce74932010-02-05 07:07:10 +00001315 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001316 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001317 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001318
John McCall9f3059a2009-10-09 21:13:30 +00001319 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001320}
1321
Richard Smith0e5d7b82013-07-25 23:08:39 +00001322/// \brief Find the declaration that a class temploid member specialization was
1323/// instantiated from, or the member itself if it is an explicit specialization.
1324static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1325 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1326}
1327
Richard Smith42413142015-05-15 20:05:43 +00001328Module *Sema::getOwningModule(Decl *Entity) {
1329 // If it's imported, grab its owning module.
1330 Module *M = Entity->getImportedOwningModule();
1331 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1332 return M;
1333 assert(!Entity->isFromASTFile() &&
1334 "hidden entity from AST file has no owning module");
1335
Richard Smith87bb5692015-06-09 00:35:49 +00001336 if (!getLangOpts().ModulesLocalVisibility) {
1337 // If we're not tracking visibility locally, the only way a declaration
1338 // can be hidden and local is if it's hidden because it's parent is (for
1339 // instance, maybe this is a lazily-declared special member of an imported
1340 // class).
1341 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1342 assert(Parent->isHidden() && "unexpectedly hidden decl");
1343 return getOwningModule(Parent);
1344 }
1345
Richard Smith42413142015-05-15 20:05:43 +00001346 // It's local and hidden; grab or compute its owning module.
1347 M = Entity->getLocalOwningModule();
1348 if (M)
1349 return M;
1350
1351 if (auto *Containing =
1352 PP.getModuleContainingLocation(Entity->getLocation())) {
1353 M = Containing;
1354 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1355 // Don't bother tracking visibility for invalid declarations with broken
1356 // locations.
1357 cast<NamedDecl>(Entity)->setHidden(false);
1358 } else {
1359 // We need to assign a module to an entity that exists outside of any
1360 // module, so that we can hide it from modules that we textually enter.
1361 // Invent a fake module for all such entities.
1362 if (!CachedFakeTopLevelModule) {
1363 CachedFakeTopLevelModule =
1364 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1365 "<top-level>", nullptr, false, false).first;
1366
1367 auto &SrcMgr = PP.getSourceManager();
1368 SourceLocation StartLoc =
1369 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1370 auto &TopLevel =
1371 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1372 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1373 }
1374
1375 M = CachedFakeTopLevelModule;
1376 }
1377
1378 if (M)
1379 Entity->setLocalOwningModule(M);
1380 return M;
1381}
1382
Richard Smithd9ba2242015-05-07 03:54:19 +00001383void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001384 if (auto *M = PP.getModuleContainingLocation(Loc))
1385 Context.mergeDefinitionIntoModule(ND, M);
1386 else
1387 // We're not building a module; just make the definition visible.
1388 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001389
1390 // If ND is a template declaration, make the template parameters
1391 // visible too. They're not (necessarily) within a mergeable DeclContext.
1392 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1393 for (auto *Param : *TD->getTemplateParameters())
1394 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001395}
1396
Richard Smith0e5d7b82013-07-25 23:08:39 +00001397/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001398static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001399 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1400 // If this function was instantiated from a template, the defining module is
1401 // the module containing the pattern.
1402 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1403 Entity = Pattern;
1404 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001405 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1406 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001407 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1408 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1409 Entity = getInstantiatedFrom(ED, MSInfo);
1410 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1411 // FIXME: Map from variable template specializations back to the template.
1412 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1413 Entity = getInstantiatedFrom(VD, MSInfo);
1414 }
1415
1416 // Walk up to the containing context. That might also have been instantiated
1417 // from a template.
1418 DeclContext *Context = Entity->getDeclContext();
1419 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001420 return S.getOwningModule(Entity);
1421 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001422}
1423
1424llvm::DenseSet<Module*> &Sema::getLookupModules() {
1425 unsigned N = ActiveTemplateInstantiations.size();
1426 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1427 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001428 Module *M =
1429 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001430 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001431 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001432 ActiveTemplateInstantiationLookupModules.push_back(M);
1433 }
1434 return LookupModulesCache;
1435}
1436
Richard Smith42413142015-05-15 20:05:43 +00001437bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1438 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1439 if (isModuleVisible(Merged))
1440 return true;
1441 return false;
1442}
1443
Richard Smithe7bd6de2015-06-10 20:30:23 +00001444template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001445static bool
1446hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1447 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001448 if (!D->hasDefaultArgument())
1449 return false;
1450
1451 while (D) {
1452 auto &DefaultArg = D->getDefaultArgStorage();
1453 if (!DefaultArg.isInherited() && S.isVisible(D))
1454 return true;
1455
Richard Smith63e09bf2015-06-17 20:39:41 +00001456 if (!DefaultArg.isInherited() && Modules) {
1457 auto *NonConstD = const_cast<ParmDecl*>(D);
1458 Modules->push_back(S.getOwningModule(NonConstD));
1459 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1460 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1461 }
Richard Smith35c1df52015-06-17 20:16:32 +00001462
Richard Smithe7bd6de2015-06-10 20:30:23 +00001463 // If there was a previous default argument, maybe its parameter is visible.
1464 D = DefaultArg.getInheritedFrom();
1465 }
1466 return false;
1467}
1468
Richard Smith35c1df52015-06-17 20:16:32 +00001469bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1470 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001471 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001472 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001473 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001474 return ::hasVisibleDefaultArgument(*this, P, Modules);
1475 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1476 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001477}
1478
Richard Smith6739a102016-05-05 00:56:12 +00001479bool Sema::hasVisibleMemberSpecialization(
1480 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1481 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1482 "not a member specialization");
1483 for (auto *Redecl : D->redecls()) {
1484 // If the specialization is declared at namespace scope, then it's a member
1485 // specialization declaration. If it's lexically inside the class
1486 // definition then it was instantiated.
1487 //
1488 // FIXME: This is a hack. There should be a better way to determine this.
1489 // FIXME: What about MS-style explicit specializations declared within a
1490 // class definition?
1491 if (Redecl->getLexicalDeclContext()->isFileContext()) {
1492 auto *NonConstR = const_cast<NamedDecl*>(cast<NamedDecl>(Redecl));
1493
1494 if (isVisible(NonConstR))
1495 return true;
1496
1497 if (Modules) {
1498 Modules->push_back(getOwningModule(NonConstR));
1499 const auto &Merged = Context.getModulesWithMergedDefinition(NonConstR);
1500 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1501 }
1502 }
1503 }
1504
1505 return false;
1506}
1507
Richard Smith0e5d7b82013-07-25 23:08:39 +00001508/// \brief Determine whether a declaration is visible to name lookup.
1509///
1510/// This routine determines whether the declaration D is visible in the current
1511/// lookup context, taking into account the current template instantiation
1512/// stack. During template instantiation, a declaration is visible if it is
1513/// visible from a module containing any entity on the template instantiation
1514/// path (by instantiating a template, you allow it to see the declarations that
1515/// your module can see, including those later on in your module).
1516bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001517 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001518 Module *DeclModule = nullptr;
1519
1520 if (SemaRef.getLangOpts().ModulesLocalVisibility) {
1521 DeclModule = SemaRef.getOwningModule(D);
1522 if (!DeclModule) {
1523 // getOwningModule() may have decided the declaration should not be hidden.
1524 assert(!D->isHidden() && "hidden decl not from a module");
Richard Smith42413142015-05-15 20:05:43 +00001525 return true;
Richard Smith5196a172015-08-24 03:38:11 +00001526 }
1527
1528 // If the owning module is visible, and the decl is not module private,
1529 // then the decl is visible too. (Module private is ignored within the same
1530 // top-level module.)
1531 if ((!D->isFromASTFile() || !D->isModulePrivate()) &&
1532 (SemaRef.isModuleVisible(DeclModule) ||
1533 SemaRef.hasVisibleMergedDefinition(D)))
Richard Smith42413142015-05-15 20:05:43 +00001534 return true;
1535 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001536
Richard Smithbe3980b2015-03-27 00:41:57 +00001537 // If this declaration is not at namespace scope nor module-private,
1538 // then it is visible if its lexical parent has a visible definition.
1539 DeclContext *DC = D->getLexicalDeclContext();
1540 if (!D->isModulePrivate() &&
1541 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001542 // For a parameter, check whether our current template declaration's
1543 // lexical context is visible, not whether there's some other visible
1544 // definition of it, because parameters aren't "within" the definition.
1545 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1546 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1547 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001548 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1549 // FIXME: Do something better in this case.
1550 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001551 // Cache the fact that this declaration is implicitly visible because
1552 // its parent has a visible definition.
1553 D->setHidden(false);
1554 }
1555 return true;
1556 }
1557 return false;
1558 }
1559
Richard Smith0e5d7b82013-07-25 23:08:39 +00001560 // Find the extra places where we need to look.
1561 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1562 if (LookupModules.empty())
1563 return false;
1564
Richard Smith5196a172015-08-24 03:38:11 +00001565 if (!DeclModule) {
1566 DeclModule = SemaRef.getOwningModule(D);
1567 assert(DeclModule && "hidden decl not from a module");
1568 }
1569
Richard Smith0e5d7b82013-07-25 23:08:39 +00001570 // If our lookup set contains the decl's module, it's visible.
1571 if (LookupModules.count(DeclModule))
1572 return true;
1573
1574 // If the declaration isn't exported, it's not visible in any other module.
1575 if (D->isModulePrivate())
1576 return false;
1577
1578 // Check whether DeclModule is transitively exported to an import of
1579 // the lookup set.
Yaron Keren941ad902015-11-23 19:28:42 +00001580 return std::any_of(LookupModules.begin(), LookupModules.end(),
Yaron Keren4c31fcf2015-11-24 20:18:24 +00001581 [&](Module *M) { return M->isModuleVisible(DeclModule); });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001582}
1583
Richard Smith42413142015-05-15 20:05:43 +00001584bool Sema::isVisibleSlow(const NamedDecl *D) {
1585 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1586}
1587
Richard Smith10568d82015-11-17 03:02:41 +00001588bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1589 for (auto *D : R) {
1590 if (isVisible(D))
1591 return true;
1592 }
1593 return New->isExternallyVisible();
1594}
1595
Douglas Gregor4a814562011-12-14 16:03:29 +00001596/// \brief Retrieve the visible declaration corresponding to D, if any.
1597///
1598/// This routine determines whether the declaration D is visible in the current
1599/// module, with the current imports. If not, it checks whether any
1600/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001601///
Douglas Gregor4a814562011-12-14 16:03:29 +00001602/// \returns D, or a visible previous declaration of D, whichever is more recent
1603/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001604static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1605 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001606
Aaron Ballman86c93902014-03-06 23:45:36 +00001607 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001608 // Don't bother with extra checks if we already know this one isn't visible.
1609 if (RD == D)
1610 continue;
1611
Richard Smith6739a102016-05-05 00:56:12 +00001612 auto ND = cast<NamedDecl>(RD);
1613 // FIXME: This is wrong in the case where the previous declaration is not
1614 // visible in the same scope as D. This needs to be done much more
1615 // carefully.
1616 if (LookupResult::isVisible(SemaRef, ND))
1617 return ND;
Douglas Gregor4a814562011-12-14 16:03:29 +00001618 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001619
Craig Topperc3ec1492014-05-26 06:22:03 +00001620 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001621}
1622
Richard Smith6739a102016-05-05 00:56:12 +00001623bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1624 llvm::SmallVectorImpl<Module *> *Modules) {
1625 assert(!isVisible(D) && "not in slow case");
1626
1627 for (auto *Redecl : D->redecls()) {
1628 auto *NonConstR = const_cast<NamedDecl*>(cast<NamedDecl>(Redecl));
1629 if (isVisible(NonConstR))
1630 return true;
1631
1632 if (Modules) {
1633 Modules->push_back(getOwningModule(NonConstR));
1634 const auto &Merged = Context.getModulesWithMergedDefinition(NonConstR);
1635 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1636 }
1637 }
1638
1639 return false;
1640}
1641
Richard Smithe156254d2013-08-20 20:35:18 +00001642NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001643 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1644 // Namespaces are a bit of a special case: we expect there to be a lot of
1645 // redeclarations of some namespaces, all declarations of a namespace are
1646 // essentially interchangeable, all declarations are found by name lookup
1647 // if any is, and namespaces are never looked up during template
1648 // instantiation. So we benefit from caching the check in this case, and
1649 // it is correct to do so.
1650 auto *Key = ND->getCanonicalDecl();
1651 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1652 return Acceptable;
1653 auto *Acceptable =
1654 isVisible(getSema(), Key) ? Key : findAcceptableDecl(getSema(), Key);
1655 if (Acceptable)
1656 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1657 return Acceptable;
1658 }
1659
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001660 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001661}
1662
Douglas Gregor34074322009-01-14 22:20:51 +00001663/// @brief Perform unqualified name lookup starting from a given
1664/// scope.
1665///
1666/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1667/// used to find names within the current scope. For example, 'x' in
1668/// @code
1669/// int x;
1670/// int f() {
1671/// return x; // unqualified name look finds 'x' in the global scope
1672/// }
1673/// @endcode
1674///
1675/// Different lookup criteria can find different names. For example, a
1676/// particular scope can have both a struct and a function of the same
1677/// name, and each can be found by certain lookup criteria. For more
1678/// information about lookup criteria, see the documentation for the
1679/// class LookupCriteria.
1680///
1681/// @param S The scope from which unqualified name lookup will
1682/// begin. If the lookup criteria permits, name lookup may also search
1683/// in the parent scopes.
1684///
James Dennett91738ff2012-06-22 10:32:46 +00001685/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1686/// look up and the lookup kind), and is updated with the results of lookup
1687/// including zero or more declarations and possibly additional information
1688/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001689///
James Dennett91738ff2012-06-22 10:32:46 +00001690/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001691bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1692 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001693 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001694
John McCall27b18f82009-11-17 02:14:36 +00001695 LookupNameKind NameKind = R.getLookupKind();
1696
David Blaikiebbafb8a2012-03-11 07:00:24 +00001697 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001698 // Unqualified name lookup in C/Objective-C is purely lexical, so
1699 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001700 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001701 // Find the nearest non-transparent declaration scope.
1702 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001703 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001704 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001705 }
1706
Richard Smith541b38b2013-09-20 01:15:31 +00001707 // When performing a scope lookup, we want to find local extern decls.
1708 FindLocalExternScope FindLocals(R);
1709
Douglas Gregor34074322009-01-14 22:20:51 +00001710 // Scan up the scope chain looking for a decl that matches this
1711 // identifier that is in the appropriate namespace. This search
1712 // should not take long, as shadowing of names is uncommon, and
1713 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001714 bool LeftStartingScope = false;
1715
Douglas Gregored8f2882009-01-30 01:04:22 +00001716 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001717 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001718 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001719 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001720 if (NameKind == LookupRedeclarationWithLinkage) {
1721 // Determine whether this (or a previous) declaration is
1722 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001723 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001724 LeftStartingScope = true;
1725
1726 // If we found something outside of our starting scope that
1727 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001728 if (LeftStartingScope && !((*I)->hasLinkage())) {
1729 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001730 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001731 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001732 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001733 else if (NameKind == LookupObjCImplicitSelfParam &&
1734 !isa<ImplicitParamDecl>(*I))
1735 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001736
Douglas Gregor4a814562011-12-14 16:03:29 +00001737 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001738
Douglas Gregorb59643b2012-01-03 23:26:26 +00001739 // Check whether there are any other declarations with the same name
1740 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001741 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001742 // Find the scope in which this declaration was declared (if it
1743 // actually exists in a Scope).
1744 while (S && !S->isDeclScope(D))
1745 S = S->getParent();
1746
1747 // If the scope containing the declaration is the translation unit,
1748 // then we'll need to perform our checks based on the matching
1749 // DeclContexts rather than matching scopes.
1750 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001751 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001752
1753 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001754 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001755 if (!S)
1756 DC = (*I)->getDeclContext()->getRedeclContext();
1757
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001758 IdentifierResolver::iterator LastI = I;
1759 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001760 if (S) {
1761 // Match based on scope.
1762 if (!S->isDeclScope(*LastI))
1763 break;
1764 } else {
1765 // Match based on DeclContext.
1766 DeclContext *LastDC
1767 = (*LastI)->getDeclContext()->getRedeclContext();
1768 if (!LastDC->Equals(DC))
1769 break;
1770 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001771
1772 // If the declaration is in the right namespace and visible, add it.
1773 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1774 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001775 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001776
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001777 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001778 }
Richard Smith541b38b2013-09-20 01:15:31 +00001779
John McCall9f3059a2009-10-09 21:13:30 +00001780 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001781 }
Douglas Gregor34074322009-01-14 22:20:51 +00001782 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001783 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001784 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001785 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001786 }
1787
1788 // If we didn't find a use of this identifier, and if the identifier
1789 // corresponds to a compiler builtin, create the decl object for the builtin
1790 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001791 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1792 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001793
Axel Naumann016538a2011-02-24 16:47:47 +00001794 // If we didn't find a use of this identifier, the ExternalSource
1795 // may be able to handle the situation.
1796 // Note: some lookup failures are expected!
1797 // See e.g. R.isForRedeclaration().
1798 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001799}
1800
John McCall6538c932009-10-10 05:48:19 +00001801/// @brief Perform qualified name lookup in the namespaces nominated by
1802/// using directives by the given context.
1803///
1804/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001805/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001806/// (where X is the global namespace), let S be the set of all
1807/// declarations of m in X and in the transitive closure of all
1808/// namespaces nominated by using-directives in X and its used
1809/// namespaces, except that using-directives are ignored in any
1810/// namespace, including X, directly containing one or more
1811/// declarations of m. No namespace is searched more than once in
1812/// the lookup of a name. If S is the empty set, the program is
1813/// ill-formed. Otherwise, if S has exactly one member, or if the
1814/// context of the reference is a using-declaration
1815/// (namespace.udecl), S is the required set of declarations of
1816/// m. Otherwise if the use of m is not one that allows a unique
1817/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001818///
John McCall6538c932009-10-10 05:48:19 +00001819/// C++98 [namespace.qual]p5:
1820/// During the lookup of a qualified namespace member name, if the
1821/// lookup finds more than one declaration of the member, and if one
1822/// declaration introduces a class name or enumeration name and the
1823/// other declarations either introduce the same object, the same
1824/// enumerator or a set of functions, the non-type name hides the
1825/// class or enumeration name if and only if the declarations are
1826/// from the same namespace; otherwise (the declarations are from
1827/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001828static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001829 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001830 assert(StartDC->isFileContext() && "start context is not a file context");
1831
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001832 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1833 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001834
1835 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001836 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001837 Visited.insert(StartDC);
1838
1839 // We have not yet looked into these namespaces, much less added
1840 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001841 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001842
1843 // We have already looked into the initial namespace; seed the queue
1844 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001845 for (auto *I : UsingDirectives) {
1846 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001847 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001848 Queue.push_back(ND);
1849 }
1850
1851 // The easiest way to implement the restriction in [namespace.qual]p5
1852 // is to check whether any of the individual results found a tag
1853 // and, if so, to declare an ambiguity if the final result is not
1854 // a tag.
1855 bool FoundTag = false;
1856 bool FoundNonTag = false;
1857
John McCall5cebab12009-11-18 07:57:50 +00001858 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001859
1860 bool Found = false;
1861 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001862 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001863
1864 // We go through some convolutions here to avoid copying results
1865 // between LookupResults.
1866 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001867 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001868 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001869
1870 if (FoundDirect) {
1871 // First do any local hiding.
1872 DirectR.resolveKind();
1873
1874 // If the local result is a tag, remember that.
1875 if (DirectR.isSingleTagDecl())
1876 FoundTag = true;
1877 else
1878 FoundNonTag = true;
1879
1880 // Append the local results to the total results if necessary.
1881 if (UseLocal) {
1882 R.addAllDecls(LocalR);
1883 LocalR.clear();
1884 }
1885 }
1886
1887 // If we find names in this namespace, ignore its using directives.
1888 if (FoundDirect) {
1889 Found = true;
1890 continue;
1891 }
1892
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001893 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001894 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001895 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001896 Queue.push_back(Nom);
1897 }
1898 }
1899
1900 if (Found) {
1901 if (FoundTag && FoundNonTag)
1902 R.setAmbiguousQualifiedTagHiding();
1903 else
1904 R.resolveKind();
1905 }
1906
1907 return Found;
1908}
1909
Douglas Gregor39982192010-08-15 06:18:01 +00001910/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001912 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001913 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001915 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001916 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001917}
1918
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001920/// static members, nested types, and enumerators.
1921template<typename InputIterator>
1922static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1923 Decl *D = (*First)->getUnderlyingDecl();
1924 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1925 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Douglas Gregorc0d24902010-10-22 22:08:47 +00001927 if (isa<CXXMethodDecl>(D)) {
1928 // Determine whether all of the methods are static.
1929 bool AllMethodsAreStatic = true;
1930 for(; First != Last; ++First) {
1931 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregorc0d24902010-10-22 22:08:47 +00001933 if (!isa<CXXMethodDecl>(D)) {
1934 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1935 break;
1936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937
Douglas Gregorc0d24902010-10-22 22:08:47 +00001938 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1939 AllMethodsAreStatic = false;
1940 break;
1941 }
1942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943
Douglas Gregorc0d24902010-10-22 22:08:47 +00001944 if (AllMethodsAreStatic)
1945 return true;
1946 }
1947
1948 return false;
1949}
1950
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001951/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001952///
1953/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1954/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001955/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001956///
1957/// Different lookup criteria can find different names. For example, a
1958/// particular scope can have both a struct and a function of the same
1959/// name, and each can be found by certain lookup criteria. For more
1960/// information about lookup criteria, see the documentation for the
1961/// class LookupCriteria.
1962///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001963/// \param R captures both the lookup criteria and any lookup results found.
1964///
1965/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001966/// search. If the lookup criteria permits, name lookup may also search
1967/// in the parent contexts or (for C++ classes) base classes.
1968///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001970/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001971///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001972/// \returns true if lookup succeeded, false if it failed.
1973bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1974 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001975 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001976
John McCall27b18f82009-11-17 02:14:36 +00001977 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001978 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001980 // Make sure that the declaration context is complete.
1981 assert((!isa<TagDecl>(LookupCtx) ||
1982 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001983 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001984 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001985 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001986
Eugene Leviant0d8103e2015-11-18 12:48:05 +00001987 struct QualifiedLookupInScope {
1988 bool oldVal;
1989 DeclContext *Context;
1990 // Set flag in DeclContext informing debugger that we're looking for qualified name
1991 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
1992 oldVal = ctx->setUseQualifiedLookup();
1993 }
1994 ~QualifiedLookupInScope() {
1995 Context->setUseQualifiedLookup(oldVal);
1996 }
1997 } QL(LookupCtx);
1998
Douglas Gregord3a59182010-02-12 05:48:04 +00001999 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00002000 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00002001 if (isa<CXXRecordDecl>(LookupCtx))
2002 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00002003 return true;
2004 }
Douglas Gregor34074322009-01-14 22:20:51 +00002005
John McCall6538c932009-10-10 05:48:19 +00002006 // Don't descend into implied contexts for redeclarations.
2007 // C++98 [namespace.qual]p6:
2008 // In a declaration for a namespace member in which the
2009 // declarator-id is a qualified-id, given that the qualified-id
2010 // for the namespace member has the form
2011 // nested-name-specifier unqualified-id
2012 // the unqualified-id shall name a member of the namespace
2013 // designated by the nested-name-specifier.
2014 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00002015 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00002016 return false;
2017
John McCall27b18f82009-11-17 02:14:36 +00002018 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00002019 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00002020 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00002021
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002022 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00002023 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002024 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00002025 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00002026 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002027
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002028 // If we're performing qualified name lookup into a dependent class,
2029 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002031 // template instantiation time (at which point all bases will be available)
2032 // or we have to fail.
2033 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2034 LookupRec->hasAnyDependentBases()) {
2035 R.setNotFoundInCurrentInstantiation();
2036 return false;
2037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002039 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002040 CXXBasePaths Paths;
2041 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002042
2043 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002044 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2045 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002046 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002047 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002048 case LookupOrdinaryName:
2049 case LookupMemberName:
2050 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002051 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002052 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2053 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
Douglas Gregor36d1b142009-10-06 17:59:45 +00002055 case LookupTagName:
2056 BaseCallback = &CXXRecordDecl::FindTagMember;
2057 break;
John McCall84d87672009-12-10 09:41:52 +00002058
Douglas Gregor39982192010-08-15 06:18:01 +00002059 case LookupAnyName:
2060 BaseCallback = &LookupAnyMember;
2061 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002062
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002063 case LookupOMPReductionName:
2064 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2065 break;
2066
John McCall84d87672009-12-10 09:41:52 +00002067 case LookupUsingDeclName:
2068 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Douglas Gregor36d1b142009-10-06 17:59:45 +00002070 case LookupOperatorName:
2071 case LookupNamespaceName:
2072 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002073 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002074 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002075 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002076
Douglas Gregor36d1b142009-10-06 17:59:45 +00002077 case LookupNestedNameSpecifierName:
2078 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2079 break;
2080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002082 DeclarationName Name = R.getLookupName();
2083 if (!LookupRec->lookupInBases(
2084 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2085 return BaseCallback(Specifier, Path, Name);
2086 },
2087 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002088 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002089
John McCall553c0792010-01-23 00:46:32 +00002090 R.setNamingClass(LookupRec);
2091
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002092 // C++ [class.member.lookup]p2:
2093 // [...] If the resulting set of declarations are not all from
2094 // sub-objects of the same type, or the set has a nonstatic member
2095 // and includes members from distinct sub-objects, there is an
2096 // ambiguity and the program is ill-formed. Otherwise that set is
2097 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002098 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002099 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002100 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002101
Douglas Gregor36d1b142009-10-06 17:59:45 +00002102 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002103 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002104 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002105
John McCall401982f2010-01-20 21:53:11 +00002106 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2107 // across all paths.
2108 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002110 // Determine whether we're looking at a distinct sub-object or not.
2111 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002112 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002113 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2114 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002115 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116 }
2117
Douglas Gregorc0d24902010-10-22 22:08:47 +00002118 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002119 != Context.getCanonicalType(PathElement.Base->getType())) {
2120 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002121 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002122 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002123 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002124 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002125 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2126 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127
David Blaikieff7d47a2012-12-19 00:45:41 +00002128 while (FirstD != FirstPath->Decls.end() &&
2129 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002130 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2131 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2132 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133
Douglas Gregorc0d24902010-10-22 22:08:47 +00002134 ++FirstD;
2135 ++CurrentD;
2136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137
David Blaikieff7d47a2012-12-19 00:45:41 +00002138 if (FirstD == FirstPath->Decls.end() &&
2139 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002140 continue;
2141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002142
John McCall9f3059a2009-10-09 21:13:30 +00002143 R.setAmbiguousBaseSubobjectTypes(Paths);
2144 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145 }
2146
Douglas Gregorc0d24902010-10-22 22:08:47 +00002147 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002148 // We have a different subobject of the same type.
2149
2150 // C++ [class.member.lookup]p5:
2151 // A static member, a nested type or an enumerator defined in
2152 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002153 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002154 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002155 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002157 // We have found a nonstatic member name in multiple, distinct
2158 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002159 R.setAmbiguousBaseSubobjects(Paths);
2160 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002161 }
2162 }
2163
2164 // Lookup in a base class succeeded; return these results.
2165
Aaron Ballman1e606f42014-07-15 22:03:49 +00002166 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002167 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2168 D->getAccess());
2169 R.addDecl(D, AS);
2170 }
John McCall9f3059a2009-10-09 21:13:30 +00002171 R.resolveKind();
2172 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002173}
2174
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002175/// \brief Performs qualified name lookup or special type of lookup for
2176/// "__super::" scope specifier.
2177///
2178/// This routine is a convenience overload meant to be called from contexts
2179/// that need to perform a qualified name lookup with an optional C++ scope
2180/// specifier that might require special kind of lookup.
2181///
2182/// \param R captures both the lookup criteria and any lookup results found.
2183///
2184/// \param LookupCtx The context in which qualified name lookup will
2185/// search.
2186///
2187/// \param SS An optional C++ scope-specifier.
2188///
2189/// \returns true if lookup succeeded, false if it failed.
2190bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2191 CXXScopeSpec &SS) {
2192 auto *NNS = SS.getScopeRep();
2193 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2194 return LookupInSuper(R, NNS->getAsRecordDecl());
2195 else
2196
2197 return LookupQualifiedName(R, LookupCtx);
2198}
2199
Douglas Gregor34074322009-01-14 22:20:51 +00002200/// @brief Performs name lookup for a name that was parsed in the
2201/// source code, and may contain a C++ scope specifier.
2202///
2203/// This routine is a convenience routine meant to be called from
2204/// contexts that receive a name and an optional C++ scope specifier
2205/// (e.g., "N::M::x"). It will then perform either qualified or
2206/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002207/// respectively) on the given name and return those results. It will
2208/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002209///
2210/// @param S The scope from which unqualified name lookup will
2211/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002212///
Douglas Gregore861bac2009-08-25 22:51:20 +00002213/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002214///
Douglas Gregore861bac2009-08-25 22:51:20 +00002215/// @param EnteringContext Indicates whether we are going to enter the
2216/// context of the scope-specifier SS (if present).
2217///
John McCall9f3059a2009-10-09 21:13:30 +00002218/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002219bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002220 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002221 if (SS && SS->isInvalid()) {
2222 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002223 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002224 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregore861bac2009-08-25 22:51:20 +00002227 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002228 NestedNameSpecifier *NNS = SS->getScopeRep();
2229 if (NNS->getKind() == NestedNameSpecifier::Super)
2230 return LookupInSuper(R, NNS->getAsRecordDecl());
2231
Douglas Gregore861bac2009-08-25 22:51:20 +00002232 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002233 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002234 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002235 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002236 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002237
John McCall27b18f82009-11-17 02:14:36 +00002238 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002239 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002240 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002241
Douglas Gregore861bac2009-08-25 22:51:20 +00002242 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002243 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002244 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002245 R.setNotFoundInCurrentInstantiation();
2246 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002247 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002248 }
2249
Mike Stump11289f42009-09-09 15:08:12 +00002250 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002251 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002252}
2253
Nikola Smiljanic67860242014-09-26 00:28:20 +00002254/// \brief Perform qualified name lookup into all base classes of the given
2255/// class.
2256///
2257/// \param R captures both the lookup criteria and any lookup results found.
2258///
2259/// \param Class The context in which qualified name lookup will
2260/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002261///
2262/// @returns True if any decls were found (but possibly ambiguous)
2263bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002264 // The access-control rules we use here are essentially the rules for
2265 // doing a lookup in Class that just magically skipped the direct
2266 // members of Class itself. That is, the naming class is Class, and the
2267 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002268 for (const auto &BaseSpec : Class->bases()) {
2269 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2270 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2271 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2272 Result.setBaseObjectType(Context.getRecordType(Class));
2273 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002274
2275 // Copy the lookup results into the target, merging the base's access into
2276 // the path access.
2277 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2278 R.addDecl(I.getDecl(),
2279 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2280 I.getAccess()));
2281 }
2282
2283 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002284 }
2285
2286 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002287 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002288
2289 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002290}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002291
James Dennett41725122012-06-22 10:16:05 +00002292/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002293/// from name lookup.
2294///
James Dennett41725122012-06-22 10:16:05 +00002295/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002296void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002297 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2298
John McCall27b18f82009-11-17 02:14:36 +00002299 DeclarationName Name = Result.getLookupName();
2300 SourceLocation NameLoc = Result.getNameLoc();
2301 SourceRange LookupRange = Result.getContextRange();
2302
John McCall6538c932009-10-10 05:48:19 +00002303 switch (Result.getAmbiguityKind()) {
2304 case LookupResult::AmbiguousBaseSubobjects: {
2305 CXXBasePaths *Paths = Result.getBasePaths();
2306 QualType SubobjectType = Paths->front().back().Base->getType();
2307 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2308 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2309 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002310
David Blaikieff7d47a2012-12-19 00:45:41 +00002311 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002312 while (isa<CXXMethodDecl>(*Found) &&
2313 cast<CXXMethodDecl>(*Found)->isStatic())
2314 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002315
John McCall6538c932009-10-10 05:48:19 +00002316 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002317 break;
John McCall6538c932009-10-10 05:48:19 +00002318 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002319
John McCall6538c932009-10-10 05:48:19 +00002320 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002321 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2322 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002323
John McCall6538c932009-10-10 05:48:19 +00002324 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002325 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002326 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2327 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002328 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002329 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002330 if (DeclsPrinted.insert(D).second)
2331 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2332 }
Serge Pavlov99292092013-08-29 07:23:24 +00002333 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002334 }
2335
John McCall6538c932009-10-10 05:48:19 +00002336 case LookupResult::AmbiguousTagHiding: {
2337 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002338
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002339 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002340
Aaron Ballman1e606f42014-07-15 22:03:49 +00002341 for (auto *D : Result)
2342 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002343 TagDecls.insert(TD);
2344 Diag(TD->getLocation(), diag::note_hidden_tag);
2345 }
2346
Aaron Ballman1e606f42014-07-15 22:03:49 +00002347 for (auto *D : Result)
2348 if (!isa<TagDecl>(D))
2349 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002350
2351 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002352 LookupResult::Filter F = Result.makeFilter();
2353 while (F.hasNext()) {
2354 if (TagDecls.count(F.next()))
2355 F.erase();
2356 }
2357 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002358 break;
John McCall6538c932009-10-10 05:48:19 +00002359 }
2360
2361 case LookupResult::AmbiguousReference: {
2362 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002363
Aaron Ballman1e606f42014-07-15 22:03:49 +00002364 for (auto *D : Result)
2365 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002366 break;
John McCall6538c932009-10-10 05:48:19 +00002367 }
Serge Pavlov99292092013-08-29 07:23:24 +00002368 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002369}
Douglas Gregore254f902009-02-04 00:32:51 +00002370
John McCallf24d7bb2010-05-28 18:45:08 +00002371namespace {
2372 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002373 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002374 Sema::AssociatedNamespaceSet &Namespaces,
2375 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002376 : S(S), Namespaces(Namespaces), Classes(Classes),
2377 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002378 }
2379
2380 Sema &S;
2381 Sema::AssociatedNamespaceSet &Namespaces;
2382 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002383 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002384 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002385} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002386
Mike Stump11289f42009-09-09 15:08:12 +00002387static void
John McCallf24d7bb2010-05-28 18:45:08 +00002388addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002389
Douglas Gregor8b895222010-04-30 07:08:38 +00002390static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2391 DeclContext *Ctx) {
2392 // Add the associated namespace for this class.
2393
2394 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2395 // be a locally scoped record.
2396
Sebastian Redlbd595762010-08-31 20:53:31 +00002397 // We skip out of inline namespaces. The innermost non-inline namespace
2398 // contains all names of all its nested inline namespaces anyway, so we can
2399 // replace the entire inline namespace tree with its root.
2400 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2401 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002402 Ctx = Ctx->getParent();
2403
John McCallc7e8e792009-08-07 22:18:02 +00002404 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002405 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002406}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002407
Mike Stump11289f42009-09-09 15:08:12 +00002408// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002409// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002410static void
John McCallf24d7bb2010-05-28 18:45:08 +00002411addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2412 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002413 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002414 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002415 switch (Arg.getKind()) {
2416 case TemplateArgument::Null:
2417 break;
Mike Stump11289f42009-09-09 15:08:12 +00002418
Douglas Gregor197e5f72009-07-08 07:51:57 +00002419 case TemplateArgument::Type:
2420 // [...] the namespaces and classes associated with the types of the
2421 // template arguments provided for template type parameters (excluding
2422 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002423 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002424 break;
Mike Stump11289f42009-09-09 15:08:12 +00002425
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002427 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002428 // [...] the namespaces in which any template template arguments are
2429 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002430 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002431 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002432 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002433 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002434 DeclContext *Ctx = ClassTemplate->getDeclContext();
2435 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002436 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002437 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002438 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002439 }
2440 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002442
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002443 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002444 case TemplateArgument::Integral:
2445 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002446 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002447 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002448 // associated namespaces. ]
2449 break;
Mike Stump11289f42009-09-09 15:08:12 +00002450
Douglas Gregor197e5f72009-07-08 07:51:57 +00002451 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002452 for (const auto &P : Arg.pack_elements())
2453 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002454 break;
2455 }
2456}
2457
Douglas Gregore254f902009-02-04 00:32:51 +00002458// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002459// argument-dependent lookup with an argument of class type
2460// (C++ [basic.lookup.koenig]p2).
2461static void
John McCallf24d7bb2010-05-28 18:45:08 +00002462addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2463 CXXRecordDecl *Class) {
2464
2465 // Just silently ignore anything whose name is __va_list_tag.
2466 if (Class->getDeclName() == Result.S.VAListTagName)
2467 return;
2468
Douglas Gregore254f902009-02-04 00:32:51 +00002469 // C++ [basic.lookup.koenig]p2:
2470 // [...]
2471 // -- If T is a class type (including unions), its associated
2472 // classes are: the class itself; the class of which it is a
2473 // member, if any; and its direct and indirect base
2474 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002475 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002476
2477 // Add the class of which it is a member, if any.
2478 DeclContext *Ctx = Class->getDeclContext();
2479 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002480 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002481 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002482 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002483
Douglas Gregore254f902009-02-04 00:32:51 +00002484 // Add the class itself. If we've already seen this class, we don't
2485 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002486 //
2487 // FIXME: That's not correct, we may have added this class only because it
2488 // was the enclosing class of another class, and in that case we won't have
2489 // added its base classes yet.
Richard Smith6642bb32016-03-24 19:12:22 +00002490 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002491 return;
2492
Mike Stump11289f42009-09-09 15:08:12 +00002493 // -- If T is a template-id, its associated namespaces and classes are
2494 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002495 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002496 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002497 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002498 // namespaces in which any template template arguments are defined; and
2499 // the classes in which any member templates used as template template
2500 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002501 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002502 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002503 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2504 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2505 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002506 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002507 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002508 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002509
Douglas Gregor197e5f72009-07-08 07:51:57 +00002510 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2511 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002512 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002513 }
Mike Stump11289f42009-09-09 15:08:12 +00002514
John McCall67da35c2010-02-04 22:26:26 +00002515 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002516 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2517 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002518 return;
John McCall67da35c2010-02-04 22:26:26 +00002519
Douglas Gregore254f902009-02-04 00:32:51 +00002520 // Add direct and indirect base classes along with their associated
2521 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002522 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002523 Bases.push_back(Class);
2524 while (!Bases.empty()) {
2525 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002526 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002527
2528 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002529 for (const auto &Base : Class->bases()) {
2530 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002531 // In dependent contexts, we do ADL twice, and the first time around,
2532 // the base type might be a dependent TemplateSpecializationType, or a
2533 // TemplateTypeParmType. If that happens, simply ignore it.
2534 // FIXME: If we want to support export, we probably need to add the
2535 // namespace of the template in a TemplateSpecializationType, or even
2536 // the classes and namespaces of known non-dependent arguments.
2537 if (!BaseType)
2538 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002539 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6642bb32016-03-24 19:12:22 +00002540 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002541 // Find the associated namespace for this base class.
2542 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002543 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002544
2545 // Make sure we visit the bases of this base class.
2546 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2547 Bases.push_back(BaseDecl);
2548 }
2549 }
2550 }
2551}
2552
2553// \brief Add the associated classes and namespaces for
2554// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002555// (C++ [basic.lookup.koenig]p2).
2556static void
John McCallf24d7bb2010-05-28 18:45:08 +00002557addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002558 // C++ [basic.lookup.koenig]p2:
2559 //
2560 // For each argument type T in the function call, there is a set
2561 // of zero or more associated namespaces and a set of zero or more
2562 // associated classes to be considered. The sets of namespaces and
2563 // classes is determined entirely by the types of the function
2564 // arguments (and the namespace of any template template
2565 // argument). Typedef names and using-declarations used to specify
2566 // the types do not contribute to this set. The sets of namespaces
2567 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002568
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002569 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002570 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2571
Douglas Gregore254f902009-02-04 00:32:51 +00002572 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002573 switch (T->getTypeClass()) {
2574
2575#define TYPE(Class, Base)
2576#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2577#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2578#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2579#define ABSTRACT_TYPE(Class, Base)
2580#include "clang/AST/TypeNodes.def"
2581 // T is canonical. We can also ignore dependent types because
2582 // we don't need to do ADL at the definition point, but if we
2583 // wanted to implement template export (or if we find some other
2584 // use for associated classes and namespaces...) this would be
2585 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002586 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002587
John McCall0af3d3b2010-05-28 06:08:54 +00002588 // -- If T is a pointer to U or an array of U, its associated
2589 // namespaces and classes are those associated with U.
2590 case Type::Pointer:
2591 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2592 continue;
2593 case Type::ConstantArray:
2594 case Type::IncompleteArray:
2595 case Type::VariableArray:
2596 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2597 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002598
John McCall0af3d3b2010-05-28 06:08:54 +00002599 // -- If T is a fundamental type, its associated sets of
2600 // namespaces and classes are both empty.
2601 case Type::Builtin:
2602 break;
2603
2604 // -- If T is a class type (including unions), its associated
2605 // classes are: the class itself; the class of which it is a
2606 // member, if any; and its direct and indirect base
2607 // classes. Its associated namespaces are the namespaces in
2608 // which its associated classes are defined.
2609 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002610 CXXRecordDecl *Class =
2611 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002612 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002613 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002614 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002615
John McCall0af3d3b2010-05-28 06:08:54 +00002616 // -- If T is an enumeration type, its associated namespace is
2617 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002618 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002619 // it has no associated class.
2620 case Type::Enum: {
2621 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002622
John McCall0af3d3b2010-05-28 06:08:54 +00002623 DeclContext *Ctx = Enum->getDeclContext();
2624 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002625 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002626
John McCall0af3d3b2010-05-28 06:08:54 +00002627 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002628 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002629
John McCall0af3d3b2010-05-28 06:08:54 +00002630 break;
2631 }
2632
2633 // -- If T is a function type, its associated namespaces and
2634 // classes are those associated with the function parameter
2635 // types and those associated with the return type.
2636 case Type::FunctionProto: {
2637 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002638 for (const auto &Arg : Proto->param_types())
2639 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002640 // fallthrough
2641 }
2642 case Type::FunctionNoProto: {
2643 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002644 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002645 continue;
2646 }
2647
2648 // -- If T is a pointer to a member function of a class X, its
2649 // associated namespaces and classes are those associated
2650 // with the function parameter types and return type,
2651 // together with those associated with X.
2652 //
2653 // -- If T is a pointer to a data member of class X, its
2654 // associated namespaces and classes are those associated
2655 // with the member type together with those associated with
2656 // X.
2657 case Type::MemberPointer: {
2658 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2659
2660 // Queue up the class type into which this points.
2661 Queue.push_back(MemberPtr->getClass());
2662
2663 // And directly continue with the pointee type.
2664 T = MemberPtr->getPointeeType().getTypePtr();
2665 continue;
2666 }
2667
2668 // As an extension, treat this like a normal pointer.
2669 case Type::BlockPointer:
2670 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2671 continue;
2672
2673 // References aren't covered by the standard, but that's such an
2674 // obvious defect that we cover them anyway.
2675 case Type::LValueReference:
2676 case Type::RValueReference:
2677 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2678 continue;
2679
2680 // These are fundamental types.
2681 case Type::Vector:
2682 case Type::ExtVector:
2683 case Type::Complex:
2684 break;
2685
Richard Smith27d807c2013-04-30 13:56:41 +00002686 // Non-deduced auto types only get here for error cases.
2687 case Type::Auto:
2688 break;
2689
Douglas Gregor8e936662011-04-12 01:02:45 +00002690 // If T is an Objective-C object or interface type, or a pointer to an
2691 // object or interface type, the associated namespace is the global
2692 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002693 case Type::ObjCObject:
2694 case Type::ObjCInterface:
2695 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002696 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002697 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002698
2699 // Atomic types are just wrappers; use the associations of the
2700 // contained type.
2701 case Type::Atomic:
2702 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2703 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002704 case Type::Pipe:
2705 T = cast<PipeType>(T)->getElementType().getTypePtr();
2706 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002707 }
2708
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002709 if (Queue.empty())
2710 break;
2711 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002712 }
Douglas Gregore254f902009-02-04 00:32:51 +00002713}
2714
2715/// \brief Find the associated classes and namespaces for
2716/// argument-dependent lookup for a call with the given set of
2717/// arguments.
2718///
2719/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002720/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002721/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002722void Sema::FindAssociatedClassesAndNamespaces(
2723 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2724 AssociatedNamespaceSet &AssociatedNamespaces,
2725 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002726 AssociatedNamespaces.clear();
2727 AssociatedClasses.clear();
2728
John McCall7d8b0412012-08-24 20:38:34 +00002729 AssociatedLookup Result(*this, InstantiationLoc,
2730 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002731
Douglas Gregore254f902009-02-04 00:32:51 +00002732 // C++ [basic.lookup.koenig]p2:
2733 // For each argument type T in the function call, there is a set
2734 // of zero or more associated namespaces and a set of zero or more
2735 // associated classes to be considered. The sets of namespaces and
2736 // classes is determined entirely by the types of the function
2737 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002738 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002739 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002740 Expr *Arg = Args[ArgIdx];
2741
2742 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002743 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002744 continue;
2745 }
2746
2747 // [...] In addition, if the argument is the name or address of a
2748 // set of overloaded functions and/or function templates, its
2749 // associated classes and namespaces are the union of those
2750 // associated with each of the members of the set: the namespace
2751 // in which the function or function template is defined and the
2752 // classes and namespaces associated with its (non-dependent)
2753 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002754 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002755 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002756 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002757 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002758
John McCallf24d7bb2010-05-28 18:45:08 +00002759 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2760 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002761
Aaron Ballman1e606f42014-07-15 22:03:49 +00002762 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002763 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002764 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002765
2766 // Add the classes and namespaces associated with the parameter
2767 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002768 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002769 }
2770 }
2771}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002772
John McCall5cebab12009-11-18 07:57:50 +00002773NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002774 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002775 LookupNameKind NameKind,
2776 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002777 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002778 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002779 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002780}
2781
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002782/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002784 SourceLocation IdLoc,
2785 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002786 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002787 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002788 return cast_or_null<ObjCProtocolDecl>(D);
2789}
2790
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002791void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002792 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002793 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002794 // C++ [over.match.oper]p3:
2795 // -- The set of non-member candidates is the result of the
2796 // unqualified lookup of operator@ in the context of the
2797 // expression according to the usual rules for name lookup in
2798 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002799 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002800 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002801 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2802 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002803
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002804 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002805 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002806}
2807
Alexis Hunt1da39282011-06-24 02:11:39 +00002808Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002809 CXXSpecialMember SM,
2810 bool ConstArg,
2811 bool VolatileArg,
2812 bool RValueThis,
2813 bool ConstThis,
2814 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002815 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002816 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002817 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002818 if (RValueThis || ConstThis || VolatileThis)
2819 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2820 "constructors and destructors always have unqualified lvalue this");
2821 if (ConstArg || VolatileArg)
2822 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2823 "parameter-less special members can't have qualified arguments");
2824
2825 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002826 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002827 ID.AddInteger(SM);
2828 ID.AddInteger(ConstArg);
2829 ID.AddInteger(VolatileArg);
2830 ID.AddInteger(RValueThis);
2831 ID.AddInteger(ConstThis);
2832 ID.AddInteger(VolatileThis);
2833
2834 void *InsertPoint;
2835 SpecialMemberOverloadResult *Result =
2836 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2837
2838 // This was already cached
2839 if (Result)
2840 return Result;
2841
Alexis Huntba8e18d2011-06-07 00:11:58 +00002842 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2843 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002844 SpecialMemberCache.InsertNode(Result, InsertPoint);
2845
2846 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002847 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002848 DeclareImplicitDestructor(RD);
2849 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002850 assert(DD && "record without a destructor");
2851 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002852 Result->setKind(DD->isDeleted() ?
2853 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002854 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002855 return Result;
2856 }
2857
Alexis Hunteef8ee02011-06-10 03:50:41 +00002858 // Prepare for overload resolution. Here we construct a synthetic argument
2859 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002860 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002861 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002862 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002863 unsigned NumArgs;
2864
Richard Smith83c478d2012-04-20 18:46:14 +00002865 QualType ArgType = CanTy;
2866 ExprValueKind VK = VK_LValue;
2867
Alexis Hunteef8ee02011-06-10 03:50:41 +00002868 if (SM == CXXDefaultConstructor) {
2869 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2870 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002871 if (RD->needsImplicitDefaultConstructor())
2872 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002873 } else {
2874 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2875 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002876 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002877 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002878 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002879 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002880 } else {
2881 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002882 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002883 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002884 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002885 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002886 }
2887
Alexis Hunteef8ee02011-06-10 03:50:41 +00002888 if (ConstArg)
2889 ArgType.addConst();
2890 if (VolatileArg)
2891 ArgType.addVolatile();
2892
2893 // This isn't /really/ specified by the standard, but it's implied
2894 // we should be working from an RValue in the case of move to ensure
2895 // that we prefer to bind to rvalue references, and an LValue in the
2896 // case of copy to ensure we don't bind to rvalue references.
2897 // Possibly an XValue is actually correct in the case of move, but
2898 // there is no semantic difference for class types in this restricted
2899 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002900 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002901 VK = VK_LValue;
2902 else
2903 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002904 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002905
Richard Smith83c478d2012-04-20 18:46:14 +00002906 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2907
2908 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002909 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002910 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002911 }
2912
2913 // Create the object argument
2914 QualType ThisTy = CanTy;
2915 if (ConstThis)
2916 ThisTy.addConst();
2917 if (VolatileThis)
2918 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002919 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002920 OpaqueValueExpr(SourceLocation(), ThisTy,
2921 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002922
2923 // Now we perform lookup on the name we computed earlier and do overload
2924 // resolution. Lookup is only performed directly into the class since there
2925 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002926 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002927 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002928
2929 if (R.empty()) {
2930 // We might have no default constructor because we have a lambda's closure
2931 // type, rather than because there's some other declared constructor.
2932 // Every class has a copy/move constructor, copy/move assignment, and
2933 // destructor.
2934 assert(SM == CXXDefaultConstructor &&
2935 "lookup for a constructor or assignment operator was empty");
2936 Result->setMethod(nullptr);
2937 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2938 return Result;
2939 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002940
2941 // Copy the candidates as our processing of them may load new declarations
2942 // from an external source and invalidate lookup_result.
2943 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2944
Richard Smith5179eb72016-06-28 19:03:57 +00002945 for (NamedDecl *CandDecl : Candidates) {
2946 if (CandDecl->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002947 continue;
2948
Richard Smith5179eb72016-06-28 19:03:57 +00002949 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
2950 auto CtorInfo = getConstructorInfo(Cand);
2951 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002952 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Richard Smith5179eb72016-06-28 19:03:57 +00002953 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
2954 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2955 else if (CtorInfo)
2956 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002957 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002958 else
Richard Smith5179eb72016-06-28 19:03:57 +00002959 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
2960 true);
2961 } else if (FunctionTemplateDecl *Tmpl =
2962 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
2963 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2964 AddMethodTemplateCandidate(
2965 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
2966 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2967 else if (CtorInfo)
2968 AddTemplateOverloadCandidate(
2969 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
2970 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2971 else
2972 AddTemplateOverloadCandidate(
2973 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002974 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00002975 assert(isa<UsingDecl>(Cand.getDecl()) &&
2976 "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002977 }
2978 }
2979
2980 OverloadCandidateSet::iterator Best;
2981 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2982 case OR_Success:
2983 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002984 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002985 break;
2986
2987 case OR_Deleted:
2988 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002989 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002990 break;
2991
2992 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002993 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002994 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2995 break;
2996
Alexis Hunteef8ee02011-06-10 03:50:41 +00002997 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002998 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002999 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003000 break;
3001 }
3002
3003 return Result;
3004}
3005
3006/// \brief Look up the default constructor for the given class.
3007CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003008 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00003009 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3010 false, false);
3011
3012 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003013}
3014
Alexis Hunt491ec602011-06-21 23:42:56 +00003015/// \brief Look up the copying constructor for the given class.
3016CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00003017 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003018 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3019 "non-const, non-volatile qualifiers for copy ctor arg");
3020 SpecialMemberOverloadResult *Result =
3021 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3022 Quals & Qualifiers::Volatile, false, false, false);
3023
Alexis Hunt899bd442011-06-10 04:44:37 +00003024 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
3025}
3026
Sebastian Redl22653ba2011-08-30 19:58:05 +00003027/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00003028CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3029 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003030 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003031 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3032 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003033
3034 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
3035}
3036
Douglas Gregor52b72822010-07-02 23:12:18 +00003037/// \brief Look up the constructors for the given class.
3038DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003039 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00003040 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00003041 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003042 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00003043 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003044 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003045 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003046 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
Douglas Gregor52b72822010-07-02 23:12:18 +00003049 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3050 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3051 return Class->lookup(Name);
3052}
3053
Alexis Hunt491ec602011-06-21 23:42:56 +00003054/// \brief Look up the copying assignment operator for the given class.
3055CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3056 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003057 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003058 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3059 "non-const, non-volatile qualifiers for copy assignment arg");
3060 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3061 "non-const, non-volatile qualifiers for copy assignment this");
3062 SpecialMemberOverloadResult *Result =
3063 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3064 Quals & Qualifiers::Volatile, RValueThis,
3065 ThisQuals & Qualifiers::Const,
3066 ThisQuals & Qualifiers::Volatile);
3067
Alexis Hunt491ec602011-06-21 23:42:56 +00003068 return Result->getMethod();
3069}
3070
Sebastian Redl22653ba2011-08-30 19:58:05 +00003071/// \brief Look up the moving assignment operator for the given class.
3072CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003073 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003074 bool RValueThis,
3075 unsigned ThisQuals) {
3076 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3077 "non-const, non-volatile qualifiers for copy assignment this");
3078 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003079 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3080 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003081 ThisQuals & Qualifiers::Const,
3082 ThisQuals & Qualifiers::Volatile);
3083
3084 return Result->getMethod();
3085}
3086
Douglas Gregore71edda2010-07-01 22:47:18 +00003087/// \brief Look for the destructor of the given class.
3088///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003089/// During semantic analysis, this routine should be used in lieu of
3090/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003091///
3092/// \returns The destructor for this class.
3093CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003094 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3095 false, false, false,
3096 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003097}
3098
Richard Smithbcc22fc2012-03-09 08:00:36 +00003099/// LookupLiteralOperator - Determine which literal operator should be used for
3100/// a user-defined literal, per C++11 [lex.ext].
3101///
3102/// Normal overload resolution is not used to select which literal operator to
3103/// call for a user-defined literal. Look up the provided literal operator name,
3104/// and filter the results to the appropriate set for the given argument types.
3105Sema::LiteralOperatorLookupResult
3106Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3107 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003108 bool AllowRaw, bool AllowTemplate,
3109 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003110 LookupName(R, S);
3111 assert(R.getResultKind() != LookupResult::Ambiguous &&
3112 "literal operator lookup can't be ambiguous");
3113
3114 // Filter the lookup results appropriately.
3115 LookupResult::Filter F = R.makeFilter();
3116
Richard Smithbcc22fc2012-03-09 08:00:36 +00003117 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003118 bool FoundTemplate = false;
3119 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003120 bool FoundExactMatch = false;
3121
3122 while (F.hasNext()) {
3123 Decl *D = F.next();
3124 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3125 D = USD->getTargetDecl();
3126
Douglas Gregorc1970572013-04-10 05:18:00 +00003127 // If the declaration we found is invalid, skip it.
3128 if (D->isInvalidDecl()) {
3129 F.erase();
3130 continue;
3131 }
3132
Richard Smithb8b41d32013-10-07 19:57:58 +00003133 bool IsRaw = false;
3134 bool IsTemplate = false;
3135 bool IsStringTemplate = false;
3136 bool IsExactMatch = false;
3137
Richard Smithbcc22fc2012-03-09 08:00:36 +00003138 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3139 if (FD->getNumParams() == 1 &&
3140 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3141 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003142 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003143 IsExactMatch = true;
3144 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3145 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3146 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3147 IsExactMatch = false;
3148 break;
3149 }
3150 }
3151 }
3152 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003153 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3154 TemplateParameterList *Params = FD->getTemplateParameters();
3155 if (Params->size() == 1)
3156 IsTemplate = true;
3157 else
3158 IsStringTemplate = true;
3159 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003160
3161 if (IsExactMatch) {
3162 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003163 AllowRaw = false;
3164 AllowTemplate = false;
3165 AllowStringTemplate = false;
3166 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003167 // Go through again and remove the raw and template decls we've
3168 // already found.
3169 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003170 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003171 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003172 } else if (AllowRaw && IsRaw) {
3173 FoundRaw = true;
3174 } else if (AllowTemplate && IsTemplate) {
3175 FoundTemplate = true;
3176 } else if (AllowStringTemplate && IsStringTemplate) {
3177 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003178 } else {
3179 F.erase();
3180 }
3181 }
3182
3183 F.done();
3184
3185 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3186 // parameter type, that is used in preference to a raw literal operator
3187 // or literal operator template.
3188 if (FoundExactMatch)
3189 return LOLR_Cooked;
3190
3191 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3192 // operator template, but not both.
3193 if (FoundRaw && FoundTemplate) {
3194 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003195 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Richard Smithc2bebe92016-05-11 20:37:46 +00003196 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003197 return LOLR_Error;
3198 }
3199
3200 if (FoundRaw)
3201 return LOLR_Raw;
3202
3203 if (FoundTemplate)
3204 return LOLR_Template;
3205
Richard Smithb8b41d32013-10-07 19:57:58 +00003206 if (FoundStringTemplate)
3207 return LOLR_StringTemplate;
3208
Richard Smithbcc22fc2012-03-09 08:00:36 +00003209 // Didn't find anything we could use.
3210 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3211 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00003212 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3213 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003214 return LOLR_Error;
3215}
3216
John McCall8fe68082010-01-26 07:16:45 +00003217void ADLResult::insert(NamedDecl *New) {
3218 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3219
3220 // If we haven't yet seen a decl for this key, or the last decl
3221 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003222 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003223 Old = New;
3224 return;
3225 }
3226
3227 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003228 FunctionDecl *OldFD = Old->getAsFunction();
3229 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003230
3231 FunctionDecl *Cursor = NewFD;
3232 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003233 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003234
3235 // If we got to the end without finding OldFD, OldFD is the newer
3236 // declaration; leave things as they are.
3237 if (!Cursor) return;
3238
3239 // If we do find OldFD, then NewFD is newer.
3240 if (Cursor == OldFD) break;
3241
3242 // Otherwise, keep looking.
3243 }
3244
3245 Old = New;
3246}
3247
Richard Smith100b24a2014-04-17 01:52:14 +00003248void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3249 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003250 // Find all of the associated namespaces and classes based on the
3251 // arguments we have.
3252 AssociatedNamespaceSet AssociatedNamespaces;
3253 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003254 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003255 AssociatedNamespaces,
3256 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003257
3258 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003259 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3260 // and let Y be the lookup set produced by argument dependent
3261 // lookup (defined as follows). If X contains [...] then Y is
3262 // empty. Otherwise Y is the set of declarations found in the
3263 // namespaces associated with the argument types as described
3264 // below. The set of declarations found by the lookup of the name
3265 // is the union of X and Y.
3266 //
3267 // Here, we compute Y and add its members to the overloaded
3268 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003269 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003270 // When considering an associated namespace, the lookup is the
3271 // same as the lookup performed when the associated namespace is
3272 // used as a qualifier (3.4.3.2) except that:
3273 //
3274 // -- Any using-directives in the associated namespace are
3275 // ignored.
3276 //
John McCallc7e8e792009-08-07 22:18:02 +00003277 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003278 // associated classes are visible within their respective
3279 // namespaces even if they are not visible during an ordinary
3280 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003281 DeclContext::lookup_result R = NS->lookup(Name);
3282 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003283 // If the only declaration here is an ordinary friend, consider
3284 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003285 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3286 // If it's neither ordinarily visible nor a friend, we can't find it.
3287 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3288 continue;
3289
Richard Smith64017682013-07-17 23:53:16 +00003290 bool DeclaredInAssociatedClass = false;
3291 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3292 DeclContext *LexDC = DI->getLexicalDeclContext();
3293 if (isa<CXXRecordDecl>(LexDC) &&
Richard Smith82b8d4e2015-12-18 22:19:11 +00003294 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3295 isVisible(cast<NamedDecl>(DI))) {
Richard Smith64017682013-07-17 23:53:16 +00003296 DeclaredInAssociatedClass = true;
3297 break;
3298 }
3299 }
3300 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003301 continue;
3302 }
Mike Stump11289f42009-09-09 15:08:12 +00003303
John McCall91f61fc2010-01-26 06:04:06 +00003304 if (isa<UsingShadowDecl>(D))
3305 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003306
Richard Smith100b24a2014-04-17 01:52:14 +00003307 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003308 continue;
3309
Richard Smitha1431072015-06-12 01:32:13 +00003310 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3311 continue;
3312
John McCall8fe68082010-01-26 07:16:45 +00003313 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003314 }
3315 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003316}
Douglas Gregor2d435302009-12-30 17:04:44 +00003317
3318//----------------------------------------------------------------------------
3319// Search for all visible declarations.
3320//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003321VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003322
Richard Smithe156254d2013-08-20 20:35:18 +00003323bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3324
Douglas Gregor2d435302009-12-30 17:04:44 +00003325namespace {
3326
3327class ShadowContextRAII;
3328
3329class VisibleDeclsRecord {
3330public:
3331 /// \brief An entry in the shadow map, which is optimized to store a
3332 /// single declaration (the common case) but can also store a list
3333 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003334 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003335
3336private:
3337 /// \brief A mapping from declaration names to the declarations that have
3338 /// this name within a particular scope.
3339 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3340
3341 /// \brief A list of shadow maps, which is used to model name hiding.
3342 std::list<ShadowMap> ShadowMaps;
3343
3344 /// \brief The declaration contexts we have already visited.
3345 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3346
3347 friend class ShadowContextRAII;
3348
3349public:
3350 /// \brief Determine whether we have already visited this context
3351 /// (and, if not, note that we are going to visit that context now).
3352 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003353 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003354 }
3355
Douglas Gregor39982192010-08-15 06:18:01 +00003356 bool alreadyVisitedContext(DeclContext *Ctx) {
3357 return VisitedContexts.count(Ctx);
3358 }
3359
Douglas Gregor2d435302009-12-30 17:04:44 +00003360 /// \brief Determine whether the given declaration is hidden in the
3361 /// current scope.
3362 ///
3363 /// \returns the declaration that hides the given declaration, or
3364 /// NULL if no such declaration exists.
3365 NamedDecl *checkHidden(NamedDecl *ND);
3366
3367 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003368 void add(NamedDecl *ND) {
3369 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3370 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003371};
3372
3373/// \brief RAII object that records when we've entered a shadow context.
3374class ShadowContextRAII {
3375 VisibleDeclsRecord &Visible;
3376
3377 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3378
3379public:
3380 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003381 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003382 }
3383
3384 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003385 Visible.ShadowMaps.pop_back();
3386 }
3387};
3388
3389} // end anonymous namespace
3390
Douglas Gregor2d435302009-12-30 17:04:44 +00003391NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3392 unsigned IDNS = ND->getIdentifierNamespace();
3393 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3394 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3395 SM != SMEnd; ++SM) {
3396 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3397 if (Pos == SM->end())
3398 continue;
3399
Aaron Ballman1e606f42014-07-15 22:03:49 +00003400 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003401 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003402 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003404 Decl::IDNS_ObjCProtocol)))
3405 continue;
3406
3407 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003408 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003409 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003410 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003411 continue;
3412
Douglas Gregor09bbc652010-01-14 15:47:35 +00003413 // Functions and function templates in the same scope overload
3414 // rather than hide. FIXME: Look for hiding based on function
3415 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003416 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003417 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003418 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003419 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor2d435302009-12-30 17:04:44 +00003421 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003422 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003423 }
3424 }
3425
Craig Topperc3ec1492014-05-26 06:22:03 +00003426 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003427}
3428
3429static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3430 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003431 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003432 VisibleDeclConsumer &Consumer,
3433 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003434 if (!Ctx)
3435 return;
3436
Douglas Gregor2d435302009-12-30 17:04:44 +00003437 // Make sure we don't visit the same context twice.
3438 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3439 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440
Richard Smith9e2341d2015-03-23 03:25:59 +00003441 // Outside C++, lookup results for the TU live on identifiers.
3442 if (isa<TranslationUnitDecl>(Ctx) &&
3443 !Result.getSema().getLangOpts().CPlusPlus) {
3444 auto &S = Result.getSema();
3445 auto &Idents = S.Context.Idents;
3446
3447 // Ensure all external identifiers are in the identifier table.
3448 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3449 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3450 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3451 Idents.get(Name);
3452 }
3453
3454 // Walk all lookup results in the TU for each identifier.
3455 for (const auto &Ident : Idents) {
3456 for (auto I = S.IdResolver.begin(Ident.getValue()),
3457 E = S.IdResolver.end();
3458 I != E; ++I) {
3459 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3460 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3461 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3462 Visited.add(ND);
3463 }
3464 }
3465 }
3466 }
3467
3468 return;
3469 }
3470
Douglas Gregor7454c562010-07-02 20:37:36 +00003471 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3472 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3473
Douglas Gregor2d435302009-12-30 17:04:44 +00003474 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003475 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003476 for (auto *D : R) {
3477 if (auto *ND = Result.getAcceptableDecl(D)) {
3478 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3479 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003480 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003481 }
3482 }
3483
3484 // Traverse using directives for qualified name lookup.
3485 if (QualifiedNameLookup) {
3486 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003487 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003488 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003489 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003490 }
3491 }
3492
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003493 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003494 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003495 if (!Record->hasDefinition())
3496 return;
3497
Aaron Ballman574705e2014-03-13 15:41:46 +00003498 for (const auto &B : Record->bases()) {
3499 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500
Douglas Gregor2d435302009-12-30 17:04:44 +00003501 // Don't look into dependent bases, because name lookup can't look
3502 // there anyway.
3503 if (BaseType->isDependentType())
3504 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505
Douglas Gregor2d435302009-12-30 17:04:44 +00003506 const RecordType *Record = BaseType->getAs<RecordType>();
3507 if (!Record)
3508 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509
Douglas Gregor2d435302009-12-30 17:04:44 +00003510 // FIXME: It would be nice to be able to determine whether referencing
3511 // a particular member would be ambiguous. For example, given
3512 //
3513 // struct A { int member; };
3514 // struct B { int member; };
3515 // struct C : A, B { };
3516 //
3517 // void f(C *c) { c->### }
3518 //
3519 // accessing 'member' would result in an ambiguity. However, we
3520 // could be smart enough to qualify the member with the base
3521 // class, e.g.,
3522 //
3523 // c->B::member
3524 //
3525 // or
3526 //
3527 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
Douglas Gregor2d435302009-12-30 17:04:44 +00003529 // Find results in this base class (and its bases).
3530 ShadowContextRAII Shadow(Visited);
3531 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003532 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003533 }
3534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003536 // Traverse the contexts of Objective-C classes.
3537 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3538 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003539 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003540 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003541 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003542 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003543 }
3544
3545 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003546 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003547 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003548 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003549 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003550 }
3551
3552 // Traverse the superclass.
3553 if (IFace->getSuperClass()) {
3554 ShadowContextRAII Shadow(Visited);
3555 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003556 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Douglas Gregor0b59e802010-04-19 18:02:19 +00003559 // If there is an implementation, traverse it. We do this to find
3560 // synthesized ivars.
3561 if (IFace->getImplementation()) {
3562 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003564 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003565 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003566 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003567 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003568 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003569 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003570 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003571 }
3572 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003573 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003574 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003575 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003576 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003578
Douglas Gregor0b59e802010-04-19 18:02:19 +00003579 // If there is an implementation, traverse it.
3580 if (Category->getImplementation()) {
3581 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003583 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003585 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003586}
3587
3588static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3589 UnqualUsingDirectiveSet &UDirs,
3590 VisibleDeclConsumer &Consumer,
3591 VisibleDeclsRecord &Visited) {
3592 if (!S)
3593 return;
3594
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595 if (!S->getEntity() ||
3596 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003597 !Visited.alreadyVisitedContext(S->getEntity())) ||
3598 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003599 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003600 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003601 for (auto *D : S->decls()) {
3602 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003603 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003604 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003605 Visited.add(ND);
3606 }
3607 }
3608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregor66230062010-03-15 14:33:29 +00003610 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003611 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003612 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003613 // Look into this scope's declaration context, along with any of its
3614 // parent lookup contexts (e.g., enclosing classes), up to the point
3615 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003616 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003617 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618
Douglas Gregorea166062010-03-15 15:26:48 +00003619 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003620 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003621 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3622 if (Method->isInstanceMethod()) {
3623 // For instance methods, look for ivars in the method's interface.
3624 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3625 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003626 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003628 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003629 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003630 }
3631
3632 // We've already performed all of the name lookup that we need
3633 // to for Objective-C methods; the next context will be the
3634 // outer scope.
3635 break;
3636 }
3637
Douglas Gregor2d435302009-12-30 17:04:44 +00003638 if (Ctx->isFunctionOrMethod())
3639 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
3641 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003642 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003643 }
3644 } else if (!S->getParent()) {
3645 // Look into the translation unit scope. We walk through the translation
3646 // unit's declaration context, because the Scope itself won't have all of
3647 // the declarations if we loaded a precompiled header.
3648 // FIXME: We would like the translation unit's Scope object to point to the
3649 // translation unit, so we don't need this special "if" branch. However,
3650 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003652 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003653 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003654 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003656 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657 }
3658
Douglas Gregor2d435302009-12-30 17:04:44 +00003659 if (Entity) {
3660 // Lookup visible declarations in any namespaces found by using
3661 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003662 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3663 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003665 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003666 }
3667
3668 // Lookup names in the parent scope.
3669 ShadowContextRAII Shadow(Visited);
3670 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3671}
3672
3673void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003674 VisibleDeclConsumer &Consumer,
3675 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003676 // Determine the set of using directives available during
3677 // unqualified name lookup.
3678 Scope *Initial = S;
3679 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003680 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003681 // Find the first namespace or translation-unit scope.
3682 while (S && !isNamespaceOrTranslationUnitScope(S))
3683 S = S->getParent();
3684
3685 UDirs.visitScopeChain(Initial, S);
3686 }
3687 UDirs.done();
3688
3689 // Look for visible declarations.
3690 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003691 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003692 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003693 if (!IncludeGlobalScope)
3694 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003695 ShadowContextRAII Shadow(Visited);
3696 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3697}
3698
3699void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003700 VisibleDeclConsumer &Consumer,
3701 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003702 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003703 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003704 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003705 if (!IncludeGlobalScope)
3706 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003707 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003709 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003710}
3711
Chris Lattner43e7f312011-02-18 02:08:43 +00003712/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003713/// If GnuLabelLoc is a valid source location, then this is a definition
3714/// of an __label__ label name, otherwise it is a normal label definition
3715/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003716LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003717 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003718 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003719 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003720
3721 if (GnuLabelLoc.isValid()) {
3722 // Local label definitions always shadow existing labels.
3723 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3724 Scope *S = CurScope;
3725 PushOnScopeChains(Res, S, true);
3726 return cast<LabelDecl>(Res);
3727 }
3728
3729 // Not a GNU local label.
3730 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3731 // If we found a label, check to see if it is in the same context as us.
3732 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003733 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003734 Res = nullptr;
3735 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003736 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003737 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3738 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003739 assert(S && "Not in a function?");
3740 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003741 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003742 return cast<LabelDecl>(Res);
3743}
3744
3745//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003746// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003747//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003748
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003749static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3750 TypoCorrection &Candidate) {
3751 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3752 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3753}
3754
3755static void LookupPotentialTypoResult(Sema &SemaRef,
3756 LookupResult &Res,
3757 IdentifierInfo *Name,
3758 Scope *S, CXXScopeSpec *SS,
3759 DeclContext *MemberContext,
3760 bool EnteringContext,
3761 bool isObjCIvarLookup,
3762 bool FindHidden);
3763
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003764/// \brief Check whether the declarations found for a typo correction are
3765/// visible, and if none of them are, convert the correction to an 'import
3766/// a module' correction.
3767static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3768 if (TC.begin() == TC.end())
3769 return;
3770
3771 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3772
3773 for (/**/; DI != DE; ++DI)
3774 if (!LookupResult::isVisible(SemaRef, *DI))
3775 break;
3776 // Nothing to do if all decls are visible.
3777 if (DI == DE)
3778 return;
3779
3780 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3781 bool AnyVisibleDecls = !NewDecls.empty();
3782
3783 for (/**/; DI != DE; ++DI) {
3784 NamedDecl *VisibleDecl = *DI;
3785 if (!LookupResult::isVisible(SemaRef, *DI))
3786 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3787
3788 if (VisibleDecl) {
3789 if (!AnyVisibleDecls) {
3790 // Found a visible decl, discard all hidden ones.
3791 AnyVisibleDecls = true;
3792 NewDecls.clear();
3793 }
3794 NewDecls.push_back(VisibleDecl);
3795 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3796 NewDecls.push_back(*DI);
3797 }
3798
3799 if (NewDecls.empty())
3800 TC = TypoCorrection();
3801 else {
3802 TC.setCorrectionDecls(NewDecls);
3803 TC.setRequiresImport(!AnyVisibleDecls);
3804 }
3805}
3806
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003807// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3808// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3809// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3810static void getNestedNameSpecifierIdentifiers(
3811 NestedNameSpecifier *NNS,
3812 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3813 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3814 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3815 else
3816 Identifiers.clear();
3817
3818 const IdentifierInfo *II = nullptr;
3819
3820 switch (NNS->getKind()) {
3821 case NestedNameSpecifier::Identifier:
3822 II = NNS->getAsIdentifier();
3823 break;
3824
3825 case NestedNameSpecifier::Namespace:
3826 if (NNS->getAsNamespace()->isAnonymousNamespace())
3827 return;
3828 II = NNS->getAsNamespace()->getIdentifier();
3829 break;
3830
3831 case NestedNameSpecifier::NamespaceAlias:
3832 II = NNS->getAsNamespaceAlias()->getIdentifier();
3833 break;
3834
3835 case NestedNameSpecifier::TypeSpecWithTemplate:
3836 case NestedNameSpecifier::TypeSpec:
3837 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3838 break;
3839
3840 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003841 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003842 return;
3843 }
3844
3845 if (II)
3846 Identifiers.push_back(II);
3847}
3848
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003850 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003851 // Don't consider hidden names for typo correction.
3852 if (Hiding)
3853 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854
Douglas Gregor2d435302009-12-30 17:04:44 +00003855 // Only consider entities with identifiers for names, ignoring
3856 // special names (constructors, overloaded operators, selectors,
3857 // etc.).
3858 IdentifierInfo *Name = ND->getIdentifier();
3859 if (!Name)
3860 return;
3861
Richard Smithe156254d2013-08-20 20:35:18 +00003862 // Only consider visible declarations and declarations from modules with
3863 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003864 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003865 !findAcceptableDecl(SemaRef, ND))
3866 return;
3867
Douglas Gregor57756ea2010-10-14 22:11:03 +00003868 FoundName(Name->getName());
3869}
3870
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003871void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003872 // Compute the edit distance between the typo and the name of this
3873 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003874 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003875}
3876
3877void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3878 // Compute the edit distance between the typo and this keyword,
3879 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003880 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003881}
3882
3883void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3884 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003885 // Use a simple length-based heuristic to determine the minimum possible
3886 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003887 StringRef TypoStr = Typo->getName();
3888 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3889 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003890 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003892 // Compute an upper bound on the allowable edit distance, so that the
3893 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003894 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3895 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003896 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003898 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003899 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003900 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003901 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003902}
3903
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003904static const unsigned MaxTypoDistanceResultSets = 5;
3905
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003906void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003907 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003908 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003909
3910 // For very short typos, ignore potential corrections that have a different
3911 // base identifier from the typo or which have a normalized edit distance
3912 // longer than the typo itself.
3913 if (TypoStr.size() < 3 &&
3914 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3915 return;
3916
3917 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003918 if (Correction.isResolved()) {
3919 checkCorrectionVisibility(SemaRef, Correction);
3920 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3921 return;
3922 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003923
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003924 TypoResultList &CList =
3925 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003926
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003927 if (!CList.empty() && !CList.back().isResolved())
3928 CList.pop_back();
3929 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3930 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3931 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3932 RI != RIEnd; ++RI) {
3933 // If the Correction refers to a decl already in the result list,
3934 // replace the existing result if the string representation of Correction
3935 // comes before the current result alphabetically, then stop as there is
3936 // nothing more to be done to add Correction to the candidate set.
3937 if (RI->getCorrectionDecl() == NewND) {
3938 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3939 *RI = Correction;
3940 return;
3941 }
3942 }
3943 }
3944 if (CList.empty() || Correction.isResolved())
3945 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003946
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003947 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003948 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3949}
3950
3951void TypoCorrectionConsumer::addNamespaces(
3952 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3953 SearchNamespaces = true;
3954
3955 for (auto KNPair : KnownNamespaces)
3956 Namespaces.addNameSpecifier(KNPair.first);
3957
3958 bool SSIsTemplate = false;
3959 if (NestedNameSpecifier *NNS =
3960 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3961 if (const Type *T = NNS->getAsType())
3962 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3963 }
Richard Smith2a40fb72015-11-18 01:19:02 +00003964 // Do not transform this into an iterator-based loop. The loop body can
3965 // trigger the creation of further types (through lazy deserialization) and
3966 // invalide iterators into this list.
3967 auto &Types = SemaRef.getASTContext().getTypes();
3968 for (unsigned I = 0; I != Types.size(); ++I) {
3969 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003970 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3971 CD = CD->getCanonicalDecl();
3972 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3973 !CD->isUnion() && CD->getIdentifier() &&
3974 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3975 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3976 Namespaces.addNameSpecifier(CD);
3977 }
3978 }
3979}
3980
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003981const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3982 if (++CurrentTCIndex < ValidatedCorrections.size())
3983 return ValidatedCorrections[CurrentTCIndex];
3984
3985 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003986 while (!CorrectionResults.empty()) {
3987 auto DI = CorrectionResults.begin();
3988 if (DI->second.empty()) {
3989 CorrectionResults.erase(DI);
3990 continue;
3991 }
3992
3993 auto RI = DI->second.begin();
3994 if (RI->second.empty()) {
3995 DI->second.erase(RI);
3996 performQualifiedLookups();
3997 continue;
3998 }
3999
4000 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004001 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004002 ValidatedCorrections.push_back(TC);
4003 return ValidatedCorrections[CurrentTCIndex];
4004 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004005 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004006 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004007}
4008
4009bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4010 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4011 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004012 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004013retry_lookup:
4014 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4015 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004016 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004017 Name == Typo && !Candidate.WillReplaceSpecifier());
4018 switch (Result.getResultKind()) {
4019 case LookupResult::NotFound:
4020 case LookupResult::NotFoundInCurrentInstantiation:
4021 case LookupResult::FoundUnresolvedValue:
4022 if (TempSS) {
4023 // Immediately retry the lookup without the given CXXScopeSpec
4024 TempSS = nullptr;
4025 Candidate.WillReplaceSpecifier(true);
4026 goto retry_lookup;
4027 }
4028 if (TempMemberContext) {
4029 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004030 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004031 TempMemberContext = nullptr;
4032 goto retry_lookup;
4033 }
4034 if (SearchNamespaces)
4035 QualifiedResults.push_back(Candidate);
4036 break;
4037
4038 case LookupResult::Ambiguous:
4039 // We don't deal with ambiguities.
4040 break;
4041
4042 case LookupResult::Found:
4043 case LookupResult::FoundOverloaded:
4044 // Store all of the Decls for overloaded symbols
4045 for (auto *TRD : Result)
4046 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004047 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004048 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004049 if (SearchNamespaces)
4050 QualifiedResults.push_back(Candidate);
4051 break;
4052 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004053 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004054 return true;
4055 }
4056 return false;
4057}
4058
4059void TypoCorrectionConsumer::performQualifiedLookups() {
4060 unsigned TypoLen = Typo->getName().size();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00004061 for (const TypoCorrection &QR : QualifiedResults) {
4062 for (const auto &NSI : Namespaces) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004063 DeclContext *Ctx = NSI.DeclCtx;
4064 const Type *NSType = NSI.NameSpecifier->getAsType();
4065
4066 // If the current NestedNameSpecifier refers to a class and the
4067 // current correction candidate is the name of that class, then skip
4068 // it as it is unlikely a qualified version of the class' constructor
4069 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004070 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4071 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004072 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4073 continue;
4074 }
4075
4076 TypoCorrection TC(QR);
4077 TC.ClearCorrectionDecls();
4078 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4079 TC.setQualifierDistance(NSI.EditDistance);
4080 TC.setCallbackDistance(0); // Reset the callback distance
4081
4082 // If the current correction candidate and namespace combination are
4083 // too far away from the original typo based on the normalized edit
4084 // distance, then skip performing a qualified name lookup.
4085 unsigned TmpED = TC.getEditDistance(true);
4086 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4087 TypoLen / TmpED < 3)
4088 continue;
4089
4090 Result.clear();
4091 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4092 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4093 continue;
4094
4095 // Any corrections added below will be validated in subsequent
4096 // iterations of the main while() loop over the Consumer's contents.
4097 switch (Result.getResultKind()) {
4098 case LookupResult::Found:
4099 case LookupResult::FoundOverloaded: {
4100 if (SS && SS->isValid()) {
4101 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4102 std::string OldQualified;
4103 llvm::raw_string_ostream OldOStream(OldQualified);
4104 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4105 OldOStream << Typo->getName();
4106 // If correction candidate would be an identical written qualified
4107 // identifer, then the existing CXXScopeSpec probably included a
4108 // typedef that didn't get accounted for properly.
4109 if (OldOStream.str() == NewQualified)
4110 break;
4111 }
4112 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4113 TRD != TRDEnd; ++TRD) {
4114 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4115 NSType ? NSType->getAsCXXRecordDecl()
4116 : nullptr,
4117 TRD.getPair()) == Sema::AR_accessible)
4118 TC.addCorrectionDecl(*TRD);
4119 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004120 if (TC.isResolved()) {
4121 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004122 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004123 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004124 break;
4125 }
4126 case LookupResult::NotFound:
4127 case LookupResult::NotFoundInCurrentInstantiation:
4128 case LookupResult::Ambiguous:
4129 case LookupResult::FoundUnresolvedValue:
4130 break;
4131 }
4132 }
4133 }
4134 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004135}
4136
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004137TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4138 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004139 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004140 if (NestedNameSpecifier *NNS =
4141 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4142 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4143 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4144
4145 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4146 }
4147 // Build the list of identifiers that would be used for an absolute
4148 // (from the global context) NestedNameSpecifier referring to the current
4149 // context.
David Majnemerf7e36092016-06-23 00:15:04 +00004150 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4151 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004152 CurContextIdentifiers.push_back(ND->getIdentifier());
4153 }
4154
4155 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004156 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4157 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4158 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004159}
4160
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004161auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4162 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004163 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004164 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004165 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004166 DC = DC->getLookupParent()) {
4167 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4168 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4169 !(ND && ND->isAnonymousNamespace()))
4170 Chain.push_back(DC->getPrimaryContext());
4171 }
4172 return Chain;
4173}
4174
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004175unsigned
4176TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4177 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004178 unsigned NumSpecifiers = 0;
David Majnemerf7e36092016-06-23 00:15:04 +00004179 for (DeclContext *C : llvm::reverse(DeclChain)) {
4180 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004181 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4182 ++NumSpecifiers;
David Majnemerf7e36092016-06-23 00:15:04 +00004183 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004184 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4185 RD->getTypeForDecl());
4186 ++NumSpecifiers;
4187 }
4188 }
4189 return NumSpecifiers;
4190}
4191
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004192void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4193 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004194 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004195 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004196 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004197 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4198
4199 // Eliminate common elements from the two DeclContext chains.
David Majnemerf7e36092016-06-23 00:15:04 +00004200 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4201 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4202 break;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004203 NamespaceDeclChain.pop_back();
4204 }
4205
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004206 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004207 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004208
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004209 // Add an explicit leading '::' specifier if needed.
4210 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004211 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004212 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004213 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004214 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004215 } else if (NamedDecl *ND =
4216 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004217 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004218 bool SameNameSpecifier = false;
4219 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004220 CurNameSpecifierIdentifiers.end(),
4221 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004222 std::string NewNameSpecifier;
4223 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4224 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4225 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4226 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4227 SpecifierOStream.flush();
4228 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004229 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004230 if (SameNameSpecifier ||
4231 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4232 Name) != CurContextIdentifiers.end()) {
4233 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4234 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4235 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004236 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004237 }
4238 }
4239
4240 // If the built NestedNameSpecifier would be replacing an existing
4241 // NestedNameSpecifier, use the number of component identifiers that
4242 // would need to be changed as the edit distance instead of the number
4243 // of components in the built NestedNameSpecifier.
4244 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4245 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4246 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4247 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004248 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4249 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004250 }
4251
Hans Wennborg66010132014-06-11 21:24:13 +00004252 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4253 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004254}
4255
Douglas Gregord507d772010-10-20 03:06:34 +00004256/// \brief Perform name lookup for a possible result for typo correction.
4257static void LookupPotentialTypoResult(Sema &SemaRef,
4258 LookupResult &Res,
4259 IdentifierInfo *Name,
4260 Scope *S, CXXScopeSpec *SS,
4261 DeclContext *MemberContext,
4262 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004263 bool isObjCIvarLookup,
4264 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004265 Res.suppressDiagnostics();
4266 Res.clear();
4267 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004268 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004270 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004271 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004272 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4273 Res.addDecl(Ivar);
4274 Res.resolveKind();
4275 return;
4276 }
4277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Manman Ren5b786402016-01-28 18:49:28 +00004279 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4280 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004281 Res.addDecl(Prop);
4282 Res.resolveKind();
4283 return;
4284 }
4285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286
Douglas Gregord507d772010-10-20 03:06:34 +00004287 SemaRef.LookupQualifiedName(Res, MemberContext);
4288 return;
4289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
4291 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004292 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
Douglas Gregord507d772010-10-20 03:06:34 +00004294 // Fake ivar lookup; this should really be part of
4295 // LookupParsedName.
4296 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4297 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004299 (Res.isSingleResult() &&
4300 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004302 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4303 Res.addDecl(IV);
4304 Res.resolveKind();
4305 }
4306 }
4307 }
4308}
4309
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004310/// \brief Add keywords to the consumer as possible typo corrections.
4311static void AddKeywordsToConsumer(Sema &SemaRef,
4312 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004313 Scope *S, CorrectionCandidateCallback &CCC,
4314 bool AfterNestedNameSpecifier) {
4315 if (AfterNestedNameSpecifier) {
4316 // For 'X::', we know exactly which keywords can appear next.
4317 Consumer.addKeywordResult("template");
4318 if (CCC.WantExpressionKeywords)
4319 Consumer.addKeywordResult("operator");
4320 return;
4321 }
4322
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004323 if (CCC.WantObjCSuper)
4324 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004325
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004326 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004327 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004328 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004329 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004330 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004331 "_Complex", "_Imaginary",
4332 // storage-specifiers as well
4333 "extern", "inline", "static", "typedef"
4334 };
4335
Craig Toppere5ce8312013-07-15 03:38:40 +00004336 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004337 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4338 Consumer.addKeywordResult(CTypeSpecs[I]);
4339
David Blaikiebbafb8a2012-03-11 07:00:24 +00004340 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004341 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004342 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004343 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004344 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004345 Consumer.addKeywordResult("_Bool");
4346
David Blaikiebbafb8a2012-03-11 07:00:24 +00004347 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004348 Consumer.addKeywordResult("class");
4349 Consumer.addKeywordResult("typename");
4350 Consumer.addKeywordResult("wchar_t");
4351
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004352 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004353 Consumer.addKeywordResult("char16_t");
4354 Consumer.addKeywordResult("char32_t");
4355 Consumer.addKeywordResult("constexpr");
4356 Consumer.addKeywordResult("decltype");
4357 Consumer.addKeywordResult("thread_local");
4358 }
4359 }
4360
David Blaikiebbafb8a2012-03-11 07:00:24 +00004361 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004362 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004363 } else if (CCC.WantFunctionLikeCasts) {
4364 static const char *const CastableTypeSpecs[] = {
4365 "char", "double", "float", "int", "long", "short",
4366 "signed", "unsigned", "void"
4367 };
4368 for (auto *kw : CastableTypeSpecs)
4369 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004370 }
4371
David Blaikiebbafb8a2012-03-11 07:00:24 +00004372 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004373 Consumer.addKeywordResult("const_cast");
4374 Consumer.addKeywordResult("dynamic_cast");
4375 Consumer.addKeywordResult("reinterpret_cast");
4376 Consumer.addKeywordResult("static_cast");
4377 }
4378
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004379 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004380 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004381 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004382 Consumer.addKeywordResult("false");
4383 Consumer.addKeywordResult("true");
4384 }
4385
David Blaikiebbafb8a2012-03-11 07:00:24 +00004386 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004387 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004388 "delete", "new", "operator", "throw", "typeid"
4389 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004390 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004391 for (unsigned I = 0; I != NumCXXExprs; ++I)
4392 Consumer.addKeywordResult(CXXExprs[I]);
4393
4394 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4395 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4396 Consumer.addKeywordResult("this");
4397
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004398 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004399 Consumer.addKeywordResult("alignof");
4400 Consumer.addKeywordResult("nullptr");
4401 }
4402 }
Jordan Rose58d54722012-06-30 21:33:57 +00004403
4404 if (SemaRef.getLangOpts().C11) {
4405 // FIXME: We should not suggest _Alignof if the alignof macro
4406 // is present.
4407 Consumer.addKeywordResult("_Alignof");
4408 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004409 }
4410
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004411 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004412 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4413 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004414 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004415 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004416 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004417 for (unsigned I = 0; I != NumCStmts; ++I)
4418 Consumer.addKeywordResult(CStmts[I]);
4419
David Blaikiebbafb8a2012-03-11 07:00:24 +00004420 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004421 Consumer.addKeywordResult("catch");
4422 Consumer.addKeywordResult("try");
4423 }
4424
4425 if (S && S->getBreakParent())
4426 Consumer.addKeywordResult("break");
4427
4428 if (S && S->getContinueParent())
4429 Consumer.addKeywordResult("continue");
4430
4431 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4432 Consumer.addKeywordResult("case");
4433 Consumer.addKeywordResult("default");
4434 }
4435 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004436 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004437 Consumer.addKeywordResult("namespace");
4438 Consumer.addKeywordResult("template");
4439 }
4440
4441 if (S && S->isClassScope()) {
4442 Consumer.addKeywordResult("explicit");
4443 Consumer.addKeywordResult("friend");
4444 Consumer.addKeywordResult("mutable");
4445 Consumer.addKeywordResult("private");
4446 Consumer.addKeywordResult("protected");
4447 Consumer.addKeywordResult("public");
4448 Consumer.addKeywordResult("virtual");
4449 }
4450 }
4451
David Blaikiebbafb8a2012-03-11 07:00:24 +00004452 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004453 Consumer.addKeywordResult("using");
4454
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004455 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004456 Consumer.addKeywordResult("static_assert");
4457 }
4458 }
4459}
4460
Kaelyn Takata6c759512014-10-27 18:07:37 +00004461std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4462 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4463 Scope *S, CXXScopeSpec *SS,
4464 std::unique_ptr<CorrectionCandidateCallback> CCC,
4465 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004466 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004467
4468 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4469 DisableTypoCorrection)
4470 return nullptr;
4471
4472 // In Microsoft mode, don't perform typo correction in a template member
4473 // function dependent context because it interferes with the "lookup into
4474 // dependent bases of class templates" feature.
4475 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4476 isa<CXXMethodDecl>(CurContext))
4477 return nullptr;
4478
4479 // We only attempt to correct typos for identifiers.
4480 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4481 if (!Typo)
4482 return nullptr;
4483
4484 // If the scope specifier itself was invalid, don't try to correct
4485 // typos.
4486 if (SS && SS->isInvalid())
4487 return nullptr;
4488
4489 // Never try to correct typos during template deduction or
4490 // instantiation.
4491 if (!ActiveTemplateInstantiations.empty())
4492 return nullptr;
4493
4494 // Don't try to correct 'super'.
4495 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4496 return nullptr;
4497
4498 // Abort if typo correction already failed for this specific typo.
4499 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4500 if (locs != TypoCorrectionFailures.end() &&
4501 locs->second.count(TypoName.getLoc()))
4502 return nullptr;
4503
4504 // Don't try to correct the identifier "vector" when in AltiVec mode.
4505 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4506 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004507 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004508 return nullptr;
4509
Nick Lewycky24653262014-12-16 21:39:02 +00004510 // Provide a stop gap for files that are just seriously broken. Trying
4511 // to correct all typos can turn into a HUGE performance penalty, causing
4512 // some files to take minutes to get rejected by the parser.
4513 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4514 if (Limit && TyposCorrected >= Limit)
4515 return nullptr;
4516 ++TyposCorrected;
4517
Kaelyn Takata6c759512014-10-27 18:07:37 +00004518 // If we're handling a missing symbol error, using modules, and the
4519 // special search all modules option is used, look for a missing import.
4520 if (ErrorRecovery && getLangOpts().Modules &&
4521 getLangOpts().ModulesSearchAll) {
4522 // The following has the side effect of loading the missing module.
4523 getModuleLoader().lookupMissingImports(Typo->getName(),
4524 TypoName.getLocStart());
4525 }
4526
4527 CorrectionCandidateCallback &CCCRef = *CCC;
4528 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4529 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4530 EnteringContext);
4531
Kaelyn Takata6c759512014-10-27 18:07:37 +00004532 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004533 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004534 DeclContext *QualifiedDC = MemberContext;
4535 if (MemberContext) {
4536 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4537
4538 // Look in qualified interfaces.
4539 if (OPT) {
4540 for (auto *I : OPT->quals())
4541 LookupVisibleDecls(I, LookupKind, *Consumer);
4542 }
4543 } else if (SS && SS->isSet()) {
4544 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4545 if (!QualifiedDC)
4546 return nullptr;
4547
Kaelyn Takata6c759512014-10-27 18:07:37 +00004548 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4549 } else {
4550 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004551 }
4552
4553 // Determine whether we are going to search in the various namespaces for
4554 // corrections.
4555 bool SearchNamespaces
4556 = getLangOpts().CPlusPlus &&
4557 (IsUnqualifiedLookup || (SS && SS->isSet()));
4558
4559 if (IsUnqualifiedLookup || SearchNamespaces) {
4560 // For unqualified lookup, look through all of the names that we have
4561 // seen in this translation unit.
4562 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4563 for (const auto &I : Context.Idents)
4564 Consumer->FoundName(I.getKey());
4565
4566 // Walk through identifiers in external identifier sources.
4567 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4568 if (IdentifierInfoLookup *External
4569 = Context.Idents.getExternalIdentifierLookup()) {
4570 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4571 do {
4572 StringRef Name = Iter->Next();
4573 if (Name.empty())
4574 break;
4575
4576 Consumer->FoundName(Name);
4577 } while (true);
4578 }
4579 }
4580
4581 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4582
4583 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4584 // to search those namespaces.
4585 if (SearchNamespaces) {
4586 // Load any externally-known namespaces.
4587 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4588 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4589 LoadedExternalKnownNamespaces = true;
4590 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4591 for (auto *N : ExternalKnownNamespaces)
4592 KnownNamespaces[N] = true;
4593 }
4594
4595 Consumer->addNamespaces(KnownNamespaces);
4596 }
4597
4598 return Consumer;
4599}
4600
Douglas Gregor2d435302009-12-30 17:04:44 +00004601/// \brief Try to "correct" a typo in the source code by finding
4602/// visible declarations whose names are similar to the name that was
4603/// present in the source code.
4604///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004605/// \param TypoName the \c DeclarationNameInfo structure that contains
4606/// the name that was present in the source code along with its location.
4607///
4608/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004609///
4610/// \param S the scope in which name lookup occurs.
4611///
4612/// \param SS the nested-name-specifier that precedes the name we're
4613/// looking for, if present.
4614///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004615/// \param CCC A CorrectionCandidateCallback object that provides further
4616/// validation of typo correction candidates. It also provides flags for
4617/// determining the set of keywords permitted.
4618///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004619/// \param MemberContext if non-NULL, the context in which to look for
4620/// a member access expression.
4621///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004623/// the nested-name-specifier SS.
4624///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004625/// \param OPT when non-NULL, the search for visible declarations will
4626/// also walk the protocols in the qualified interfaces of \p OPT.
4627///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004628/// \returns a \c TypoCorrection containing the corrected name if the typo
4629/// along with information such as the \c NamedDecl where the corrected name
4630/// was declared, and any additional \c NestedNameSpecifier needed to access
4631/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4632TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4633 Sema::LookupNameKind LookupKind,
4634 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004635 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004636 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004637 DeclContext *MemberContext,
4638 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004639 const ObjCObjectPointerType *OPT,
4640 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004641 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4642
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004643 // Always let the ExternalSource have the first chance at correction, even
4644 // if we would otherwise have given up.
4645 if (ExternalSource) {
4646 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004647 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004648 return Correction;
4649 }
4650
Kaelyn Takata6c759512014-10-27 18:07:37 +00004651 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4652 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4653 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4654 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4655 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656
Kaelyn Takata6c759512014-10-27 18:07:37 +00004657 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004658 auto Consumer = makeTypoCorrectionConsumer(
4659 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004660 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004661
Kaelyn Takata6c759512014-10-27 18:07:37 +00004662 if (!Consumer)
4663 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004665 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004666 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004667 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004668
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004669 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4670 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004671 unsigned ED = Consumer->getBestEditDistance(true);
4672 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004673 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004674 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004675
Kaelyn Takata6c759512014-10-27 18:07:37 +00004676 TypoCorrection BestTC = Consumer->getNextCorrection();
4677 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004678 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004679 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004680
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004681 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004682
Kaelyn Takata6c759512014-10-27 18:07:37 +00004683 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004684 // If this was an unqualified lookup and we believe the callback
4685 // object wouldn't have filtered out possible corrections, note
4686 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004687 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004688 }
4689
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004690 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004691 if (!SecondBestTC ||
4692 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4693 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004694
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004695 // Don't correct to a keyword that's the same as the typo; the keyword
4696 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004697 if (ED == 0 && Result.isKeyword())
4698 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004699
David Blaikie04ea41c2012-10-12 20:00:44 +00004700 TypoCorrection TC = Result;
4701 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004702 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004703 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004704 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004705 // Prefer 'super' when we're completing in a message-receiver
4706 // context.
4707
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004708 if (BestTC.getCorrection().getAsString() != "super") {
4709 if (SecondBestTC.getCorrection().getAsString() == "super")
4710 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004711 else if ((*Consumer)["super"].front().isKeyword())
4712 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004713 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004714 // Don't correct to a keyword that's the same as the typo; the keyword
4715 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004716 if (BestTC.getEditDistance() == 0 ||
4717 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004718 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004720 BestTC.setCorrectionRange(SS, TypoName);
4721 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004724 // Record the failure's location if needed and return an empty correction. If
4725 // this was an unqualified lookup and we believe the callback object did not
4726 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004727 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004728}
4729
Kaelyn Takata6c759512014-10-27 18:07:37 +00004730/// \brief Try to "correct" a typo in the source code by finding
4731/// visible declarations whose names are similar to the name that was
4732/// present in the source code.
4733///
4734/// \param TypoName the \c DeclarationNameInfo structure that contains
4735/// the name that was present in the source code along with its location.
4736///
4737/// \param LookupKind the name-lookup criteria used to search for the name.
4738///
4739/// \param S the scope in which name lookup occurs.
4740///
4741/// \param SS the nested-name-specifier that precedes the name we're
4742/// looking for, if present.
4743///
4744/// \param CCC A CorrectionCandidateCallback object that provides further
4745/// validation of typo correction candidates. It also provides flags for
4746/// determining the set of keywords permitted.
4747///
4748/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4749/// diagnostics when the actual typo correction is attempted.
4750///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004751/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4752/// Expr from a typo correction candidate.
4753///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004754/// \param MemberContext if non-NULL, the context in which to look for
4755/// a member access expression.
4756///
4757/// \param EnteringContext whether we're entering the context described by
4758/// the nested-name-specifier SS.
4759///
4760/// \param OPT when non-NULL, the search for visible declarations will
4761/// also walk the protocols in the qualified interfaces of \p OPT.
4762///
4763/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4764/// Expr representing the result of performing typo correction, or nullptr if
4765/// typo correction is not possible. If nullptr is returned, no diagnostics will
4766/// be emitted and it is the responsibility of the caller to emit any that are
4767/// needed.
4768TypoExpr *Sema::CorrectTypoDelayed(
4769 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4770 Scope *S, CXXScopeSpec *SS,
4771 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004772 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004773 DeclContext *MemberContext, bool EnteringContext,
4774 const ObjCObjectPointerType *OPT) {
4775 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4776
Kaelyn Takata6c759512014-10-27 18:07:37 +00004777 auto Consumer = makeTypoCorrectionConsumer(
4778 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004779 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004780
Benjamin Kramerb8727332016-05-19 10:46:10 +00004781 // Give the external sema source a chance to correct the typo.
4782 TypoCorrection ExternalTypo;
4783 if (ExternalSource && Consumer) {
4784 ExternalTypo = ExternalSource->CorrectTypo(
Benjamin Kramer97d7a662016-05-19 21:53:33 +00004785 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4786 MemberContext, EnteringContext, OPT);
Benjamin Kramerb8727332016-05-19 10:46:10 +00004787 if (ExternalTypo)
4788 Consumer->addCorrection(ExternalTypo);
4789 }
4790
Kaelyn Takata6c759512014-10-27 18:07:37 +00004791 if (!Consumer || Consumer->empty())
4792 return nullptr;
4793
4794 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4795 // is not more that about a third of the length of the typo's identifier.
4796 unsigned ED = Consumer->getBestEditDistance(true);
4797 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Benjamin Kramerb8727332016-05-19 10:46:10 +00004798 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004799 return nullptr;
4800
4801 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004802 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004803}
4804
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004805void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4806 if (!CDecl) return;
4807
4808 if (isKeyword())
4809 CorrectionDecls.clear();
4810
Richard Smithde6d6c42015-12-29 19:43:10 +00004811 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004812
4813 if (!CorrectionName)
4814 CorrectionName = CDecl->getDeclName();
4815}
4816
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004817std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4818 if (CorrectionNameSpec) {
4819 std::string tmpBuffer;
4820 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4821 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004822 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004823 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004824 }
4825
4826 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004827}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004828
Nico Weberb58e51c2014-11-19 05:21:39 +00004829bool CorrectionCandidateCallback::ValidateCandidate(
4830 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004831 if (!candidate.isResolved())
4832 return true;
4833
4834 if (candidate.isKeyword())
4835 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4836 WantRemainingKeywords || WantObjCSuper;
4837
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004838 bool HasNonType = false;
4839 bool HasStaticMethod = false;
4840 bool HasNonStaticMethod = false;
4841 for (Decl *D : candidate) {
4842 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4843 D = FTD->getTemplatedDecl();
4844 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4845 if (Method->isStatic())
4846 HasStaticMethod = true;
4847 else
4848 HasNonStaticMethod = true;
4849 }
4850 if (!isa<TypeDecl>(D))
4851 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004852 }
4853
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004854 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4855 !candidate.getCorrectionSpecifier())
4856 return false;
4857
4858 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004859}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004860
4861FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004862 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004863 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004864 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004865 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004866 WantTypeSpecifiers = false;
4867 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004868 WantRemainingKeywords = false;
4869}
4870
4871bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4872 if (!candidate.getCorrectionDecl())
4873 return candidate.isKeyword();
4874
Aaron Ballman1e606f42014-07-15 22:03:49 +00004875 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004876 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004877 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004878 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4879 FD = FTD->getTemplatedDecl();
4880 if (!HasExplicitTemplateArgs && !FD) {
4881 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4882 // If the Decl is neither a function nor a template function,
4883 // determine if it is a pointer or reference to a function. If so,
4884 // check against the number of arguments expected for the pointee.
4885 QualType ValType = cast<ValueDecl>(ND)->getType();
4886 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4887 ValType = ValType->getPointeeType();
4888 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004889 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004890 return true;
4891 }
4892 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004893
4894 // Skip the current candidate if it is not a FunctionDecl or does not accept
4895 // the current number of arguments.
4896 if (!FD || !(FD->getNumParams() >= NumArgs &&
4897 FD->getMinRequiredArguments() <= NumArgs))
4898 continue;
4899
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004900 // If the current candidate is a non-static C++ method, skip the candidate
4901 // unless the method being corrected--or the current DeclContext, if the
4902 // function being corrected is not a method--is a method in the same class
4903 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004905 if (MemberFn || !MD->isStatic()) {
4906 CXXMethodDecl *CurMD =
4907 MemberFn
4908 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4909 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004910 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004911 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004912 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4913 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4914 continue;
4915 }
4916 }
4917 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004918 }
4919 return false;
4920}
Richard Smithf9b15102013-08-17 00:46:16 +00004921
4922void Sema::diagnoseTypo(const TypoCorrection &Correction,
4923 const PartialDiagnostic &TypoDiag,
4924 bool ErrorRecovery) {
4925 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4926 ErrorRecovery);
4927}
4928
Richard Smithe156254d2013-08-20 20:35:18 +00004929/// Find which declaration we should import to provide the definition of
4930/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004931static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4932 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004933 return VD->getDefinition();
Yaron Keren18c3d062016-07-13 19:04:51 +00004934 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4935 return FD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004936 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004937 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004938 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004939 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004940 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004941 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004942 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004943 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004944 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004945}
4946
Richard Smithf2b1eb92015-06-15 20:15:48 +00004947void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
Richard Smith6739a102016-05-05 00:56:12 +00004948 MissingImportKind MIK, bool Recover) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004949 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4950
4951 // Suggest importing a module providing the definition of this entity, if
4952 // possible.
4953 NamedDecl *Def = getDefinitionToImport(Decl);
4954 if (!Def)
4955 Def = Decl;
4956
Richard Smithf2b1eb92015-06-15 20:15:48 +00004957 Module *Owner = getOwningModule(Decl);
4958 assert(Owner && "definition of hidden declaration is not in a module");
4959
Richard Smith35c1df52015-06-17 20:16:32 +00004960 llvm::SmallVector<Module*, 8> OwningModules;
4961 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004962 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004963 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4964
Richard Smith6739a102016-05-05 00:56:12 +00004965 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
Richard Smith35c1df52015-06-17 20:16:32 +00004966 Recover);
4967}
4968
Richard Smith4eb83932016-04-27 21:57:05 +00004969/// \brief Get a "quoted.h" or <angled.h> include path to use in a diagnostic
4970/// suggesting the addition of a #include of the specified file.
4971static std::string getIncludeStringForHeader(Preprocessor &PP,
4972 const FileEntry *E) {
4973 bool IsSystem;
4974 auto Path =
4975 PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
4976 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
4977}
4978
Richard Smith35c1df52015-06-17 20:16:32 +00004979void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4980 SourceLocation DeclLoc,
4981 ArrayRef<Module *> Modules,
4982 MissingImportKind MIK, bool Recover) {
4983 assert(!Modules.empty());
4984
4985 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004986 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004987 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00004988 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004989 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00004990 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004991 ModuleList += "[...]";
4992 break;
4993 }
4994 ModuleList += M->getFullModuleName();
4995 }
4996
Richard Smith35c1df52015-06-17 20:16:32 +00004997 Diag(UseLoc, diag::err_module_unimported_use_multiple)
4998 << (int)MIK << Decl << ModuleList;
Richard Smith4eb83932016-04-27 21:57:05 +00004999 } else if (const FileEntry *E =
5000 PP.getModuleHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5001 // The right way to make the declaration visible is to include a header;
5002 // suggest doing so.
5003 //
5004 // FIXME: Find a smart place to suggest inserting a #include, and add
5005 // a FixItHint there.
5006 Diag(UseLoc, diag::err_module_unimported_use_header)
5007 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5008 << getIncludeStringForHeader(PP, E);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005009 } else {
Richard Smithacef17a2016-05-05 02:14:06 +00005010 // FIXME: Add a FixItHint that imports the corresponding module.
Richard Smith35c1df52015-06-17 20:16:32 +00005011 Diag(UseLoc, diag::err_module_unimported_use)
5012 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005013 }
Richard Smith35c1df52015-06-17 20:16:32 +00005014
5015 unsigned DiagID;
5016 switch (MIK) {
5017 case MissingImportKind::Declaration:
5018 DiagID = diag::note_previous_declaration;
5019 break;
5020 case MissingImportKind::Definition:
5021 DiagID = diag::note_previous_definition;
5022 break;
5023 case MissingImportKind::DefaultArgument:
5024 DiagID = diag::note_default_argument_declared_here;
5025 break;
Richard Smith6739a102016-05-05 00:56:12 +00005026 case MissingImportKind::ExplicitSpecialization:
5027 DiagID = diag::note_explicit_specialization_declared_here;
5028 break;
5029 case MissingImportKind::PartialSpecialization:
5030 DiagID = diag::note_partial_specialization_declared_here;
5031 break;
Richard Smith35c1df52015-06-17 20:16:32 +00005032 }
5033 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005034
5035 // Try to recover by implicitly importing this module.
5036 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00005037 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005038}
5039
Richard Smithf9b15102013-08-17 00:46:16 +00005040/// \brief Diagnose a successfully-corrected typo. Separated from the correction
5041/// itself to allow external validation of the result, etc.
5042///
5043/// \param Correction The result of performing typo correction.
5044/// \param TypoDiag The diagnostic to produce. This will have the corrected
5045/// string added to it (and usually also a fixit).
5046/// \param PrevNote A note to use when indicating the location of the entity to
5047/// which we are correcting. Will have the correction string added to it.
5048/// \param ErrorRecovery If \c true (the default), the caller is going to
5049/// recover from the typo as if the corrected string had been typed.
5050/// In this case, \c PDiag must be an error, and we will attach a fixit
5051/// to it.
5052void Sema::diagnoseTypo(const TypoCorrection &Correction,
5053 const PartialDiagnostic &TypoDiag,
5054 const PartialDiagnostic &PrevNote,
5055 bool ErrorRecovery) {
5056 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5057 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5058 FixItHint FixTypo = FixItHint::CreateReplacement(
5059 Correction.getCorrectionRange(), CorrectedStr);
5060
Richard Smithe156254d2013-08-20 20:35:18 +00005061 // Maybe we're just missing a module import.
5062 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00005063 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00005064 assert(Decl && "import required but no declaration to import");
5065
Richard Smithf2b1eb92015-06-15 20:15:48 +00005066 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005067 MissingImportKind::Declaration, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00005068 return;
5069 }
5070
Richard Smithf9b15102013-08-17 00:46:16 +00005071 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5072 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5073
5074 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005075 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005076 if (PrevNote.getDiagID() && ChosenDecl)
5077 Diag(ChosenDecl->getLocation(), PrevNote)
5078 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5079}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005080
Kaelyn Takata8363f042014-10-27 18:07:42 +00005081TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5082 TypoDiagnosticGenerator TDG,
5083 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005084 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5085 auto TE = new (Context) TypoExpr(Context.DependentTy);
5086 auto &State = DelayedTypos[TE];
5087 State.Consumer = std::move(TCC);
5088 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005089 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005090 return TE;
5091}
5092
5093const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5094 auto Entry = DelayedTypos.find(TE);
5095 assert(Entry != DelayedTypos.end() &&
5096 "Failed to get the state for a TypoExpr!");
5097 return Entry->second;
5098}
5099
5100void Sema::clearDelayedTypo(TypoExpr *TE) {
5101 DelayedTypos.erase(TE);
5102}
Richard Smithba3a4f92016-01-12 21:59:26 +00005103
5104void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5105 DeclarationNameInfo Name(II, IILoc);
5106 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5107 R.suppressDiagnostics();
5108 R.setHideTags(false);
5109 LookupName(R, S);
5110 R.dump();
5111}