blob: 1fc6d4fd51589baa57003574d27043d6240949c4 [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.
Chandler Carruth6232e4d2016-11-04 06:16:09 +00001296 if (!(Found && S->isTemplateParamScope())) {
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001297 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());
Vassil Vassilevb4829e42016-09-13 10:38:26 +00001342 assert(Parent->isHidden() && "unexpectedly hidden decl");
Richard Smith87bb5692015-06-09 00:35:49 +00001343 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());
Richard Smithdc1f0422016-07-20 19:10:16 +00001370 auto &TopLevel = ModuleScopes.empty()
1371 ? VisibleModules
1372 : ModuleScopes[0].OuterVisibleModules;
Richard Smith42413142015-05-15 20:05:43 +00001373 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1374 }
1375
1376 M = CachedFakeTopLevelModule;
1377 }
1378
1379 if (M)
1380 Entity->setLocalOwningModule(M);
1381 return M;
1382}
1383
Richard Smithd9ba2242015-05-07 03:54:19 +00001384void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001385 if (auto *M = PP.getModuleContainingLocation(Loc))
1386 Context.mergeDefinitionIntoModule(ND, M);
1387 else
1388 // We're not building a module; just make the definition visible.
1389 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001390
1391 // If ND is a template declaration, make the template parameters
1392 // visible too. They're not (necessarily) within a mergeable DeclContext.
1393 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1394 for (auto *Param : *TD->getTemplateParameters())
1395 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001396}
1397
Richard Smith0e5d7b82013-07-25 23:08:39 +00001398/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001399static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001400 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1401 // If this function was instantiated from a template, the defining module is
1402 // the module containing the pattern.
1403 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1404 Entity = Pattern;
1405 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001406 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1407 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001408 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1409 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1410 Entity = getInstantiatedFrom(ED, MSInfo);
1411 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1412 // FIXME: Map from variable template specializations back to the template.
1413 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1414 Entity = getInstantiatedFrom(VD, MSInfo);
1415 }
1416
1417 // Walk up to the containing context. That might also have been instantiated
1418 // from a template.
1419 DeclContext *Context = Entity->getDeclContext();
1420 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001421 return S.getOwningModule(Entity);
1422 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001423}
1424
1425llvm::DenseSet<Module*> &Sema::getLookupModules() {
1426 unsigned N = ActiveTemplateInstantiations.size();
1427 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1428 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001429 Module *M =
1430 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001431 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001432 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001433 ActiveTemplateInstantiationLookupModules.push_back(M);
1434 }
1435 return LookupModulesCache;
1436}
1437
Richard Smith42413142015-05-15 20:05:43 +00001438bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1439 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1440 if (isModuleVisible(Merged))
1441 return true;
1442 return false;
1443}
1444
Richard Smithe7bd6de2015-06-10 20:30:23 +00001445template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001446static bool
1447hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1448 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001449 if (!D->hasDefaultArgument())
1450 return false;
1451
1452 while (D) {
1453 auto &DefaultArg = D->getDefaultArgStorage();
1454 if (!DefaultArg.isInherited() && S.isVisible(D))
1455 return true;
1456
Richard Smith63e09bf2015-06-17 20:39:41 +00001457 if (!DefaultArg.isInherited() && Modules) {
1458 auto *NonConstD = const_cast<ParmDecl*>(D);
1459 Modules->push_back(S.getOwningModule(NonConstD));
1460 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1461 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1462 }
Richard Smith35c1df52015-06-17 20:16:32 +00001463
Richard Smithe7bd6de2015-06-10 20:30:23 +00001464 // If there was a previous default argument, maybe its parameter is visible.
1465 D = DefaultArg.getInheritedFrom();
1466 }
1467 return false;
1468}
1469
Richard Smith35c1df52015-06-17 20:16:32 +00001470bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1471 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001472 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001473 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001474 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001475 return ::hasVisibleDefaultArgument(*this, P, Modules);
1476 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1477 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001478}
1479
Richard Smith6739a102016-05-05 00:56:12 +00001480bool Sema::hasVisibleMemberSpecialization(
1481 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1482 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1483 "not a member specialization");
1484 for (auto *Redecl : D->redecls()) {
1485 // If the specialization is declared at namespace scope, then it's a member
1486 // specialization declaration. If it's lexically inside the class
1487 // definition then it was instantiated.
1488 //
1489 // FIXME: This is a hack. There should be a better way to determine this.
1490 // FIXME: What about MS-style explicit specializations declared within a
1491 // class definition?
1492 if (Redecl->getLexicalDeclContext()->isFileContext()) {
1493 auto *NonConstR = const_cast<NamedDecl*>(cast<NamedDecl>(Redecl));
1494
1495 if (isVisible(NonConstR))
1496 return true;
1497
1498 if (Modules) {
1499 Modules->push_back(getOwningModule(NonConstR));
1500 const auto &Merged = Context.getModulesWithMergedDefinition(NonConstR);
1501 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1502 }
1503 }
1504 }
1505
1506 return false;
1507}
1508
Richard Smith0e5d7b82013-07-25 23:08:39 +00001509/// \brief Determine whether a declaration is visible to name lookup.
1510///
1511/// This routine determines whether the declaration D is visible in the current
1512/// lookup context, taking into account the current template instantiation
1513/// stack. During template instantiation, a declaration is visible if it is
1514/// visible from a module containing any entity on the template instantiation
1515/// path (by instantiating a template, you allow it to see the declarations that
1516/// your module can see, including those later on in your module).
1517bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001518 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001519 Module *DeclModule = nullptr;
1520
1521 if (SemaRef.getLangOpts().ModulesLocalVisibility) {
1522 DeclModule = SemaRef.getOwningModule(D);
1523 if (!DeclModule) {
1524 // getOwningModule() may have decided the declaration should not be hidden.
1525 assert(!D->isHidden() && "hidden decl not from a module");
Richard Smith42413142015-05-15 20:05:43 +00001526 return true;
Richard Smith5196a172015-08-24 03:38:11 +00001527 }
1528
1529 // If the owning module is visible, and the decl is not module private,
1530 // then the decl is visible too. (Module private is ignored within the same
1531 // top-level module.)
1532 if ((!D->isFromASTFile() || !D->isModulePrivate()) &&
1533 (SemaRef.isModuleVisible(DeclModule) ||
1534 SemaRef.hasVisibleMergedDefinition(D)))
Richard Smith42413142015-05-15 20:05:43 +00001535 return true;
1536 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001537
Richard Smithbe3980b2015-03-27 00:41:57 +00001538 // If this declaration is not at namespace scope nor module-private,
1539 // then it is visible if its lexical parent has a visible definition.
1540 DeclContext *DC = D->getLexicalDeclContext();
Richard Smith8df390f2016-09-08 23:14:54 +00001541 if (!D->isModulePrivate() && DC && !DC->isFileContext() &&
1542 !isa<LinkageSpecDecl>(DC) && !isa<ExportDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001543 // For a parameter, check whether our current template declaration's
1544 // lexical context is visible, not whether there's some other visible
1545 // definition of it, because parameters aren't "within" the definition.
Vassil Vassilev714b81c2016-09-08 20:34:41 +00001546 //
1547 // In C++ we need to check for a visible definition due to ODR merging,
1548 // and in C we must not because each declaration of a function gets its own
1549 // set of declarations for tags in prototype scope.
1550 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D)
1551 || (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
Richard Smithc7d48d12015-05-20 17:50:35 +00001552 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1553 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001554 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1555 // FIXME: Do something better in this case.
1556 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001557 // Cache the fact that this declaration is implicitly visible because
1558 // its parent has a visible definition.
1559 D->setHidden(false);
1560 }
1561 return true;
1562 }
1563 return false;
1564 }
1565
Richard Smith0e5d7b82013-07-25 23:08:39 +00001566 // Find the extra places where we need to look.
1567 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1568 if (LookupModules.empty())
1569 return false;
1570
Richard Smith5196a172015-08-24 03:38:11 +00001571 if (!DeclModule) {
1572 DeclModule = SemaRef.getOwningModule(D);
1573 assert(DeclModule && "hidden decl not from a module");
1574 }
1575
Richard Smith0e5d7b82013-07-25 23:08:39 +00001576 // If our lookup set contains the decl's module, it's visible.
1577 if (LookupModules.count(DeclModule))
1578 return true;
1579
1580 // If the declaration isn't exported, it's not visible in any other module.
1581 if (D->isModulePrivate())
1582 return false;
1583
1584 // Check whether DeclModule is transitively exported to an import of
1585 // the lookup set.
Yaron Keren941ad902015-11-23 19:28:42 +00001586 return std::any_of(LookupModules.begin(), LookupModules.end(),
Yaron Keren4c31fcf2015-11-24 20:18:24 +00001587 [&](Module *M) { return M->isModuleVisible(DeclModule); });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001588}
1589
Richard Smith42413142015-05-15 20:05:43 +00001590bool Sema::isVisibleSlow(const NamedDecl *D) {
1591 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1592}
1593
Richard Smith10568d82015-11-17 03:02:41 +00001594bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1595 for (auto *D : R) {
1596 if (isVisible(D))
1597 return true;
1598 }
1599 return New->isExternallyVisible();
1600}
1601
Douglas Gregor4a814562011-12-14 16:03:29 +00001602/// \brief Retrieve the visible declaration corresponding to D, if any.
1603///
1604/// This routine determines whether the declaration D is visible in the current
1605/// module, with the current imports. If not, it checks whether any
1606/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001607///
Douglas Gregor4a814562011-12-14 16:03:29 +00001608/// \returns D, or a visible previous declaration of D, whichever is more recent
1609/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001610static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1611 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001612
Aaron Ballman86c93902014-03-06 23:45:36 +00001613 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001614 // Don't bother with extra checks if we already know this one isn't visible.
1615 if (RD == D)
1616 continue;
1617
Richard Smith6739a102016-05-05 00:56:12 +00001618 auto ND = cast<NamedDecl>(RD);
1619 // FIXME: This is wrong in the case where the previous declaration is not
1620 // visible in the same scope as D. This needs to be done much more
1621 // carefully.
1622 if (LookupResult::isVisible(SemaRef, ND))
1623 return ND;
Douglas Gregor4a814562011-12-14 16:03:29 +00001624 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001625
Craig Topperc3ec1492014-05-26 06:22:03 +00001626 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001627}
1628
Richard Smith6739a102016-05-05 00:56:12 +00001629bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1630 llvm::SmallVectorImpl<Module *> *Modules) {
1631 assert(!isVisible(D) && "not in slow case");
1632
1633 for (auto *Redecl : D->redecls()) {
1634 auto *NonConstR = const_cast<NamedDecl*>(cast<NamedDecl>(Redecl));
1635 if (isVisible(NonConstR))
1636 return true;
1637
1638 if (Modules) {
1639 Modules->push_back(getOwningModule(NonConstR));
1640 const auto &Merged = Context.getModulesWithMergedDefinition(NonConstR);
1641 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1642 }
1643 }
1644
1645 return false;
1646}
1647
Richard Smithe156254d2013-08-20 20:35:18 +00001648NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001649 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1650 // Namespaces are a bit of a special case: we expect there to be a lot of
1651 // redeclarations of some namespaces, all declarations of a namespace are
1652 // essentially interchangeable, all declarations are found by name lookup
1653 // if any is, and namespaces are never looked up during template
1654 // instantiation. So we benefit from caching the check in this case, and
1655 // it is correct to do so.
1656 auto *Key = ND->getCanonicalDecl();
1657 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1658 return Acceptable;
1659 auto *Acceptable =
1660 isVisible(getSema(), Key) ? Key : findAcceptableDecl(getSema(), Key);
1661 if (Acceptable)
1662 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1663 return Acceptable;
1664 }
1665
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001666 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001667}
1668
Douglas Gregor34074322009-01-14 22:20:51 +00001669/// @brief Perform unqualified name lookup starting from a given
1670/// scope.
1671///
1672/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1673/// used to find names within the current scope. For example, 'x' in
1674/// @code
1675/// int x;
1676/// int f() {
1677/// return x; // unqualified name look finds 'x' in the global scope
1678/// }
1679/// @endcode
1680///
1681/// Different lookup criteria can find different names. For example, a
1682/// particular scope can have both a struct and a function of the same
1683/// name, and each can be found by certain lookup criteria. For more
1684/// information about lookup criteria, see the documentation for the
1685/// class LookupCriteria.
1686///
1687/// @param S The scope from which unqualified name lookup will
1688/// begin. If the lookup criteria permits, name lookup may also search
1689/// in the parent scopes.
1690///
James Dennett91738ff2012-06-22 10:32:46 +00001691/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1692/// look up and the lookup kind), and is updated with the results of lookup
1693/// including zero or more declarations and possibly additional information
1694/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001695///
James Dennett91738ff2012-06-22 10:32:46 +00001696/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001697bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1698 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001699 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001700
John McCall27b18f82009-11-17 02:14:36 +00001701 LookupNameKind NameKind = R.getLookupKind();
1702
David Blaikiebbafb8a2012-03-11 07:00:24 +00001703 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001704 // Unqualified name lookup in C/Objective-C is purely lexical, so
1705 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001706 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001707 // Find the nearest non-transparent declaration scope.
1708 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001709 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001710 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001711 }
1712
Richard Smith541b38b2013-09-20 01:15:31 +00001713 // When performing a scope lookup, we want to find local extern decls.
1714 FindLocalExternScope FindLocals(R);
1715
Douglas Gregor34074322009-01-14 22:20:51 +00001716 // Scan up the scope chain looking for a decl that matches this
1717 // identifier that is in the appropriate namespace. This search
1718 // should not take long, as shadowing of names is uncommon, and
1719 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001720 bool LeftStartingScope = false;
1721
Douglas Gregored8f2882009-01-30 01:04:22 +00001722 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001723 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001724 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001725 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001726 if (NameKind == LookupRedeclarationWithLinkage) {
1727 // Determine whether this (or a previous) declaration is
1728 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001729 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001730 LeftStartingScope = true;
1731
1732 // If we found something outside of our starting scope that
1733 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001734 if (LeftStartingScope && !((*I)->hasLinkage())) {
1735 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001736 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001737 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001738 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001739 else if (NameKind == LookupObjCImplicitSelfParam &&
1740 !isa<ImplicitParamDecl>(*I))
1741 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001742
Douglas Gregor4a814562011-12-14 16:03:29 +00001743 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001744
Douglas Gregorb59643b2012-01-03 23:26:26 +00001745 // Check whether there are any other declarations with the same name
1746 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001747 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001748 // Find the scope in which this declaration was declared (if it
1749 // actually exists in a Scope).
1750 while (S && !S->isDeclScope(D))
1751 S = S->getParent();
1752
1753 // If the scope containing the declaration is the translation unit,
1754 // then we'll need to perform our checks based on the matching
1755 // DeclContexts rather than matching scopes.
1756 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001757 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001758
1759 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001760 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001761 if (!S)
1762 DC = (*I)->getDeclContext()->getRedeclContext();
1763
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001764 IdentifierResolver::iterator LastI = I;
1765 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001766 if (S) {
1767 // Match based on scope.
1768 if (!S->isDeclScope(*LastI))
1769 break;
1770 } else {
1771 // Match based on DeclContext.
1772 DeclContext *LastDC
1773 = (*LastI)->getDeclContext()->getRedeclContext();
1774 if (!LastDC->Equals(DC))
1775 break;
1776 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001777
1778 // If the declaration is in the right namespace and visible, add it.
1779 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1780 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001781 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001782
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001783 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001784 }
Richard Smith541b38b2013-09-20 01:15:31 +00001785
John McCall9f3059a2009-10-09 21:13:30 +00001786 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001787 }
Douglas Gregor34074322009-01-14 22:20:51 +00001788 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001789 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001790 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001791 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001792 }
1793
1794 // If we didn't find a use of this identifier, and if the identifier
1795 // corresponds to a compiler builtin, create the decl object for the builtin
1796 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001797 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1798 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001799
Axel Naumann016538a2011-02-24 16:47:47 +00001800 // If we didn't find a use of this identifier, the ExternalSource
1801 // may be able to handle the situation.
1802 // Note: some lookup failures are expected!
1803 // See e.g. R.isForRedeclaration().
1804 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001805}
1806
John McCall6538c932009-10-10 05:48:19 +00001807/// @brief Perform qualified name lookup in the namespaces nominated by
1808/// using directives by the given context.
1809///
1810/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001811/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001812/// (where X is the global namespace), let S be the set of all
1813/// declarations of m in X and in the transitive closure of all
1814/// namespaces nominated by using-directives in X and its used
1815/// namespaces, except that using-directives are ignored in any
1816/// namespace, including X, directly containing one or more
1817/// declarations of m. No namespace is searched more than once in
1818/// the lookup of a name. If S is the empty set, the program is
1819/// ill-formed. Otherwise, if S has exactly one member, or if the
1820/// context of the reference is a using-declaration
1821/// (namespace.udecl), S is the required set of declarations of
1822/// m. Otherwise if the use of m is not one that allows a unique
1823/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001824///
John McCall6538c932009-10-10 05:48:19 +00001825/// C++98 [namespace.qual]p5:
1826/// During the lookup of a qualified namespace member name, if the
1827/// lookup finds more than one declaration of the member, and if one
1828/// declaration introduces a class name or enumeration name and the
1829/// other declarations either introduce the same object, the same
1830/// enumerator or a set of functions, the non-type name hides the
1831/// class or enumeration name if and only if the declarations are
1832/// from the same namespace; otherwise (the declarations are from
1833/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001834static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001835 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001836 assert(StartDC->isFileContext() && "start context is not a file context");
1837
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001838 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1839 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001840
1841 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001842 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001843 Visited.insert(StartDC);
1844
1845 // We have not yet looked into these namespaces, much less added
1846 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001847 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001848
1849 // We have already looked into the initial namespace; seed the queue
1850 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001851 for (auto *I : UsingDirectives) {
1852 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001853 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001854 Queue.push_back(ND);
1855 }
1856
1857 // The easiest way to implement the restriction in [namespace.qual]p5
1858 // is to check whether any of the individual results found a tag
1859 // and, if so, to declare an ambiguity if the final result is not
1860 // a tag.
1861 bool FoundTag = false;
1862 bool FoundNonTag = false;
1863
John McCall5cebab12009-11-18 07:57:50 +00001864 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001865
1866 bool Found = false;
1867 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001868 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001869
1870 // We go through some convolutions here to avoid copying results
1871 // between LookupResults.
1872 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001873 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001874 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001875
1876 if (FoundDirect) {
1877 // First do any local hiding.
1878 DirectR.resolveKind();
1879
1880 // If the local result is a tag, remember that.
1881 if (DirectR.isSingleTagDecl())
1882 FoundTag = true;
1883 else
1884 FoundNonTag = true;
1885
1886 // Append the local results to the total results if necessary.
1887 if (UseLocal) {
1888 R.addAllDecls(LocalR);
1889 LocalR.clear();
1890 }
1891 }
1892
1893 // If we find names in this namespace, ignore its using directives.
1894 if (FoundDirect) {
1895 Found = true;
1896 continue;
1897 }
1898
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001899 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001900 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001901 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001902 Queue.push_back(Nom);
1903 }
1904 }
1905
1906 if (Found) {
1907 if (FoundTag && FoundNonTag)
1908 R.setAmbiguousQualifiedTagHiding();
1909 else
1910 R.resolveKind();
1911 }
1912
1913 return Found;
1914}
1915
Douglas Gregor39982192010-08-15 06:18:01 +00001916/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001918 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001919 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001921 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001922 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001923}
1924
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001926/// static members, nested types, and enumerators.
1927template<typename InputIterator>
1928static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1929 Decl *D = (*First)->getUnderlyingDecl();
1930 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1931 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregorc0d24902010-10-22 22:08:47 +00001933 if (isa<CXXMethodDecl>(D)) {
1934 // Determine whether all of the methods are static.
1935 bool AllMethodsAreStatic = true;
1936 for(; First != Last; ++First) {
1937 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
Douglas Gregorc0d24902010-10-22 22:08:47 +00001939 if (!isa<CXXMethodDecl>(D)) {
1940 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1941 break;
1942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943
Douglas Gregorc0d24902010-10-22 22:08:47 +00001944 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1945 AllMethodsAreStatic = false;
1946 break;
1947 }
1948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Douglas Gregorc0d24902010-10-22 22:08:47 +00001950 if (AllMethodsAreStatic)
1951 return true;
1952 }
1953
1954 return false;
1955}
1956
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001957/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001958///
1959/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1960/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001961/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001962///
1963/// Different lookup criteria can find different names. For example, a
1964/// particular scope can have both a struct and a function of the same
1965/// name, and each can be found by certain lookup criteria. For more
1966/// information about lookup criteria, see the documentation for the
1967/// class LookupCriteria.
1968///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001969/// \param R captures both the lookup criteria and any lookup results found.
1970///
1971/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001972/// search. If the lookup criteria permits, name lookup may also search
1973/// in the parent contexts or (for C++ classes) base classes.
1974///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001976/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001977///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001978/// \returns true if lookup succeeded, false if it failed.
1979bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1980 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001981 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001982
John McCall27b18f82009-11-17 02:14:36 +00001983 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001984 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001985
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001986 // Make sure that the declaration context is complete.
1987 assert((!isa<TagDecl>(LookupCtx) ||
1988 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001989 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001990 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001991 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001992
Eugene Leviant0d8103e2015-11-18 12:48:05 +00001993 struct QualifiedLookupInScope {
1994 bool oldVal;
1995 DeclContext *Context;
1996 // Set flag in DeclContext informing debugger that we're looking for qualified name
1997 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
1998 oldVal = ctx->setUseQualifiedLookup();
1999 }
2000 ~QualifiedLookupInScope() {
2001 Context->setUseQualifiedLookup(oldVal);
2002 }
2003 } QL(LookupCtx);
2004
Douglas Gregord3a59182010-02-12 05:48:04 +00002005 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00002006 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00002007 if (isa<CXXRecordDecl>(LookupCtx))
2008 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00002009 return true;
2010 }
Douglas Gregor34074322009-01-14 22:20:51 +00002011
John McCall6538c932009-10-10 05:48:19 +00002012 // Don't descend into implied contexts for redeclarations.
2013 // C++98 [namespace.qual]p6:
2014 // In a declaration for a namespace member in which the
2015 // declarator-id is a qualified-id, given that the qualified-id
2016 // for the namespace member has the form
2017 // nested-name-specifier unqualified-id
2018 // the unqualified-id shall name a member of the namespace
2019 // designated by the nested-name-specifier.
2020 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00002021 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00002022 return false;
2023
John McCall27b18f82009-11-17 02:14:36 +00002024 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00002025 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00002026 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00002027
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002028 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00002029 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002030 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00002031 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00002032 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002033
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002034 // If we're performing qualified name lookup into a dependent class,
2035 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002036 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002037 // template instantiation time (at which point all bases will be available)
2038 // or we have to fail.
2039 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2040 LookupRec->hasAnyDependentBases()) {
2041 R.setNotFoundInCurrentInstantiation();
2042 return false;
2043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002044
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002045 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002046 CXXBasePaths Paths;
2047 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002048
2049 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002050 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2051 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002052 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002053 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002054 case LookupOrdinaryName:
2055 case LookupMemberName:
2056 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002057 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002058 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2059 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060
Douglas Gregor36d1b142009-10-06 17:59:45 +00002061 case LookupTagName:
2062 BaseCallback = &CXXRecordDecl::FindTagMember;
2063 break;
John McCall84d87672009-12-10 09:41:52 +00002064
Douglas Gregor39982192010-08-15 06:18:01 +00002065 case LookupAnyName:
2066 BaseCallback = &LookupAnyMember;
2067 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002069 case LookupOMPReductionName:
2070 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2071 break;
2072
John McCall84d87672009-12-10 09:41:52 +00002073 case LookupUsingDeclName:
2074 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075
Douglas Gregor36d1b142009-10-06 17:59:45 +00002076 case LookupOperatorName:
2077 case LookupNamespaceName:
2078 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002079 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002080 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002081 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082
Douglas Gregor36d1b142009-10-06 17:59:45 +00002083 case LookupNestedNameSpecifierName:
2084 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2085 break;
2086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002088 DeclarationName Name = R.getLookupName();
2089 if (!LookupRec->lookupInBases(
2090 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2091 return BaseCallback(Specifier, Path, Name);
2092 },
2093 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002094 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002095
John McCall553c0792010-01-23 00:46:32 +00002096 R.setNamingClass(LookupRec);
2097
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002098 // C++ [class.member.lookup]p2:
2099 // [...] If the resulting set of declarations are not all from
2100 // sub-objects of the same type, or the set has a nonstatic member
2101 // and includes members from distinct sub-objects, there is an
2102 // ambiguity and the program is ill-formed. Otherwise that set is
2103 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002104 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002105 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002106 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107
Douglas Gregor36d1b142009-10-06 17:59:45 +00002108 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002109 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002110 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002111
John McCall401982f2010-01-20 21:53:11 +00002112 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2113 // across all paths.
2114 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002115
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002116 // Determine whether we're looking at a distinct sub-object or not.
2117 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002118 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002119 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2120 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002121 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122 }
2123
Douglas Gregorc0d24902010-10-22 22:08:47 +00002124 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002125 != Context.getCanonicalType(PathElement.Base->getType())) {
2126 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002127 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002128 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002129 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002130 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002131 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2132 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133
David Blaikieff7d47a2012-12-19 00:45:41 +00002134 while (FirstD != FirstPath->Decls.end() &&
2135 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002136 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2137 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2138 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139
Douglas Gregorc0d24902010-10-22 22:08:47 +00002140 ++FirstD;
2141 ++CurrentD;
2142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143
David Blaikieff7d47a2012-12-19 00:45:41 +00002144 if (FirstD == FirstPath->Decls.end() &&
2145 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002146 continue;
2147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
John McCall9f3059a2009-10-09 21:13:30 +00002149 R.setAmbiguousBaseSubobjectTypes(Paths);
2150 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151 }
2152
Douglas Gregorc0d24902010-10-22 22:08:47 +00002153 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002154 // We have a different subobject of the same type.
2155
2156 // C++ [class.member.lookup]p5:
2157 // A static member, a nested type or an enumerator defined in
2158 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002159 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002160 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002161 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002163 // We have found a nonstatic member name in multiple, distinct
2164 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002165 R.setAmbiguousBaseSubobjects(Paths);
2166 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002167 }
2168 }
2169
2170 // Lookup in a base class succeeded; return these results.
2171
Aaron Ballman1e606f42014-07-15 22:03:49 +00002172 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002173 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2174 D->getAccess());
2175 R.addDecl(D, AS);
2176 }
John McCall9f3059a2009-10-09 21:13:30 +00002177 R.resolveKind();
2178 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002179}
2180
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002181/// \brief Performs qualified name lookup or special type of lookup for
2182/// "__super::" scope specifier.
2183///
2184/// This routine is a convenience overload meant to be called from contexts
2185/// that need to perform a qualified name lookup with an optional C++ scope
2186/// specifier that might require special kind of lookup.
2187///
2188/// \param R captures both the lookup criteria and any lookup results found.
2189///
2190/// \param LookupCtx The context in which qualified name lookup will
2191/// search.
2192///
2193/// \param SS An optional C++ scope-specifier.
2194///
2195/// \returns true if lookup succeeded, false if it failed.
2196bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2197 CXXScopeSpec &SS) {
2198 auto *NNS = SS.getScopeRep();
2199 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2200 return LookupInSuper(R, NNS->getAsRecordDecl());
2201 else
2202
2203 return LookupQualifiedName(R, LookupCtx);
2204}
2205
Douglas Gregor34074322009-01-14 22:20:51 +00002206/// @brief Performs name lookup for a name that was parsed in the
2207/// source code, and may contain a C++ scope specifier.
2208///
2209/// This routine is a convenience routine meant to be called from
2210/// contexts that receive a name and an optional C++ scope specifier
2211/// (e.g., "N::M::x"). It will then perform either qualified or
2212/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002213/// respectively) on the given name and return those results. It will
2214/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002215///
2216/// @param S The scope from which unqualified name lookup will
2217/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002218///
Douglas Gregore861bac2009-08-25 22:51:20 +00002219/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002220///
Douglas Gregore861bac2009-08-25 22:51:20 +00002221/// @param EnteringContext Indicates whether we are going to enter the
2222/// context of the scope-specifier SS (if present).
2223///
John McCall9f3059a2009-10-09 21:13:30 +00002224/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002225bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002226 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002227 if (SS && SS->isInvalid()) {
2228 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002229 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002230 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002231 }
Mike Stump11289f42009-09-09 15:08:12 +00002232
Douglas Gregore861bac2009-08-25 22:51:20 +00002233 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002234 NestedNameSpecifier *NNS = SS->getScopeRep();
2235 if (NNS->getKind() == NestedNameSpecifier::Super)
2236 return LookupInSuper(R, NNS->getAsRecordDecl());
2237
Douglas Gregore861bac2009-08-25 22:51:20 +00002238 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002239 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002240 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002241 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002242 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002243
John McCall27b18f82009-11-17 02:14:36 +00002244 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002245 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002246 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002247
Douglas Gregore861bac2009-08-25 22:51:20 +00002248 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002249 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002250 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002251 R.setNotFoundInCurrentInstantiation();
2252 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002253 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002254 }
2255
Mike Stump11289f42009-09-09 15:08:12 +00002256 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002257 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002258}
2259
Nikola Smiljanic67860242014-09-26 00:28:20 +00002260/// \brief Perform qualified name lookup into all base classes of the given
2261/// class.
2262///
2263/// \param R captures both the lookup criteria and any lookup results found.
2264///
2265/// \param Class The context in which qualified name lookup will
2266/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002267///
2268/// @returns True if any decls were found (but possibly ambiguous)
2269bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002270 // The access-control rules we use here are essentially the rules for
2271 // doing a lookup in Class that just magically skipped the direct
2272 // members of Class itself. That is, the naming class is Class, and the
2273 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002274 for (const auto &BaseSpec : Class->bases()) {
2275 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2276 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2277 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2278 Result.setBaseObjectType(Context.getRecordType(Class));
2279 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002280
2281 // Copy the lookup results into the target, merging the base's access into
2282 // the path access.
2283 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2284 R.addDecl(I.getDecl(),
2285 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2286 I.getAccess()));
2287 }
2288
2289 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002290 }
2291
2292 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002293 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002294
2295 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002296}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002297
James Dennett41725122012-06-22 10:16:05 +00002298/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002299/// from name lookup.
2300///
James Dennett41725122012-06-22 10:16:05 +00002301/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002302void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002303 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2304
John McCall27b18f82009-11-17 02:14:36 +00002305 DeclarationName Name = Result.getLookupName();
2306 SourceLocation NameLoc = Result.getNameLoc();
2307 SourceRange LookupRange = Result.getContextRange();
2308
John McCall6538c932009-10-10 05:48:19 +00002309 switch (Result.getAmbiguityKind()) {
2310 case LookupResult::AmbiguousBaseSubobjects: {
2311 CXXBasePaths *Paths = Result.getBasePaths();
2312 QualType SubobjectType = Paths->front().back().Base->getType();
2313 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2314 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2315 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002316
David Blaikieff7d47a2012-12-19 00:45:41 +00002317 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002318 while (isa<CXXMethodDecl>(*Found) &&
2319 cast<CXXMethodDecl>(*Found)->isStatic())
2320 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321
John McCall6538c932009-10-10 05:48:19 +00002322 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002323 break;
John McCall6538c932009-10-10 05:48:19 +00002324 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002325
John McCall6538c932009-10-10 05:48:19 +00002326 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002327 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2328 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329
John McCall6538c932009-10-10 05:48:19 +00002330 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002331 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002332 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2333 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002334 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002335 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002336 if (DeclsPrinted.insert(D).second)
2337 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2338 }
Serge Pavlov99292092013-08-29 07:23:24 +00002339 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002340 }
2341
John McCall6538c932009-10-10 05:48:19 +00002342 case LookupResult::AmbiguousTagHiding: {
2343 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002344
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002345 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002346
Aaron Ballman1e606f42014-07-15 22:03:49 +00002347 for (auto *D : Result)
2348 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002349 TagDecls.insert(TD);
2350 Diag(TD->getLocation(), diag::note_hidden_tag);
2351 }
2352
Aaron Ballman1e606f42014-07-15 22:03:49 +00002353 for (auto *D : Result)
2354 if (!isa<TagDecl>(D))
2355 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002356
2357 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002358 LookupResult::Filter F = Result.makeFilter();
2359 while (F.hasNext()) {
2360 if (TagDecls.count(F.next()))
2361 F.erase();
2362 }
2363 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002364 break;
John McCall6538c932009-10-10 05:48:19 +00002365 }
2366
2367 case LookupResult::AmbiguousReference: {
2368 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Aaron Ballman1e606f42014-07-15 22:03:49 +00002370 for (auto *D : Result)
2371 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002372 break;
John McCall6538c932009-10-10 05:48:19 +00002373 }
Serge Pavlov99292092013-08-29 07:23:24 +00002374 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002375}
Douglas Gregore254f902009-02-04 00:32:51 +00002376
John McCallf24d7bb2010-05-28 18:45:08 +00002377namespace {
2378 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002379 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002380 Sema::AssociatedNamespaceSet &Namespaces,
2381 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002382 : S(S), Namespaces(Namespaces), Classes(Classes),
2383 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002384 }
2385
2386 Sema &S;
2387 Sema::AssociatedNamespaceSet &Namespaces;
2388 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002389 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002390 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002391} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002392
Mike Stump11289f42009-09-09 15:08:12 +00002393static void
John McCallf24d7bb2010-05-28 18:45:08 +00002394addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002395
Douglas Gregor8b895222010-04-30 07:08:38 +00002396static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2397 DeclContext *Ctx) {
2398 // Add the associated namespace for this class.
2399
2400 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2401 // be a locally scoped record.
2402
Sebastian Redlbd595762010-08-31 20:53:31 +00002403 // We skip out of inline namespaces. The innermost non-inline namespace
2404 // contains all names of all its nested inline namespaces anyway, so we can
2405 // replace the entire inline namespace tree with its root.
2406 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2407 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002408 Ctx = Ctx->getParent();
2409
John McCallc7e8e792009-08-07 22:18:02 +00002410 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002411 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002412}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002413
Mike Stump11289f42009-09-09 15:08:12 +00002414// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002415// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002416static void
John McCallf24d7bb2010-05-28 18:45:08 +00002417addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2418 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002419 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002420 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002421 switch (Arg.getKind()) {
2422 case TemplateArgument::Null:
2423 break;
Mike Stump11289f42009-09-09 15:08:12 +00002424
Douglas Gregor197e5f72009-07-08 07:51:57 +00002425 case TemplateArgument::Type:
2426 // [...] the namespaces and classes associated with the types of the
2427 // template arguments provided for template type parameters (excluding
2428 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002429 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002430 break;
Mike Stump11289f42009-09-09 15:08:12 +00002431
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002433 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002434 // [...] the namespaces in which any template template arguments are
2435 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002436 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002437 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002438 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002439 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002440 DeclContext *Ctx = ClassTemplate->getDeclContext();
2441 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002442 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002443 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002444 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002445 }
2446 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002449 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002450 case TemplateArgument::Integral:
2451 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002452 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002453 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002454 // associated namespaces. ]
2455 break;
Mike Stump11289f42009-09-09 15:08:12 +00002456
Douglas Gregor197e5f72009-07-08 07:51:57 +00002457 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002458 for (const auto &P : Arg.pack_elements())
2459 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002460 break;
2461 }
2462}
2463
Douglas Gregore254f902009-02-04 00:32:51 +00002464// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002465// argument-dependent lookup with an argument of class type
2466// (C++ [basic.lookup.koenig]p2).
2467static void
John McCallf24d7bb2010-05-28 18:45:08 +00002468addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2469 CXXRecordDecl *Class) {
2470
2471 // Just silently ignore anything whose name is __va_list_tag.
2472 if (Class->getDeclName() == Result.S.VAListTagName)
2473 return;
2474
Douglas Gregore254f902009-02-04 00:32:51 +00002475 // C++ [basic.lookup.koenig]p2:
2476 // [...]
2477 // -- If T is a class type (including unions), its associated
2478 // classes are: the class itself; the class of which it is a
2479 // member, if any; and its direct and indirect base
2480 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002481 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002482
2483 // Add the class of which it is a member, if any.
2484 DeclContext *Ctx = Class->getDeclContext();
2485 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002486 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002487 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002488 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002489
Douglas Gregore254f902009-02-04 00:32:51 +00002490 // Add the class itself. If we've already seen this class, we don't
2491 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002492 //
2493 // FIXME: That's not correct, we may have added this class only because it
2494 // was the enclosing class of another class, and in that case we won't have
2495 // added its base classes yet.
Richard Smith6642bb32016-03-24 19:12:22 +00002496 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002497 return;
2498
Mike Stump11289f42009-09-09 15:08:12 +00002499 // -- If T is a template-id, its associated namespaces and classes are
2500 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002501 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002502 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002503 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002504 // namespaces in which any template template arguments are defined; and
2505 // the classes in which any member templates used as template template
2506 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002507 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002508 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002509 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2510 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2511 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002512 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002513 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002514 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregor197e5f72009-07-08 07:51:57 +00002516 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2517 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002518 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002519 }
Mike Stump11289f42009-09-09 15:08:12 +00002520
John McCall67da35c2010-02-04 22:26:26 +00002521 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002522 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2523 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002524 return;
John McCall67da35c2010-02-04 22:26:26 +00002525
Douglas Gregore254f902009-02-04 00:32:51 +00002526 // Add direct and indirect base classes along with their associated
2527 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002528 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002529 Bases.push_back(Class);
2530 while (!Bases.empty()) {
2531 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002532 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002533
2534 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002535 for (const auto &Base : Class->bases()) {
2536 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002537 // In dependent contexts, we do ADL twice, and the first time around,
2538 // the base type might be a dependent TemplateSpecializationType, or a
2539 // TemplateTypeParmType. If that happens, simply ignore it.
2540 // FIXME: If we want to support export, we probably need to add the
2541 // namespace of the template in a TemplateSpecializationType, or even
2542 // the classes and namespaces of known non-dependent arguments.
2543 if (!BaseType)
2544 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002545 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6642bb32016-03-24 19:12:22 +00002546 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002547 // Find the associated namespace for this base class.
2548 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002549 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002550
2551 // Make sure we visit the bases of this base class.
2552 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2553 Bases.push_back(BaseDecl);
2554 }
2555 }
2556 }
2557}
2558
2559// \brief Add the associated classes and namespaces for
2560// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002561// (C++ [basic.lookup.koenig]p2).
2562static void
John McCallf24d7bb2010-05-28 18:45:08 +00002563addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002564 // C++ [basic.lookup.koenig]p2:
2565 //
2566 // For each argument type T in the function call, there is a set
2567 // of zero or more associated namespaces and a set of zero or more
2568 // associated classes to be considered. The sets of namespaces and
2569 // classes is determined entirely by the types of the function
2570 // arguments (and the namespace of any template template
2571 // argument). Typedef names and using-declarations used to specify
2572 // the types do not contribute to this set. The sets of namespaces
2573 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002574
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002575 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002576 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2577
Douglas Gregore254f902009-02-04 00:32:51 +00002578 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002579 switch (T->getTypeClass()) {
2580
2581#define TYPE(Class, Base)
2582#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2583#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2584#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2585#define ABSTRACT_TYPE(Class, Base)
2586#include "clang/AST/TypeNodes.def"
2587 // T is canonical. We can also ignore dependent types because
2588 // we don't need to do ADL at the definition point, but if we
2589 // wanted to implement template export (or if we find some other
2590 // use for associated classes and namespaces...) this would be
2591 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002592 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002593
John McCall0af3d3b2010-05-28 06:08:54 +00002594 // -- If T is a pointer to U or an array of U, its associated
2595 // namespaces and classes are those associated with U.
2596 case Type::Pointer:
2597 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2598 continue;
2599 case Type::ConstantArray:
2600 case Type::IncompleteArray:
2601 case Type::VariableArray:
2602 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2603 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002604
John McCall0af3d3b2010-05-28 06:08:54 +00002605 // -- If T is a fundamental type, its associated sets of
2606 // namespaces and classes are both empty.
2607 case Type::Builtin:
2608 break;
2609
2610 // -- If T is a class type (including unions), its associated
2611 // classes are: the class itself; the class of which it is a
2612 // member, if any; and its direct and indirect base
2613 // classes. Its associated namespaces are the namespaces in
2614 // which its associated classes are defined.
2615 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002616 CXXRecordDecl *Class =
2617 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002618 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002619 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002620 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002621
John McCall0af3d3b2010-05-28 06:08:54 +00002622 // -- If T is an enumeration type, its associated namespace is
2623 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002624 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002625 // it has no associated class.
2626 case Type::Enum: {
2627 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002628
John McCall0af3d3b2010-05-28 06:08:54 +00002629 DeclContext *Ctx = Enum->getDeclContext();
2630 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002631 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002632
John McCall0af3d3b2010-05-28 06:08:54 +00002633 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002634 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002635
John McCall0af3d3b2010-05-28 06:08:54 +00002636 break;
2637 }
2638
2639 // -- If T is a function type, its associated namespaces and
2640 // classes are those associated with the function parameter
2641 // types and those associated with the return type.
2642 case Type::FunctionProto: {
2643 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002644 for (const auto &Arg : Proto->param_types())
2645 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002646 // fallthrough
2647 }
2648 case Type::FunctionNoProto: {
2649 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002650 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002651 continue;
2652 }
2653
2654 // -- If T is a pointer to a member function of a class X, its
2655 // associated namespaces and classes are those associated
2656 // with the function parameter types and return type,
2657 // together with those associated with X.
2658 //
2659 // -- If T is a pointer to a data member of class X, its
2660 // associated namespaces and classes are those associated
2661 // with the member type together with those associated with
2662 // X.
2663 case Type::MemberPointer: {
2664 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2665
2666 // Queue up the class type into which this points.
2667 Queue.push_back(MemberPtr->getClass());
2668
2669 // And directly continue with the pointee type.
2670 T = MemberPtr->getPointeeType().getTypePtr();
2671 continue;
2672 }
2673
2674 // As an extension, treat this like a normal pointer.
2675 case Type::BlockPointer:
2676 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2677 continue;
2678
2679 // References aren't covered by the standard, but that's such an
2680 // obvious defect that we cover them anyway.
2681 case Type::LValueReference:
2682 case Type::RValueReference:
2683 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2684 continue;
2685
2686 // These are fundamental types.
2687 case Type::Vector:
2688 case Type::ExtVector:
2689 case Type::Complex:
2690 break;
2691
Richard Smith27d807c2013-04-30 13:56:41 +00002692 // Non-deduced auto types only get here for error cases.
2693 case Type::Auto:
2694 break;
2695
Douglas Gregor8e936662011-04-12 01:02:45 +00002696 // If T is an Objective-C object or interface type, or a pointer to an
2697 // object or interface type, the associated namespace is the global
2698 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002699 case Type::ObjCObject:
2700 case Type::ObjCInterface:
2701 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002702 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002703 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002704
2705 // Atomic types are just wrappers; use the associations of the
2706 // contained type.
2707 case Type::Atomic:
2708 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2709 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002710 case Type::Pipe:
2711 T = cast<PipeType>(T)->getElementType().getTypePtr();
2712 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002713 }
2714
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002715 if (Queue.empty())
2716 break;
2717 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002718 }
Douglas Gregore254f902009-02-04 00:32:51 +00002719}
2720
2721/// \brief Find the associated classes and namespaces for
2722/// argument-dependent lookup for a call with the given set of
2723/// arguments.
2724///
2725/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002726/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002727/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002728void Sema::FindAssociatedClassesAndNamespaces(
2729 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2730 AssociatedNamespaceSet &AssociatedNamespaces,
2731 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002732 AssociatedNamespaces.clear();
2733 AssociatedClasses.clear();
2734
John McCall7d8b0412012-08-24 20:38:34 +00002735 AssociatedLookup Result(*this, InstantiationLoc,
2736 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002737
Douglas Gregore254f902009-02-04 00:32:51 +00002738 // C++ [basic.lookup.koenig]p2:
2739 // For each argument type T in the function call, there is a set
2740 // of zero or more associated namespaces and a set of zero or more
2741 // associated classes to be considered. The sets of namespaces and
2742 // classes is determined entirely by the types of the function
2743 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002744 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002745 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002746 Expr *Arg = Args[ArgIdx];
2747
2748 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002749 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002750 continue;
2751 }
2752
2753 // [...] In addition, if the argument is the name or address of a
2754 // set of overloaded functions and/or function templates, its
2755 // associated classes and namespaces are the union of those
2756 // associated with each of the members of the set: the namespace
2757 // in which the function or function template is defined and the
2758 // classes and namespaces associated with its (non-dependent)
2759 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002760 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002761 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002762 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002763 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002764
John McCallf24d7bb2010-05-28 18:45:08 +00002765 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2766 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002767
Aaron Ballman1e606f42014-07-15 22:03:49 +00002768 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002769 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002770 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002771
2772 // Add the classes and namespaces associated with the parameter
2773 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002774 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002775 }
2776 }
2777}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002778
John McCall5cebab12009-11-18 07:57:50 +00002779NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002780 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002781 LookupNameKind NameKind,
2782 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002783 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002784 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002785 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002786}
2787
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002788/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002789ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002790 SourceLocation IdLoc,
2791 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002792 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002793 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002794 return cast_or_null<ObjCProtocolDecl>(D);
2795}
2796
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002797void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002798 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002799 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002800 // C++ [over.match.oper]p3:
2801 // -- The set of non-member candidates is the result of the
2802 // unqualified lookup of operator@ in the context of the
2803 // expression according to the usual rules for name lookup in
2804 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002805 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002806 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002807 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2808 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002809
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002810 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002811 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002812}
2813
Alexis Hunt1da39282011-06-24 02:11:39 +00002814Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002815 CXXSpecialMember SM,
2816 bool ConstArg,
2817 bool VolatileArg,
2818 bool RValueThis,
2819 bool ConstThis,
2820 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002821 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002822 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002823 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002824 if (RValueThis || ConstThis || VolatileThis)
2825 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2826 "constructors and destructors always have unqualified lvalue this");
2827 if (ConstArg || VolatileArg)
2828 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2829 "parameter-less special members can't have qualified arguments");
2830
2831 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002832 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002833 ID.AddInteger(SM);
2834 ID.AddInteger(ConstArg);
2835 ID.AddInteger(VolatileArg);
2836 ID.AddInteger(RValueThis);
2837 ID.AddInteger(ConstThis);
2838 ID.AddInteger(VolatileThis);
2839
2840 void *InsertPoint;
2841 SpecialMemberOverloadResult *Result =
2842 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2843
2844 // This was already cached
2845 if (Result)
2846 return Result;
2847
Alexis Huntba8e18d2011-06-07 00:11:58 +00002848 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2849 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002850 SpecialMemberCache.InsertNode(Result, InsertPoint);
2851
2852 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002853 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002854 DeclareImplicitDestructor(RD);
2855 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002856 assert(DD && "record without a destructor");
2857 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002858 Result->setKind(DD->isDeleted() ?
2859 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002860 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002861 return Result;
2862 }
2863
Alexis Hunteef8ee02011-06-10 03:50:41 +00002864 // Prepare for overload resolution. Here we construct a synthetic argument
2865 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002866 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002867 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002868 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002869 unsigned NumArgs;
2870
Richard Smith83c478d2012-04-20 18:46:14 +00002871 QualType ArgType = CanTy;
2872 ExprValueKind VK = VK_LValue;
2873
Alexis Hunteef8ee02011-06-10 03:50:41 +00002874 if (SM == CXXDefaultConstructor) {
2875 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2876 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002877 if (RD->needsImplicitDefaultConstructor())
2878 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002879 } else {
2880 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2881 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002882 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002883 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002884 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002885 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002886 } else {
2887 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002888 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002889 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002890 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002891 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002892 }
2893
Alexis Hunteef8ee02011-06-10 03:50:41 +00002894 if (ConstArg)
2895 ArgType.addConst();
2896 if (VolatileArg)
2897 ArgType.addVolatile();
2898
2899 // This isn't /really/ specified by the standard, but it's implied
2900 // we should be working from an RValue in the case of move to ensure
2901 // that we prefer to bind to rvalue references, and an LValue in the
2902 // case of copy to ensure we don't bind to rvalue references.
2903 // Possibly an XValue is actually correct in the case of move, but
2904 // there is no semantic difference for class types in this restricted
2905 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002906 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002907 VK = VK_LValue;
2908 else
2909 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002910 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002911
Richard Smith83c478d2012-04-20 18:46:14 +00002912 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2913
2914 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002915 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002916 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002917 }
2918
2919 // Create the object argument
2920 QualType ThisTy = CanTy;
2921 if (ConstThis)
2922 ThisTy.addConst();
2923 if (VolatileThis)
2924 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002925 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002926 OpaqueValueExpr(SourceLocation(), ThisTy,
2927 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002928
2929 // Now we perform lookup on the name we computed earlier and do overload
2930 // resolution. Lookup is only performed directly into the class since there
2931 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002932 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002933 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002934
2935 if (R.empty()) {
2936 // We might have no default constructor because we have a lambda's closure
2937 // type, rather than because there's some other declared constructor.
2938 // Every class has a copy/move constructor, copy/move assignment, and
2939 // destructor.
2940 assert(SM == CXXDefaultConstructor &&
2941 "lookup for a constructor or assignment operator was empty");
2942 Result->setMethod(nullptr);
2943 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2944 return Result;
2945 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002946
2947 // Copy the candidates as our processing of them may load new declarations
2948 // from an external source and invalidate lookup_result.
2949 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2950
Richard Smith5179eb72016-06-28 19:03:57 +00002951 for (NamedDecl *CandDecl : Candidates) {
2952 if (CandDecl->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002953 continue;
2954
Richard Smith5179eb72016-06-28 19:03:57 +00002955 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
2956 auto CtorInfo = getConstructorInfo(Cand);
2957 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002958 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Richard Smith5179eb72016-06-28 19:03:57 +00002959 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
2960 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2961 else if (CtorInfo)
2962 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002963 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002964 else
Richard Smith5179eb72016-06-28 19:03:57 +00002965 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
2966 true);
2967 } else if (FunctionTemplateDecl *Tmpl =
2968 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
2969 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2970 AddMethodTemplateCandidate(
2971 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
2972 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2973 else if (CtorInfo)
2974 AddTemplateOverloadCandidate(
2975 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
2976 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2977 else
2978 AddTemplateOverloadCandidate(
2979 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002980 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00002981 assert(isa<UsingDecl>(Cand.getDecl()) &&
2982 "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002983 }
2984 }
2985
2986 OverloadCandidateSet::iterator Best;
2987 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2988 case OR_Success:
2989 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002990 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002991 break;
2992
2993 case OR_Deleted:
2994 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002995 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002996 break;
2997
2998 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002999 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003000 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3001 break;
3002
Alexis Hunteef8ee02011-06-10 03:50:41 +00003003 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00003004 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003005 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003006 break;
3007 }
3008
3009 return Result;
3010}
3011
3012/// \brief Look up the default constructor for the given class.
3013CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003014 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00003015 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3016 false, false);
3017
3018 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003019}
3020
Alexis Hunt491ec602011-06-21 23:42:56 +00003021/// \brief Look up the copying constructor for the given class.
3022CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00003023 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003024 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3025 "non-const, non-volatile qualifiers for copy ctor arg");
3026 SpecialMemberOverloadResult *Result =
3027 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3028 Quals & Qualifiers::Volatile, false, false, false);
3029
Alexis Hunt899bd442011-06-10 04:44:37 +00003030 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
3031}
3032
Sebastian Redl22653ba2011-08-30 19:58:05 +00003033/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00003034CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3035 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003036 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003037 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3038 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003039
3040 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
3041}
3042
Douglas Gregor52b72822010-07-02 23:12:18 +00003043/// \brief Look up the constructors for the given class.
3044DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003045 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00003046 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00003047 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003048 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00003049 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003050 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003051 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003052 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054
Douglas Gregor52b72822010-07-02 23:12:18 +00003055 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3056 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3057 return Class->lookup(Name);
3058}
3059
Alexis Hunt491ec602011-06-21 23:42:56 +00003060/// \brief Look up the copying assignment operator for the given class.
3061CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3062 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003063 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003064 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3065 "non-const, non-volatile qualifiers for copy assignment arg");
3066 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3067 "non-const, non-volatile qualifiers for copy assignment this");
3068 SpecialMemberOverloadResult *Result =
3069 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3070 Quals & Qualifiers::Volatile, RValueThis,
3071 ThisQuals & Qualifiers::Const,
3072 ThisQuals & Qualifiers::Volatile);
3073
Alexis Hunt491ec602011-06-21 23:42:56 +00003074 return Result->getMethod();
3075}
3076
Sebastian Redl22653ba2011-08-30 19:58:05 +00003077/// \brief Look up the moving assignment operator for the given class.
3078CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003079 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003080 bool RValueThis,
3081 unsigned ThisQuals) {
3082 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3083 "non-const, non-volatile qualifiers for copy assignment this");
3084 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003085 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3086 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003087 ThisQuals & Qualifiers::Const,
3088 ThisQuals & Qualifiers::Volatile);
3089
3090 return Result->getMethod();
3091}
3092
Douglas Gregore71edda2010-07-01 22:47:18 +00003093/// \brief Look for the destructor of the given class.
3094///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003095/// During semantic analysis, this routine should be used in lieu of
3096/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003097///
3098/// \returns The destructor for this class.
3099CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003100 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3101 false, false, false,
3102 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003103}
3104
Richard Smithbcc22fc2012-03-09 08:00:36 +00003105/// LookupLiteralOperator - Determine which literal operator should be used for
3106/// a user-defined literal, per C++11 [lex.ext].
3107///
3108/// Normal overload resolution is not used to select which literal operator to
3109/// call for a user-defined literal. Look up the provided literal operator name,
3110/// and filter the results to the appropriate set for the given argument types.
3111Sema::LiteralOperatorLookupResult
3112Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3113 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003114 bool AllowRaw, bool AllowTemplate,
3115 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003116 LookupName(R, S);
3117 assert(R.getResultKind() != LookupResult::Ambiguous &&
3118 "literal operator lookup can't be ambiguous");
3119
3120 // Filter the lookup results appropriately.
3121 LookupResult::Filter F = R.makeFilter();
3122
Richard Smithbcc22fc2012-03-09 08:00:36 +00003123 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003124 bool FoundTemplate = false;
3125 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003126 bool FoundExactMatch = false;
3127
3128 while (F.hasNext()) {
3129 Decl *D = F.next();
3130 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3131 D = USD->getTargetDecl();
3132
Douglas Gregorc1970572013-04-10 05:18:00 +00003133 // If the declaration we found is invalid, skip it.
3134 if (D->isInvalidDecl()) {
3135 F.erase();
3136 continue;
3137 }
3138
Richard Smithb8b41d32013-10-07 19:57:58 +00003139 bool IsRaw = false;
3140 bool IsTemplate = false;
3141 bool IsStringTemplate = false;
3142 bool IsExactMatch = false;
3143
Richard Smithbcc22fc2012-03-09 08:00:36 +00003144 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3145 if (FD->getNumParams() == 1 &&
3146 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3147 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003148 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003149 IsExactMatch = true;
3150 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3151 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3152 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3153 IsExactMatch = false;
3154 break;
3155 }
3156 }
3157 }
3158 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003159 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3160 TemplateParameterList *Params = FD->getTemplateParameters();
3161 if (Params->size() == 1)
3162 IsTemplate = true;
3163 else
3164 IsStringTemplate = true;
3165 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003166
3167 if (IsExactMatch) {
3168 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003169 AllowRaw = false;
3170 AllowTemplate = false;
3171 AllowStringTemplate = false;
3172 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003173 // Go through again and remove the raw and template decls we've
3174 // already found.
3175 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003176 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003177 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003178 } else if (AllowRaw && IsRaw) {
3179 FoundRaw = true;
3180 } else if (AllowTemplate && IsTemplate) {
3181 FoundTemplate = true;
3182 } else if (AllowStringTemplate && IsStringTemplate) {
3183 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003184 } else {
3185 F.erase();
3186 }
3187 }
3188
3189 F.done();
3190
3191 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3192 // parameter type, that is used in preference to a raw literal operator
3193 // or literal operator template.
3194 if (FoundExactMatch)
3195 return LOLR_Cooked;
3196
3197 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3198 // operator template, but not both.
3199 if (FoundRaw && FoundTemplate) {
3200 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003201 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Richard Smithc2bebe92016-05-11 20:37:46 +00003202 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003203 return LOLR_Error;
3204 }
3205
3206 if (FoundRaw)
3207 return LOLR_Raw;
3208
3209 if (FoundTemplate)
3210 return LOLR_Template;
3211
Richard Smithb8b41d32013-10-07 19:57:58 +00003212 if (FoundStringTemplate)
3213 return LOLR_StringTemplate;
3214
Richard Smithbcc22fc2012-03-09 08:00:36 +00003215 // Didn't find anything we could use.
3216 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3217 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00003218 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3219 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003220 return LOLR_Error;
3221}
3222
John McCall8fe68082010-01-26 07:16:45 +00003223void ADLResult::insert(NamedDecl *New) {
3224 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3225
3226 // If we haven't yet seen a decl for this key, or the last decl
3227 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003228 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003229 Old = New;
3230 return;
3231 }
3232
3233 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003234 FunctionDecl *OldFD = Old->getAsFunction();
3235 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003236
3237 FunctionDecl *Cursor = NewFD;
3238 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003239 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003240
3241 // If we got to the end without finding OldFD, OldFD is the newer
3242 // declaration; leave things as they are.
3243 if (!Cursor) return;
3244
3245 // If we do find OldFD, then NewFD is newer.
3246 if (Cursor == OldFD) break;
3247
3248 // Otherwise, keep looking.
3249 }
3250
3251 Old = New;
3252}
3253
Richard Smith100b24a2014-04-17 01:52:14 +00003254void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3255 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003256 // Find all of the associated namespaces and classes based on the
3257 // arguments we have.
3258 AssociatedNamespaceSet AssociatedNamespaces;
3259 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003260 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003261 AssociatedNamespaces,
3262 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003263
3264 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003265 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3266 // and let Y be the lookup set produced by argument dependent
3267 // lookup (defined as follows). If X contains [...] then Y is
3268 // empty. Otherwise Y is the set of declarations found in the
3269 // namespaces associated with the argument types as described
3270 // below. The set of declarations found by the lookup of the name
3271 // is the union of X and Y.
3272 //
3273 // Here, we compute Y and add its members to the overloaded
3274 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003275 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003276 // When considering an associated namespace, the lookup is the
3277 // same as the lookup performed when the associated namespace is
3278 // used as a qualifier (3.4.3.2) except that:
3279 //
3280 // -- Any using-directives in the associated namespace are
3281 // ignored.
3282 //
John McCallc7e8e792009-08-07 22:18:02 +00003283 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003284 // associated classes are visible within their respective
3285 // namespaces even if they are not visible during an ordinary
3286 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003287 DeclContext::lookup_result R = NS->lookup(Name);
3288 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003289 // If the only declaration here is an ordinary friend, consider
3290 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003291 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3292 // If it's neither ordinarily visible nor a friend, we can't find it.
3293 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3294 continue;
3295
Richard Smith64017682013-07-17 23:53:16 +00003296 bool DeclaredInAssociatedClass = false;
3297 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3298 DeclContext *LexDC = DI->getLexicalDeclContext();
3299 if (isa<CXXRecordDecl>(LexDC) &&
Richard Smith82b8d4e2015-12-18 22:19:11 +00003300 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3301 isVisible(cast<NamedDecl>(DI))) {
Richard Smith64017682013-07-17 23:53:16 +00003302 DeclaredInAssociatedClass = true;
3303 break;
3304 }
3305 }
3306 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003307 continue;
3308 }
Mike Stump11289f42009-09-09 15:08:12 +00003309
John McCall91f61fc2010-01-26 06:04:06 +00003310 if (isa<UsingShadowDecl>(D))
3311 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003312
Richard Smith100b24a2014-04-17 01:52:14 +00003313 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003314 continue;
3315
Richard Smitha1431072015-06-12 01:32:13 +00003316 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3317 continue;
3318
John McCall8fe68082010-01-26 07:16:45 +00003319 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003320 }
3321 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003322}
Douglas Gregor2d435302009-12-30 17:04:44 +00003323
3324//----------------------------------------------------------------------------
3325// Search for all visible declarations.
3326//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003327VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003328
Richard Smithe156254d2013-08-20 20:35:18 +00003329bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3330
Douglas Gregor2d435302009-12-30 17:04:44 +00003331namespace {
3332
3333class ShadowContextRAII;
3334
3335class VisibleDeclsRecord {
3336public:
3337 /// \brief An entry in the shadow map, which is optimized to store a
3338 /// single declaration (the common case) but can also store a list
3339 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003340 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003341
3342private:
3343 /// \brief A mapping from declaration names to the declarations that have
3344 /// this name within a particular scope.
3345 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3346
3347 /// \brief A list of shadow maps, which is used to model name hiding.
3348 std::list<ShadowMap> ShadowMaps;
3349
3350 /// \brief The declaration contexts we have already visited.
3351 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3352
3353 friend class ShadowContextRAII;
3354
3355public:
3356 /// \brief Determine whether we have already visited this context
3357 /// (and, if not, note that we are going to visit that context now).
3358 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003359 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003360 }
3361
Douglas Gregor39982192010-08-15 06:18:01 +00003362 bool alreadyVisitedContext(DeclContext *Ctx) {
3363 return VisitedContexts.count(Ctx);
3364 }
3365
Douglas Gregor2d435302009-12-30 17:04:44 +00003366 /// \brief Determine whether the given declaration is hidden in the
3367 /// current scope.
3368 ///
3369 /// \returns the declaration that hides the given declaration, or
3370 /// NULL if no such declaration exists.
3371 NamedDecl *checkHidden(NamedDecl *ND);
3372
3373 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003374 void add(NamedDecl *ND) {
3375 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3376 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003377};
3378
3379/// \brief RAII object that records when we've entered a shadow context.
3380class ShadowContextRAII {
3381 VisibleDeclsRecord &Visible;
3382
3383 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3384
3385public:
3386 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003387 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003388 }
3389
3390 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003391 Visible.ShadowMaps.pop_back();
3392 }
3393};
3394
3395} // end anonymous namespace
3396
Douglas Gregor2d435302009-12-30 17:04:44 +00003397NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3398 unsigned IDNS = ND->getIdentifierNamespace();
3399 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3400 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3401 SM != SMEnd; ++SM) {
3402 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3403 if (Pos == SM->end())
3404 continue;
3405
Aaron Ballman1e606f42014-07-15 22:03:49 +00003406 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003407 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003408 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003410 Decl::IDNS_ObjCProtocol)))
3411 continue;
3412
3413 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003414 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003415 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003416 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003417 continue;
3418
Douglas Gregor09bbc652010-01-14 15:47:35 +00003419 // Functions and function templates in the same scope overload
3420 // rather than hide. FIXME: Look for hiding based on function
3421 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003422 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003423 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003424 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003425 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Douglas Gregor2d435302009-12-30 17:04:44 +00003427 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003428 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003429 }
3430 }
3431
Craig Topperc3ec1492014-05-26 06:22:03 +00003432 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003433}
3434
3435static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3436 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003437 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003438 VisibleDeclConsumer &Consumer,
3439 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003440 if (!Ctx)
3441 return;
3442
Douglas Gregor2d435302009-12-30 17:04:44 +00003443 // Make sure we don't visit the same context twice.
3444 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3445 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446
Richard Smith9e2341d2015-03-23 03:25:59 +00003447 // Outside C++, lookup results for the TU live on identifiers.
3448 if (isa<TranslationUnitDecl>(Ctx) &&
3449 !Result.getSema().getLangOpts().CPlusPlus) {
3450 auto &S = Result.getSema();
3451 auto &Idents = S.Context.Idents;
3452
3453 // Ensure all external identifiers are in the identifier table.
3454 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3455 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3456 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3457 Idents.get(Name);
3458 }
3459
3460 // Walk all lookup results in the TU for each identifier.
3461 for (const auto &Ident : Idents) {
3462 for (auto I = S.IdResolver.begin(Ident.getValue()),
3463 E = S.IdResolver.end();
3464 I != E; ++I) {
3465 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3466 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3467 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3468 Visited.add(ND);
3469 }
3470 }
3471 }
3472 }
3473
3474 return;
3475 }
3476
Douglas Gregor7454c562010-07-02 20:37:36 +00003477 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3478 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3479
Douglas Gregor2d435302009-12-30 17:04:44 +00003480 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003481 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003482 for (auto *D : R) {
3483 if (auto *ND = Result.getAcceptableDecl(D)) {
3484 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3485 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003486 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003487 }
3488 }
3489
3490 // Traverse using directives for qualified name lookup.
3491 if (QualifiedNameLookup) {
3492 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003493 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003494 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003495 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003496 }
3497 }
3498
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003499 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003500 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003501 if (!Record->hasDefinition())
3502 return;
3503
Aaron Ballman574705e2014-03-13 15:41:46 +00003504 for (const auto &B : Record->bases()) {
3505 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregor2d435302009-12-30 17:04:44 +00003507 // Don't look into dependent bases, because name lookup can't look
3508 // there anyway.
3509 if (BaseType->isDependentType())
3510 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511
Douglas Gregor2d435302009-12-30 17:04:44 +00003512 const RecordType *Record = BaseType->getAs<RecordType>();
3513 if (!Record)
3514 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515
Douglas Gregor2d435302009-12-30 17:04:44 +00003516 // FIXME: It would be nice to be able to determine whether referencing
3517 // a particular member would be ambiguous. For example, given
3518 //
3519 // struct A { int member; };
3520 // struct B { int member; };
3521 // struct C : A, B { };
3522 //
3523 // void f(C *c) { c->### }
3524 //
3525 // accessing 'member' would result in an ambiguity. However, we
3526 // could be smart enough to qualify the member with the base
3527 // class, e.g.,
3528 //
3529 // c->B::member
3530 //
3531 // or
3532 //
3533 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregor2d435302009-12-30 17:04:44 +00003535 // Find results in this base class (and its bases).
3536 ShadowContextRAII Shadow(Visited);
3537 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003538 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003539 }
3540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003542 // Traverse the contexts of Objective-C classes.
3543 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3544 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003545 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003546 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003547 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003548 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003549 }
3550
3551 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003552 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003553 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003554 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003555 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003556 }
3557
3558 // Traverse the superclass.
3559 if (IFace->getSuperClass()) {
3560 ShadowContextRAII Shadow(Visited);
3561 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003562 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564
Douglas Gregor0b59e802010-04-19 18:02:19 +00003565 // If there is an implementation, traverse it. We do this to find
3566 // synthesized ivars.
3567 if (IFace->getImplementation()) {
3568 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003570 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003571 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003572 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003573 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003574 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003575 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003576 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003577 }
3578 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003579 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003580 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003581 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003582 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
Douglas Gregor0b59e802010-04-19 18:02:19 +00003585 // If there is an implementation, traverse it.
3586 if (Category->getImplementation()) {
3587 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003589 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003591 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003592}
3593
3594static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3595 UnqualUsingDirectiveSet &UDirs,
3596 VisibleDeclConsumer &Consumer,
3597 VisibleDeclsRecord &Visited) {
3598 if (!S)
3599 return;
3600
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601 if (!S->getEntity() ||
3602 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003603 !Visited.alreadyVisitedContext(S->getEntity())) ||
3604 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003605 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003606 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003607 for (auto *D : S->decls()) {
3608 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003609 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003610 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003611 Visited.add(ND);
3612 }
3613 }
3614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Douglas Gregor66230062010-03-15 14:33:29 +00003616 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003617 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003618 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003619 // Look into this scope's declaration context, along with any of its
3620 // parent lookup contexts (e.g., enclosing classes), up to the point
3621 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003622 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003623 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624
Douglas Gregorea166062010-03-15 15:26:48 +00003625 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003626 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003627 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3628 if (Method->isInstanceMethod()) {
3629 // For instance methods, look for ivars in the method's interface.
3630 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3631 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003632 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003633 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003634 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003635 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003636 }
3637
3638 // We've already performed all of the name lookup that we need
3639 // to for Objective-C methods; the next context will be the
3640 // outer scope.
3641 break;
3642 }
3643
Douglas Gregor2d435302009-12-30 17:04:44 +00003644 if (Ctx->isFunctionOrMethod())
3645 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
3647 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003648 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003649 }
3650 } else if (!S->getParent()) {
3651 // Look into the translation unit scope. We walk through the translation
3652 // unit's declaration context, because the Scope itself won't have all of
3653 // the declarations if we loaded a precompiled header.
3654 // FIXME: We would like the translation unit's Scope object to point to the
3655 // translation unit, so we don't need this special "if" branch. However,
3656 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003658 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003659 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003660 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003661 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003662 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663 }
3664
Douglas Gregor2d435302009-12-30 17:04:44 +00003665 if (Entity) {
3666 // Lookup visible declarations in any namespaces found by using
3667 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003668 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3669 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003671 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003672 }
3673
3674 // Lookup names in the parent scope.
3675 ShadowContextRAII Shadow(Visited);
3676 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3677}
3678
3679void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003680 VisibleDeclConsumer &Consumer,
3681 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003682 // Determine the set of using directives available during
3683 // unqualified name lookup.
3684 Scope *Initial = S;
3685 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003686 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003687 // Find the first namespace or translation-unit scope.
3688 while (S && !isNamespaceOrTranslationUnitScope(S))
3689 S = S->getParent();
3690
3691 UDirs.visitScopeChain(Initial, S);
3692 }
3693 UDirs.done();
3694
3695 // Look for visible declarations.
3696 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003697 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003698 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003699 if (!IncludeGlobalScope)
3700 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003701 ShadowContextRAII Shadow(Visited);
3702 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3703}
3704
3705void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003706 VisibleDeclConsumer &Consumer,
3707 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003708 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003709 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003710 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003711 if (!IncludeGlobalScope)
3712 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003713 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003715 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003716}
3717
Chris Lattner43e7f312011-02-18 02:08:43 +00003718/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003719/// If GnuLabelLoc is a valid source location, then this is a definition
3720/// of an __label__ label name, otherwise it is a normal label definition
3721/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003722LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003723 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003724 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003725 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003726
3727 if (GnuLabelLoc.isValid()) {
3728 // Local label definitions always shadow existing labels.
3729 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3730 Scope *S = CurScope;
3731 PushOnScopeChains(Res, S, true);
3732 return cast<LabelDecl>(Res);
3733 }
3734
3735 // Not a GNU local label.
3736 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3737 // If we found a label, check to see if it is in the same context as us.
3738 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003739 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003740 Res = nullptr;
3741 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003742 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003743 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3744 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003745 assert(S && "Not in a function?");
3746 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003747 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003748 return cast<LabelDecl>(Res);
3749}
3750
3751//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003752// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003753//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003754
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003755static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3756 TypoCorrection &Candidate) {
3757 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3758 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3759}
3760
3761static void LookupPotentialTypoResult(Sema &SemaRef,
3762 LookupResult &Res,
3763 IdentifierInfo *Name,
3764 Scope *S, CXXScopeSpec *SS,
3765 DeclContext *MemberContext,
3766 bool EnteringContext,
3767 bool isObjCIvarLookup,
3768 bool FindHidden);
3769
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003770/// \brief Check whether the declarations found for a typo correction are
3771/// visible, and if none of them are, convert the correction to an 'import
3772/// a module' correction.
3773static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3774 if (TC.begin() == TC.end())
3775 return;
3776
3777 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3778
3779 for (/**/; DI != DE; ++DI)
3780 if (!LookupResult::isVisible(SemaRef, *DI))
3781 break;
3782 // Nothing to do if all decls are visible.
3783 if (DI == DE)
3784 return;
3785
3786 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3787 bool AnyVisibleDecls = !NewDecls.empty();
3788
3789 for (/**/; DI != DE; ++DI) {
3790 NamedDecl *VisibleDecl = *DI;
3791 if (!LookupResult::isVisible(SemaRef, *DI))
3792 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3793
3794 if (VisibleDecl) {
3795 if (!AnyVisibleDecls) {
3796 // Found a visible decl, discard all hidden ones.
3797 AnyVisibleDecls = true;
3798 NewDecls.clear();
3799 }
3800 NewDecls.push_back(VisibleDecl);
3801 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3802 NewDecls.push_back(*DI);
3803 }
3804
3805 if (NewDecls.empty())
3806 TC = TypoCorrection();
3807 else {
3808 TC.setCorrectionDecls(NewDecls);
3809 TC.setRequiresImport(!AnyVisibleDecls);
3810 }
3811}
3812
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003813// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3814// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3815// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3816static void getNestedNameSpecifierIdentifiers(
3817 NestedNameSpecifier *NNS,
3818 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3819 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3820 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3821 else
3822 Identifiers.clear();
3823
3824 const IdentifierInfo *II = nullptr;
3825
3826 switch (NNS->getKind()) {
3827 case NestedNameSpecifier::Identifier:
3828 II = NNS->getAsIdentifier();
3829 break;
3830
3831 case NestedNameSpecifier::Namespace:
3832 if (NNS->getAsNamespace()->isAnonymousNamespace())
3833 return;
3834 II = NNS->getAsNamespace()->getIdentifier();
3835 break;
3836
3837 case NestedNameSpecifier::NamespaceAlias:
3838 II = NNS->getAsNamespaceAlias()->getIdentifier();
3839 break;
3840
3841 case NestedNameSpecifier::TypeSpecWithTemplate:
3842 case NestedNameSpecifier::TypeSpec:
3843 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3844 break;
3845
3846 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003847 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003848 return;
3849 }
3850
3851 if (II)
3852 Identifiers.push_back(II);
3853}
3854
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003855void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003856 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003857 // Don't consider hidden names for typo correction.
3858 if (Hiding)
3859 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860
Douglas Gregor2d435302009-12-30 17:04:44 +00003861 // Only consider entities with identifiers for names, ignoring
3862 // special names (constructors, overloaded operators, selectors,
3863 // etc.).
3864 IdentifierInfo *Name = ND->getIdentifier();
3865 if (!Name)
3866 return;
3867
Richard Smithe156254d2013-08-20 20:35:18 +00003868 // Only consider visible declarations and declarations from modules with
3869 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003870 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003871 !findAcceptableDecl(SemaRef, ND))
3872 return;
3873
Douglas Gregor57756ea2010-10-14 22:11:03 +00003874 FoundName(Name->getName());
3875}
3876
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003877void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003878 // Compute the edit distance between the typo and the name of this
3879 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003880 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003881}
3882
3883void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3884 // Compute the edit distance between the typo and this keyword,
3885 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003886 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003887}
3888
3889void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3890 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003891 // Use a simple length-based heuristic to determine the minimum possible
3892 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003893 StringRef TypoStr = Typo->getName();
3894 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3895 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003896 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003898 // Compute an upper bound on the allowable edit distance, so that the
3899 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003900 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3901 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003902 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003903
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003904 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003905 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003906 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003907 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003908}
3909
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003910static const unsigned MaxTypoDistanceResultSets = 5;
3911
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003912void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003913 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003914 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003915
3916 // For very short typos, ignore potential corrections that have a different
3917 // base identifier from the typo or which have a normalized edit distance
3918 // longer than the typo itself.
3919 if (TypoStr.size() < 3 &&
3920 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3921 return;
3922
3923 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003924 if (Correction.isResolved()) {
3925 checkCorrectionVisibility(SemaRef, Correction);
3926 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3927 return;
3928 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003929
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003930 TypoResultList &CList =
3931 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003932
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003933 if (!CList.empty() && !CList.back().isResolved())
3934 CList.pop_back();
3935 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3936 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3937 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3938 RI != RIEnd; ++RI) {
3939 // If the Correction refers to a decl already in the result list,
3940 // replace the existing result if the string representation of Correction
3941 // comes before the current result alphabetically, then stop as there is
3942 // nothing more to be done to add Correction to the candidate set.
3943 if (RI->getCorrectionDecl() == NewND) {
3944 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3945 *RI = Correction;
3946 return;
3947 }
3948 }
3949 }
3950 if (CList.empty() || Correction.isResolved())
3951 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003952
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003953 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003954 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3955}
3956
3957void TypoCorrectionConsumer::addNamespaces(
3958 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3959 SearchNamespaces = true;
3960
3961 for (auto KNPair : KnownNamespaces)
3962 Namespaces.addNameSpecifier(KNPair.first);
3963
3964 bool SSIsTemplate = false;
3965 if (NestedNameSpecifier *NNS =
3966 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3967 if (const Type *T = NNS->getAsType())
3968 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3969 }
Richard Smith2a40fb72015-11-18 01:19:02 +00003970 // Do not transform this into an iterator-based loop. The loop body can
3971 // trigger the creation of further types (through lazy deserialization) and
3972 // invalide iterators into this list.
3973 auto &Types = SemaRef.getASTContext().getTypes();
3974 for (unsigned I = 0; I != Types.size(); ++I) {
3975 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003976 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3977 CD = CD->getCanonicalDecl();
3978 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3979 !CD->isUnion() && CD->getIdentifier() &&
3980 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3981 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3982 Namespaces.addNameSpecifier(CD);
3983 }
3984 }
3985}
3986
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003987const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3988 if (++CurrentTCIndex < ValidatedCorrections.size())
3989 return ValidatedCorrections[CurrentTCIndex];
3990
3991 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003992 while (!CorrectionResults.empty()) {
3993 auto DI = CorrectionResults.begin();
3994 if (DI->second.empty()) {
3995 CorrectionResults.erase(DI);
3996 continue;
3997 }
3998
3999 auto RI = DI->second.begin();
4000 if (RI->second.empty()) {
4001 DI->second.erase(RI);
4002 performQualifiedLookups();
4003 continue;
4004 }
4005
4006 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004007 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004008 ValidatedCorrections.push_back(TC);
4009 return ValidatedCorrections[CurrentTCIndex];
4010 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004011 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004012 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004013}
4014
4015bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4016 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4017 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004018 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004019retry_lookup:
4020 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4021 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004022 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004023 Name == Typo && !Candidate.WillReplaceSpecifier());
4024 switch (Result.getResultKind()) {
4025 case LookupResult::NotFound:
4026 case LookupResult::NotFoundInCurrentInstantiation:
4027 case LookupResult::FoundUnresolvedValue:
4028 if (TempSS) {
4029 // Immediately retry the lookup without the given CXXScopeSpec
4030 TempSS = nullptr;
4031 Candidate.WillReplaceSpecifier(true);
4032 goto retry_lookup;
4033 }
4034 if (TempMemberContext) {
4035 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004036 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004037 TempMemberContext = nullptr;
4038 goto retry_lookup;
4039 }
4040 if (SearchNamespaces)
4041 QualifiedResults.push_back(Candidate);
4042 break;
4043
4044 case LookupResult::Ambiguous:
4045 // We don't deal with ambiguities.
4046 break;
4047
4048 case LookupResult::Found:
4049 case LookupResult::FoundOverloaded:
4050 // Store all of the Decls for overloaded symbols
4051 for (auto *TRD : Result)
4052 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004053 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004054 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004055 if (SearchNamespaces)
4056 QualifiedResults.push_back(Candidate);
4057 break;
4058 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004059 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004060 return true;
4061 }
4062 return false;
4063}
4064
4065void TypoCorrectionConsumer::performQualifiedLookups() {
4066 unsigned TypoLen = Typo->getName().size();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00004067 for (const TypoCorrection &QR : QualifiedResults) {
4068 for (const auto &NSI : Namespaces) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004069 DeclContext *Ctx = NSI.DeclCtx;
4070 const Type *NSType = NSI.NameSpecifier->getAsType();
4071
4072 // If the current NestedNameSpecifier refers to a class and the
4073 // current correction candidate is the name of that class, then skip
4074 // it as it is unlikely a qualified version of the class' constructor
4075 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004076 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4077 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004078 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4079 continue;
4080 }
4081
4082 TypoCorrection TC(QR);
4083 TC.ClearCorrectionDecls();
4084 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4085 TC.setQualifierDistance(NSI.EditDistance);
4086 TC.setCallbackDistance(0); // Reset the callback distance
4087
4088 // If the current correction candidate and namespace combination are
4089 // too far away from the original typo based on the normalized edit
4090 // distance, then skip performing a qualified name lookup.
4091 unsigned TmpED = TC.getEditDistance(true);
4092 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4093 TypoLen / TmpED < 3)
4094 continue;
4095
4096 Result.clear();
4097 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4098 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4099 continue;
4100
4101 // Any corrections added below will be validated in subsequent
4102 // iterations of the main while() loop over the Consumer's contents.
4103 switch (Result.getResultKind()) {
4104 case LookupResult::Found:
4105 case LookupResult::FoundOverloaded: {
4106 if (SS && SS->isValid()) {
4107 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4108 std::string OldQualified;
4109 llvm::raw_string_ostream OldOStream(OldQualified);
4110 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4111 OldOStream << Typo->getName();
4112 // If correction candidate would be an identical written qualified
4113 // identifer, then the existing CXXScopeSpec probably included a
4114 // typedef that didn't get accounted for properly.
4115 if (OldOStream.str() == NewQualified)
4116 break;
4117 }
4118 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4119 TRD != TRDEnd; ++TRD) {
4120 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4121 NSType ? NSType->getAsCXXRecordDecl()
4122 : nullptr,
4123 TRD.getPair()) == Sema::AR_accessible)
4124 TC.addCorrectionDecl(*TRD);
4125 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004126 if (TC.isResolved()) {
4127 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004128 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004129 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004130 break;
4131 }
4132 case LookupResult::NotFound:
4133 case LookupResult::NotFoundInCurrentInstantiation:
4134 case LookupResult::Ambiguous:
4135 case LookupResult::FoundUnresolvedValue:
4136 break;
4137 }
4138 }
4139 }
4140 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004141}
4142
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004143TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4144 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004145 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004146 if (NestedNameSpecifier *NNS =
4147 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4148 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4149 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4150
4151 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4152 }
4153 // Build the list of identifiers that would be used for an absolute
4154 // (from the global context) NestedNameSpecifier referring to the current
4155 // context.
David Majnemerf7e36092016-06-23 00:15:04 +00004156 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4157 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004158 CurContextIdentifiers.push_back(ND->getIdentifier());
4159 }
4160
4161 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004162 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4163 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4164 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004165}
4166
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004167auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4168 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004169 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004170 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004171 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004172 DC = DC->getLookupParent()) {
4173 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4174 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4175 !(ND && ND->isAnonymousNamespace()))
4176 Chain.push_back(DC->getPrimaryContext());
4177 }
4178 return Chain;
4179}
4180
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004181unsigned
4182TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4183 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004184 unsigned NumSpecifiers = 0;
David Majnemerf7e36092016-06-23 00:15:04 +00004185 for (DeclContext *C : llvm::reverse(DeclChain)) {
4186 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004187 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4188 ++NumSpecifiers;
David Majnemerf7e36092016-06-23 00:15:04 +00004189 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004190 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4191 RD->getTypeForDecl());
4192 ++NumSpecifiers;
4193 }
4194 }
4195 return NumSpecifiers;
4196}
4197
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004198void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4199 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004200 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004201 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004202 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004203 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4204
4205 // Eliminate common elements from the two DeclContext chains.
David Majnemerf7e36092016-06-23 00:15:04 +00004206 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4207 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4208 break;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004209 NamespaceDeclChain.pop_back();
4210 }
4211
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004212 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004213 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004214
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004215 // Add an explicit leading '::' specifier if needed.
4216 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004217 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004218 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004219 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004220 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004221 } else if (NamedDecl *ND =
4222 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004223 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004224 bool SameNameSpecifier = false;
4225 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004226 CurNameSpecifierIdentifiers.end(),
4227 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004228 std::string NewNameSpecifier;
4229 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4230 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4231 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4232 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4233 SpecifierOStream.flush();
4234 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004235 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004236 if (SameNameSpecifier ||
4237 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4238 Name) != CurContextIdentifiers.end()) {
4239 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4240 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4241 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004242 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004243 }
4244 }
4245
4246 // If the built NestedNameSpecifier would be replacing an existing
4247 // NestedNameSpecifier, use the number of component identifiers that
4248 // would need to be changed as the edit distance instead of the number
4249 // of components in the built NestedNameSpecifier.
4250 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4251 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4252 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4253 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004254 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4255 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004256 }
4257
Hans Wennborg66010132014-06-11 21:24:13 +00004258 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4259 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004260}
4261
Douglas Gregord507d772010-10-20 03:06:34 +00004262/// \brief Perform name lookup for a possible result for typo correction.
4263static void LookupPotentialTypoResult(Sema &SemaRef,
4264 LookupResult &Res,
4265 IdentifierInfo *Name,
4266 Scope *S, CXXScopeSpec *SS,
4267 DeclContext *MemberContext,
4268 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004269 bool isObjCIvarLookup,
4270 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004271 Res.suppressDiagnostics();
4272 Res.clear();
4273 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004274 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004276 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004277 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004278 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4279 Res.addDecl(Ivar);
4280 Res.resolveKind();
4281 return;
4282 }
4283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Manman Ren5b786402016-01-28 18:49:28 +00004285 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4286 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004287 Res.addDecl(Prop);
4288 Res.resolveKind();
4289 return;
4290 }
4291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Douglas Gregord507d772010-10-20 03:06:34 +00004293 SemaRef.LookupQualifiedName(Res, MemberContext);
4294 return;
4295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
4297 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004298 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregord507d772010-10-20 03:06:34 +00004300 // Fake ivar lookup; this should really be part of
4301 // LookupParsedName.
4302 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4303 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004305 (Res.isSingleResult() &&
4306 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004308 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4309 Res.addDecl(IV);
4310 Res.resolveKind();
4311 }
4312 }
4313 }
4314}
4315
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004316/// \brief Add keywords to the consumer as possible typo corrections.
4317static void AddKeywordsToConsumer(Sema &SemaRef,
4318 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004319 Scope *S, CorrectionCandidateCallback &CCC,
4320 bool AfterNestedNameSpecifier) {
4321 if (AfterNestedNameSpecifier) {
4322 // For 'X::', we know exactly which keywords can appear next.
4323 Consumer.addKeywordResult("template");
4324 if (CCC.WantExpressionKeywords)
4325 Consumer.addKeywordResult("operator");
4326 return;
4327 }
4328
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004329 if (CCC.WantObjCSuper)
4330 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004331
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004332 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004333 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004334 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004335 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004336 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004337 "_Complex", "_Imaginary",
4338 // storage-specifiers as well
4339 "extern", "inline", "static", "typedef"
4340 };
4341
Craig Toppere5ce8312013-07-15 03:38:40 +00004342 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004343 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4344 Consumer.addKeywordResult(CTypeSpecs[I]);
4345
David Blaikiebbafb8a2012-03-11 07:00:24 +00004346 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004347 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004348 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004349 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004350 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004351 Consumer.addKeywordResult("_Bool");
4352
David Blaikiebbafb8a2012-03-11 07:00:24 +00004353 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004354 Consumer.addKeywordResult("class");
4355 Consumer.addKeywordResult("typename");
4356 Consumer.addKeywordResult("wchar_t");
4357
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004358 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004359 Consumer.addKeywordResult("char16_t");
4360 Consumer.addKeywordResult("char32_t");
4361 Consumer.addKeywordResult("constexpr");
4362 Consumer.addKeywordResult("decltype");
4363 Consumer.addKeywordResult("thread_local");
4364 }
4365 }
4366
David Blaikiebbafb8a2012-03-11 07:00:24 +00004367 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004368 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004369 } else if (CCC.WantFunctionLikeCasts) {
4370 static const char *const CastableTypeSpecs[] = {
4371 "char", "double", "float", "int", "long", "short",
4372 "signed", "unsigned", "void"
4373 };
4374 for (auto *kw : CastableTypeSpecs)
4375 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004376 }
4377
David Blaikiebbafb8a2012-03-11 07:00:24 +00004378 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004379 Consumer.addKeywordResult("const_cast");
4380 Consumer.addKeywordResult("dynamic_cast");
4381 Consumer.addKeywordResult("reinterpret_cast");
4382 Consumer.addKeywordResult("static_cast");
4383 }
4384
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004385 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004386 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004387 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004388 Consumer.addKeywordResult("false");
4389 Consumer.addKeywordResult("true");
4390 }
4391
David Blaikiebbafb8a2012-03-11 07:00:24 +00004392 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004393 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004394 "delete", "new", "operator", "throw", "typeid"
4395 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004396 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004397 for (unsigned I = 0; I != NumCXXExprs; ++I)
4398 Consumer.addKeywordResult(CXXExprs[I]);
4399
4400 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4401 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4402 Consumer.addKeywordResult("this");
4403
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004404 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004405 Consumer.addKeywordResult("alignof");
4406 Consumer.addKeywordResult("nullptr");
4407 }
4408 }
Jordan Rose58d54722012-06-30 21:33:57 +00004409
4410 if (SemaRef.getLangOpts().C11) {
4411 // FIXME: We should not suggest _Alignof if the alignof macro
4412 // is present.
4413 Consumer.addKeywordResult("_Alignof");
4414 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004415 }
4416
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004417 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004418 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4419 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004420 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004421 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004422 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004423 for (unsigned I = 0; I != NumCStmts; ++I)
4424 Consumer.addKeywordResult(CStmts[I]);
4425
David Blaikiebbafb8a2012-03-11 07:00:24 +00004426 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004427 Consumer.addKeywordResult("catch");
4428 Consumer.addKeywordResult("try");
4429 }
4430
4431 if (S && S->getBreakParent())
4432 Consumer.addKeywordResult("break");
4433
4434 if (S && S->getContinueParent())
4435 Consumer.addKeywordResult("continue");
4436
4437 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4438 Consumer.addKeywordResult("case");
4439 Consumer.addKeywordResult("default");
4440 }
4441 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004442 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004443 Consumer.addKeywordResult("namespace");
4444 Consumer.addKeywordResult("template");
4445 }
4446
4447 if (S && S->isClassScope()) {
4448 Consumer.addKeywordResult("explicit");
4449 Consumer.addKeywordResult("friend");
4450 Consumer.addKeywordResult("mutable");
4451 Consumer.addKeywordResult("private");
4452 Consumer.addKeywordResult("protected");
4453 Consumer.addKeywordResult("public");
4454 Consumer.addKeywordResult("virtual");
4455 }
4456 }
4457
David Blaikiebbafb8a2012-03-11 07:00:24 +00004458 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004459 Consumer.addKeywordResult("using");
4460
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004461 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004462 Consumer.addKeywordResult("static_assert");
4463 }
4464 }
4465}
4466
Kaelyn Takata6c759512014-10-27 18:07:37 +00004467std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4468 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4469 Scope *S, CXXScopeSpec *SS,
4470 std::unique_ptr<CorrectionCandidateCallback> CCC,
4471 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004472 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004473
4474 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4475 DisableTypoCorrection)
4476 return nullptr;
4477
4478 // In Microsoft mode, don't perform typo correction in a template member
4479 // function dependent context because it interferes with the "lookup into
4480 // dependent bases of class templates" feature.
4481 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4482 isa<CXXMethodDecl>(CurContext))
4483 return nullptr;
4484
4485 // We only attempt to correct typos for identifiers.
4486 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4487 if (!Typo)
4488 return nullptr;
4489
4490 // If the scope specifier itself was invalid, don't try to correct
4491 // typos.
4492 if (SS && SS->isInvalid())
4493 return nullptr;
4494
4495 // Never try to correct typos during template deduction or
4496 // instantiation.
4497 if (!ActiveTemplateInstantiations.empty())
4498 return nullptr;
4499
4500 // Don't try to correct 'super'.
4501 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4502 return nullptr;
4503
4504 // Abort if typo correction already failed for this specific typo.
4505 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4506 if (locs != TypoCorrectionFailures.end() &&
4507 locs->second.count(TypoName.getLoc()))
4508 return nullptr;
4509
4510 // Don't try to correct the identifier "vector" when in AltiVec mode.
4511 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4512 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004513 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004514 return nullptr;
4515
Nick Lewycky24653262014-12-16 21:39:02 +00004516 // Provide a stop gap for files that are just seriously broken. Trying
4517 // to correct all typos can turn into a HUGE performance penalty, causing
4518 // some files to take minutes to get rejected by the parser.
4519 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4520 if (Limit && TyposCorrected >= Limit)
4521 return nullptr;
4522 ++TyposCorrected;
4523
Kaelyn Takata6c759512014-10-27 18:07:37 +00004524 // If we're handling a missing symbol error, using modules, and the
4525 // special search all modules option is used, look for a missing import.
4526 if (ErrorRecovery && getLangOpts().Modules &&
4527 getLangOpts().ModulesSearchAll) {
4528 // The following has the side effect of loading the missing module.
4529 getModuleLoader().lookupMissingImports(Typo->getName(),
4530 TypoName.getLocStart());
4531 }
4532
4533 CorrectionCandidateCallback &CCCRef = *CCC;
4534 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4535 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4536 EnteringContext);
4537
Kaelyn Takata6c759512014-10-27 18:07:37 +00004538 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004539 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004540 DeclContext *QualifiedDC = MemberContext;
4541 if (MemberContext) {
4542 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4543
4544 // Look in qualified interfaces.
4545 if (OPT) {
4546 for (auto *I : OPT->quals())
4547 LookupVisibleDecls(I, LookupKind, *Consumer);
4548 }
4549 } else if (SS && SS->isSet()) {
4550 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4551 if (!QualifiedDC)
4552 return nullptr;
4553
Kaelyn Takata6c759512014-10-27 18:07:37 +00004554 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4555 } else {
4556 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004557 }
4558
4559 // Determine whether we are going to search in the various namespaces for
4560 // corrections.
4561 bool SearchNamespaces
4562 = getLangOpts().CPlusPlus &&
4563 (IsUnqualifiedLookup || (SS && SS->isSet()));
4564
4565 if (IsUnqualifiedLookup || SearchNamespaces) {
4566 // For unqualified lookup, look through all of the names that we have
4567 // seen in this translation unit.
4568 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4569 for (const auto &I : Context.Idents)
4570 Consumer->FoundName(I.getKey());
4571
4572 // Walk through identifiers in external identifier sources.
4573 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4574 if (IdentifierInfoLookup *External
4575 = Context.Idents.getExternalIdentifierLookup()) {
4576 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4577 do {
4578 StringRef Name = Iter->Next();
4579 if (Name.empty())
4580 break;
4581
4582 Consumer->FoundName(Name);
4583 } while (true);
4584 }
4585 }
4586
4587 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4588
4589 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4590 // to search those namespaces.
4591 if (SearchNamespaces) {
4592 // Load any externally-known namespaces.
4593 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4594 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4595 LoadedExternalKnownNamespaces = true;
4596 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4597 for (auto *N : ExternalKnownNamespaces)
4598 KnownNamespaces[N] = true;
4599 }
4600
4601 Consumer->addNamespaces(KnownNamespaces);
4602 }
4603
4604 return Consumer;
4605}
4606
Douglas Gregor2d435302009-12-30 17:04:44 +00004607/// \brief Try to "correct" a typo in the source code by finding
4608/// visible declarations whose names are similar to the name that was
4609/// present in the source code.
4610///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004611/// \param TypoName the \c DeclarationNameInfo structure that contains
4612/// the name that was present in the source code along with its location.
4613///
4614/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004615///
4616/// \param S the scope in which name lookup occurs.
4617///
4618/// \param SS the nested-name-specifier that precedes the name we're
4619/// looking for, if present.
4620///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004621/// \param CCC A CorrectionCandidateCallback object that provides further
4622/// validation of typo correction candidates. It also provides flags for
4623/// determining the set of keywords permitted.
4624///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004625/// \param MemberContext if non-NULL, the context in which to look for
4626/// a member access expression.
4627///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004629/// the nested-name-specifier SS.
4630///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004631/// \param OPT when non-NULL, the search for visible declarations will
4632/// also walk the protocols in the qualified interfaces of \p OPT.
4633///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004634/// \returns a \c TypoCorrection containing the corrected name if the typo
4635/// along with information such as the \c NamedDecl where the corrected name
4636/// was declared, and any additional \c NestedNameSpecifier needed to access
4637/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4638TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4639 Sema::LookupNameKind LookupKind,
4640 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004641 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004642 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004643 DeclContext *MemberContext,
4644 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004645 const ObjCObjectPointerType *OPT,
4646 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004647 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4648
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004649 // Always let the ExternalSource have the first chance at correction, even
4650 // if we would otherwise have given up.
4651 if (ExternalSource) {
4652 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004653 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004654 return Correction;
4655 }
4656
Kaelyn Takata6c759512014-10-27 18:07:37 +00004657 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4658 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4659 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4660 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4661 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Kaelyn Takata6c759512014-10-27 18:07:37 +00004663 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004664 auto Consumer = makeTypoCorrectionConsumer(
4665 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004666 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004667
Kaelyn Takata6c759512014-10-27 18:07:37 +00004668 if (!Consumer)
4669 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004670
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004671 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004672 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004673 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004674
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004675 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4676 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004677 unsigned ED = Consumer->getBestEditDistance(true);
4678 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004679 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004680 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004681
Kaelyn Takata6c759512014-10-27 18:07:37 +00004682 TypoCorrection BestTC = Consumer->getNextCorrection();
4683 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004684 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004685 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004686
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004687 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004688
Kaelyn Takata6c759512014-10-27 18:07:37 +00004689 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004690 // If this was an unqualified lookup and we believe the callback
4691 // object wouldn't have filtered out possible corrections, note
4692 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004693 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004694 }
4695
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004696 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004697 if (!SecondBestTC ||
4698 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4699 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004701 // Don't correct to a keyword that's the same as the typo; the keyword
4702 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004703 if (ED == 0 && Result.isKeyword())
4704 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004705
David Blaikie04ea41c2012-10-12 20:00:44 +00004706 TypoCorrection TC = Result;
4707 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004708 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004709 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004710 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004711 // Prefer 'super' when we're completing in a message-receiver
4712 // context.
4713
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004714 if (BestTC.getCorrection().getAsString() != "super") {
4715 if (SecondBestTC.getCorrection().getAsString() == "super")
4716 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004717 else if ((*Consumer)["super"].front().isKeyword())
4718 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004719 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004720 // Don't correct to a keyword that's the same as the typo; the keyword
4721 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004722 if (BestTC.getEditDistance() == 0 ||
4723 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004724 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004726 BestTC.setCorrectionRange(SS, TypoName);
4727 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004728 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004730 // Record the failure's location if needed and return an empty correction. If
4731 // this was an unqualified lookup and we believe the callback object did not
4732 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004733 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004734}
4735
Kaelyn Takata6c759512014-10-27 18:07:37 +00004736/// \brief Try to "correct" a typo in the source code by finding
4737/// visible declarations whose names are similar to the name that was
4738/// present in the source code.
4739///
4740/// \param TypoName the \c DeclarationNameInfo structure that contains
4741/// the name that was present in the source code along with its location.
4742///
4743/// \param LookupKind the name-lookup criteria used to search for the name.
4744///
4745/// \param S the scope in which name lookup occurs.
4746///
4747/// \param SS the nested-name-specifier that precedes the name we're
4748/// looking for, if present.
4749///
4750/// \param CCC A CorrectionCandidateCallback object that provides further
4751/// validation of typo correction candidates. It also provides flags for
4752/// determining the set of keywords permitted.
4753///
4754/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4755/// diagnostics when the actual typo correction is attempted.
4756///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004757/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4758/// Expr from a typo correction candidate.
4759///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004760/// \param MemberContext if non-NULL, the context in which to look for
4761/// a member access expression.
4762///
4763/// \param EnteringContext whether we're entering the context described by
4764/// the nested-name-specifier SS.
4765///
4766/// \param OPT when non-NULL, the search for visible declarations will
4767/// also walk the protocols in the qualified interfaces of \p OPT.
4768///
4769/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4770/// Expr representing the result of performing typo correction, or nullptr if
4771/// typo correction is not possible. If nullptr is returned, no diagnostics will
4772/// be emitted and it is the responsibility of the caller to emit any that are
4773/// needed.
4774TypoExpr *Sema::CorrectTypoDelayed(
4775 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4776 Scope *S, CXXScopeSpec *SS,
4777 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004778 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004779 DeclContext *MemberContext, bool EnteringContext,
4780 const ObjCObjectPointerType *OPT) {
4781 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4782
Kaelyn Takata6c759512014-10-27 18:07:37 +00004783 auto Consumer = makeTypoCorrectionConsumer(
4784 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004785 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004786
Benjamin Kramerb8727332016-05-19 10:46:10 +00004787 // Give the external sema source a chance to correct the typo.
4788 TypoCorrection ExternalTypo;
4789 if (ExternalSource && Consumer) {
4790 ExternalTypo = ExternalSource->CorrectTypo(
Benjamin Kramer97d7a662016-05-19 21:53:33 +00004791 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4792 MemberContext, EnteringContext, OPT);
Benjamin Kramerb8727332016-05-19 10:46:10 +00004793 if (ExternalTypo)
4794 Consumer->addCorrection(ExternalTypo);
4795 }
4796
Kaelyn Takata6c759512014-10-27 18:07:37 +00004797 if (!Consumer || Consumer->empty())
4798 return nullptr;
4799
4800 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4801 // is not more that about a third of the length of the typo's identifier.
4802 unsigned ED = Consumer->getBestEditDistance(true);
4803 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Benjamin Kramerb8727332016-05-19 10:46:10 +00004804 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004805 return nullptr;
4806
4807 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004808 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004809}
4810
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004811void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4812 if (!CDecl) return;
4813
4814 if (isKeyword())
4815 CorrectionDecls.clear();
4816
Richard Smithde6d6c42015-12-29 19:43:10 +00004817 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004818
4819 if (!CorrectionName)
4820 CorrectionName = CDecl->getDeclName();
4821}
4822
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004823std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4824 if (CorrectionNameSpec) {
4825 std::string tmpBuffer;
4826 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4827 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004828 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004829 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004830 }
4831
4832 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004833}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004834
Nico Weberb58e51c2014-11-19 05:21:39 +00004835bool CorrectionCandidateCallback::ValidateCandidate(
4836 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004837 if (!candidate.isResolved())
4838 return true;
4839
4840 if (candidate.isKeyword())
4841 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4842 WantRemainingKeywords || WantObjCSuper;
4843
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004844 bool HasNonType = false;
4845 bool HasStaticMethod = false;
4846 bool HasNonStaticMethod = false;
4847 for (Decl *D : candidate) {
4848 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4849 D = FTD->getTemplatedDecl();
4850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4851 if (Method->isStatic())
4852 HasStaticMethod = true;
4853 else
4854 HasNonStaticMethod = true;
4855 }
4856 if (!isa<TypeDecl>(D))
4857 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004858 }
4859
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004860 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4861 !candidate.getCorrectionSpecifier())
4862 return false;
4863
4864 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004865}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004866
4867FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004868 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004869 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004870 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004871 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004872 WantTypeSpecifiers = false;
4873 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004874 WantRemainingKeywords = false;
4875}
4876
4877bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4878 if (!candidate.getCorrectionDecl())
4879 return candidate.isKeyword();
4880
Aaron Ballman1e606f42014-07-15 22:03:49 +00004881 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004882 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004883 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004884 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4885 FD = FTD->getTemplatedDecl();
4886 if (!HasExplicitTemplateArgs && !FD) {
4887 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4888 // If the Decl is neither a function nor a template function,
4889 // determine if it is a pointer or reference to a function. If so,
4890 // check against the number of arguments expected for the pointee.
4891 QualType ValType = cast<ValueDecl>(ND)->getType();
4892 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4893 ValType = ValType->getPointeeType();
4894 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004895 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004896 return true;
4897 }
4898 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004899
4900 // Skip the current candidate if it is not a FunctionDecl or does not accept
4901 // the current number of arguments.
4902 if (!FD || !(FD->getNumParams() >= NumArgs &&
4903 FD->getMinRequiredArguments() <= NumArgs))
4904 continue;
4905
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004906 // If the current candidate is a non-static C++ method, skip the candidate
4907 // unless the method being corrected--or the current DeclContext, if the
4908 // function being corrected is not a method--is a method in the same class
4909 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004910 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004911 if (MemberFn || !MD->isStatic()) {
4912 CXXMethodDecl *CurMD =
4913 MemberFn
4914 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4915 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004916 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004917 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004918 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4919 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4920 continue;
4921 }
4922 }
4923 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004924 }
4925 return false;
4926}
Richard Smithf9b15102013-08-17 00:46:16 +00004927
4928void Sema::diagnoseTypo(const TypoCorrection &Correction,
4929 const PartialDiagnostic &TypoDiag,
4930 bool ErrorRecovery) {
4931 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4932 ErrorRecovery);
4933}
4934
Richard Smithe156254d2013-08-20 20:35:18 +00004935/// Find which declaration we should import to provide the definition of
4936/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004937static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4938 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004939 return VD->getDefinition();
Yaron Keren18c3d062016-07-13 19:04:51 +00004940 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4941 return FD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004942 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004943 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004944 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004945 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004946 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004947 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004948 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004949 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004950 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004951}
4952
Richard Smithf2b1eb92015-06-15 20:15:48 +00004953void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
Richard Smith6739a102016-05-05 00:56:12 +00004954 MissingImportKind MIK, bool Recover) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004955 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4956
4957 // Suggest importing a module providing the definition of this entity, if
4958 // possible.
4959 NamedDecl *Def = getDefinitionToImport(Decl);
4960 if (!Def)
4961 Def = Decl;
4962
Richard Smithf2b1eb92015-06-15 20:15:48 +00004963 Module *Owner = getOwningModule(Decl);
4964 assert(Owner && "definition of hidden declaration is not in a module");
4965
Richard Smith35c1df52015-06-17 20:16:32 +00004966 llvm::SmallVector<Module*, 8> OwningModules;
4967 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004968 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004969 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4970
Richard Smith6739a102016-05-05 00:56:12 +00004971 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
Richard Smith35c1df52015-06-17 20:16:32 +00004972 Recover);
4973}
4974
Richard Smith4eb83932016-04-27 21:57:05 +00004975/// \brief Get a "quoted.h" or <angled.h> include path to use in a diagnostic
4976/// suggesting the addition of a #include of the specified file.
4977static std::string getIncludeStringForHeader(Preprocessor &PP,
4978 const FileEntry *E) {
4979 bool IsSystem;
4980 auto Path =
4981 PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
4982 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
4983}
4984
Richard Smith35c1df52015-06-17 20:16:32 +00004985void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4986 SourceLocation DeclLoc,
4987 ArrayRef<Module *> Modules,
4988 MissingImportKind MIK, bool Recover) {
4989 assert(!Modules.empty());
4990
4991 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004992 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004993 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00004994 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004995 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00004996 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004997 ModuleList += "[...]";
4998 break;
4999 }
5000 ModuleList += M->getFullModuleName();
5001 }
5002
Richard Smith35c1df52015-06-17 20:16:32 +00005003 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5004 << (int)MIK << Decl << ModuleList;
Richard Smith4eb83932016-04-27 21:57:05 +00005005 } else if (const FileEntry *E =
5006 PP.getModuleHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5007 // The right way to make the declaration visible is to include a header;
5008 // suggest doing so.
5009 //
5010 // FIXME: Find a smart place to suggest inserting a #include, and add
5011 // a FixItHint there.
5012 Diag(UseLoc, diag::err_module_unimported_use_header)
5013 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5014 << getIncludeStringForHeader(PP, E);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005015 } else {
Richard Smithacef17a2016-05-05 02:14:06 +00005016 // FIXME: Add a FixItHint that imports the corresponding module.
Richard Smith35c1df52015-06-17 20:16:32 +00005017 Diag(UseLoc, diag::err_module_unimported_use)
5018 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005019 }
Richard Smith35c1df52015-06-17 20:16:32 +00005020
5021 unsigned DiagID;
5022 switch (MIK) {
5023 case MissingImportKind::Declaration:
5024 DiagID = diag::note_previous_declaration;
5025 break;
5026 case MissingImportKind::Definition:
5027 DiagID = diag::note_previous_definition;
5028 break;
5029 case MissingImportKind::DefaultArgument:
5030 DiagID = diag::note_default_argument_declared_here;
5031 break;
Richard Smith6739a102016-05-05 00:56:12 +00005032 case MissingImportKind::ExplicitSpecialization:
5033 DiagID = diag::note_explicit_specialization_declared_here;
5034 break;
5035 case MissingImportKind::PartialSpecialization:
5036 DiagID = diag::note_partial_specialization_declared_here;
5037 break;
Richard Smith35c1df52015-06-17 20:16:32 +00005038 }
5039 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005040
5041 // Try to recover by implicitly importing this module.
5042 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00005043 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005044}
5045
Richard Smithf9b15102013-08-17 00:46:16 +00005046/// \brief Diagnose a successfully-corrected typo. Separated from the correction
5047/// itself to allow external validation of the result, etc.
5048///
5049/// \param Correction The result of performing typo correction.
5050/// \param TypoDiag The diagnostic to produce. This will have the corrected
5051/// string added to it (and usually also a fixit).
5052/// \param PrevNote A note to use when indicating the location of the entity to
5053/// which we are correcting. Will have the correction string added to it.
5054/// \param ErrorRecovery If \c true (the default), the caller is going to
5055/// recover from the typo as if the corrected string had been typed.
5056/// In this case, \c PDiag must be an error, and we will attach a fixit
5057/// to it.
5058void Sema::diagnoseTypo(const TypoCorrection &Correction,
5059 const PartialDiagnostic &TypoDiag,
5060 const PartialDiagnostic &PrevNote,
5061 bool ErrorRecovery) {
5062 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5063 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5064 FixItHint FixTypo = FixItHint::CreateReplacement(
5065 Correction.getCorrectionRange(), CorrectedStr);
5066
Richard Smithe156254d2013-08-20 20:35:18 +00005067 // Maybe we're just missing a module import.
5068 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00005069 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00005070 assert(Decl && "import required but no declaration to import");
5071
Richard Smithf2b1eb92015-06-15 20:15:48 +00005072 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005073 MissingImportKind::Declaration, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00005074 return;
5075 }
5076
Richard Smithf9b15102013-08-17 00:46:16 +00005077 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5078 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5079
5080 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005081 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005082 if (PrevNote.getDiagID() && ChosenDecl)
5083 Diag(ChosenDecl->getLocation(), PrevNote)
5084 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
Benjamin Kramer7de99692016-11-16 18:15:26 +00005085
5086 // Add any extra diagnostics.
5087 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5088 Diag(Correction.getCorrectionRange().getBegin(), PD);
Richard Smithf9b15102013-08-17 00:46:16 +00005089}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005090
Kaelyn Takata8363f042014-10-27 18:07:42 +00005091TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5092 TypoDiagnosticGenerator TDG,
5093 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005094 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5095 auto TE = new (Context) TypoExpr(Context.DependentTy);
5096 auto &State = DelayedTypos[TE];
5097 State.Consumer = std::move(TCC);
5098 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005099 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005100 return TE;
5101}
5102
5103const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5104 auto Entry = DelayedTypos.find(TE);
5105 assert(Entry != DelayedTypos.end() &&
5106 "Failed to get the state for a TypoExpr!");
5107 return Entry->second;
5108}
5109
5110void Sema::clearDelayedTypo(TypoExpr *TE) {
5111 DelayedTypos.erase(TE);
5112}
Richard Smithba3a4f92016-01-12 21:59:26 +00005113
5114void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5115 DeclarationNameInfo Name(II, IILoc);
5116 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5117 R.suppressDiagnostics();
5118 R.setHideTags(false);
5119 LookupName(R, S);
5120 R.dump();
5121}