 |
|
 |
|
| Files: |
1 |
|
Branches Taken: |
85.6% |
734 / 857 |
| Generated: |
2010-02-10 01:31 |
|
Branches Executed: |
95.8% |
821 / 857 |
| |
|
Line Coverage: |
92.9% |
880 / 947 |
| |
 |
|
 |
1 : //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2 : //
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 : //===----------------------------------------------------------------------===//
14 : #include "Sema.h"
15 : #include "Lookup.h"
16 : #include "clang/AST/ASTContext.h"
17 : #include "clang/AST/CXXInheritance.h"
18 : #include "clang/AST/Decl.h"
19 : #include "clang/AST/DeclCXX.h"
20 : #include "clang/AST/DeclObjC.h"
21 : #include "clang/AST/DeclTemplate.h"
22 : #include "clang/AST/Expr.h"
23 : #include "clang/AST/ExprCXX.h"
24 : #include "clang/Parse/DeclSpec.h"
25 : #include "clang/Basic/Builtins.h"
26 : #include "clang/Basic/LangOptions.h"
27 : #include "llvm/ADT/STLExtras.h"
28 : #include "llvm/ADT/SmallPtrSet.h"
29 : #include "llvm/Support/ErrorHandling.h"
30 : #include <list>
31 : #include <set>
32 : #include <vector>
33 : #include <iterator>
34 : #include <utility>
35 : #include <algorithm>
36 :
37 : using namespace clang;
38 :
39 : namespace {
40 1064: class UnqualUsingEntry {
41 : const DeclContext *Nominated;
42 : const DeclContext *CommonAncestor;
43 :
44 : public:
45 : UnqualUsingEntry(const DeclContext *Nominated,
46 1064: const DeclContext *CommonAncestor)
47 1064: : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 1064: }
49 :
50 2866: const DeclContext *getCommonAncestor() const {
51 2866: return CommonAncestor;
52 : }
53 :
54 932: const DeclContext *getNominatedNamespace() const {
55 932: return Nominated;
56 : }
57 :
58 : // Sort by the pointer value of the common ancestor.
59 : struct Comparator {
60 386: bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 386: return L.getCommonAncestor() < R.getCommonAncestor();
62 : }
63 :
64 1282: bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 1282: return E.getCommonAncestor() < DC;
66 : }
67 :
68 812: bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 812: return DC < E.getCommonAncestor();
70 : }
71 : };
72 : };
73 :
74 : /// A collection of using directives, as used by C++ unqualified
75 : /// lookup.
76 39637: class UnqualUsingDirectiveSet {
77 : typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
78 :
79 : ListTy list;
80 : llvm::SmallPtrSet<DeclContext*, 8> visited;
81 :
82 : public:
83 39637: UnqualUsingDirectiveSet() {}
84 :
85 39546: void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 : // C++ [namespace.udir]p1:
87 : // During unqualified name lookup, the names appear as if they
88 : // were declared in the nearest enclosing namespace which contains
89 : // both the using-directive and the nominated namespace.
90 : DeclContext *InnermostFileDC
91 39546: = static_cast<DeclContext*>(InnermostFileScope->getEntity());
39546: branch 0 taken
0: branch 1 not taken
0: branch 3 not taken
39546: branch 4 taken
92 39546: assert(InnermostFileDC && InnermostFileDC->isFileContext());
93 :
78878: branch 1 taken
39546: branch 2 taken
94 118424: for (; S; S = S->getParent()) {
66613: branch 1 taken
12265: branch 2 taken
95 78878: if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
45406: branch 1 taken
21207: branch 2 taken
96 66613: DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 66613: visit(Ctx, EffectiveDC);
98 : } else {
99 12265: Scope::udir_iterator I = S->using_directives_begin(),
100 12265: End = S->using_directives_end();
101 :
0: branch 0 not taken
12265: branch 1 taken
102 12265: for (; I != End; ++I)
103 0: visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 : }
105 : }
106 39546: }
107 :
108 : // Visits a context and collect all of its using directives
109 : // recursively. Treats all using directives as if they were
110 : // declared in the context.
111 : //
112 : // A given context is only every visited once, so it is important
113 : // that contexts be visited from the inside out in order to get
114 : // the effective DCs right.
115 66613: void visit(DeclContext *DC, DeclContext *EffectiveDC) {
11: branch 1 taken
66602: branch 2 taken
116 66613: if (!visited.insert(DC))
117 11: return;
118 :
119 66602: addUsingDirectives(DC, EffectiveDC);
120 : }
121 :
122 : // Visits a using directive and collects all of its using
123 : // directives recursively. Treats all using directives as if they
124 : // were declared in the effective DC.
125 0: void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
0: branch 1 not taken
0: branch 2 not taken
126 0: DeclContext *NS = UD->getNominatedNamespace();
0: branch 1 not taken
0: branch 2 not taken
127 0: if (!visited.insert(NS))
128 0: return;
129 :
130 0: addUsingDirective(UD, EffectiveDC);
131 0: addUsingDirectives(NS, EffectiveDC);
132 : }
133 :
134 : // Adds all the using directives in a context (and those nominated
135 : // by its using directives, transitively) as if they appeared in
136 : // the given effective context.
137 66602: void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 66602: llvm::SmallVector<DeclContext*,4> queue;
139 1064: while (true) {
140 : DeclContext::udir_iterator I, End;
1177: branch 3 taken
67666: branch 4 taken
141 68843: for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 1177: UsingDirectiveDecl *UD = *I;
1177: branch 1 taken
0: branch 2 not taken
143 1177: DeclContext *NS = UD->getNominatedNamespace();
1064: branch 1 taken
113: branch 2 taken
144 1177: if (visited.insert(NS)) {
145 1064: addUsingDirective(UD, EffectiveDC);
146 1064: queue.push_back(NS);
147 : }
148 : }
149 :
1064: branch 1 taken
66602: branch 2 taken
150 67666: if (queue.empty())
151 : return;
152 :
153 1064: DC = queue.back();
154 1064: queue.pop_back();
155 66602: }
156 : }
157 :
158 : // Add a using directive as if it had been declared in the given
159 : // context. This helps implement C++ [namespace.udir]p3:
160 : // The using-directive is transitive: if a scope contains a
161 : // using-directive that nominates a second namespace that itself
162 : // contains using-directives, the effect is as if the
163 : // using-directives from the second namespace also appeared in
164 : // the first.
165 1064: void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 : // Find the common ancestor between the effective context and
167 : // the nominated namespace.
1064: branch 1 taken
0: branch 2 not taken
168 1064: DeclContext *Common = UD->getNominatedNamespace();
1161: branch 1 taken
1064: branch 2 taken
169 3289: while (!Common->Encloses(EffectiveDC))
170 1161: Common = Common->getParent();
171 1064: Common = Common->getPrimaryContext();
172 :
1064: branch 1 taken
0: branch 2 not taken
173 1064: list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 1064: }
175 :
176 39637: void done() {
177 39637: std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 39637: }
179 :
180 : typedef ListTy::iterator iterator;
181 : typedef ListTy::const_iterator const_iterator;
182 :
183 : iterator begin() { return list.begin(); }
184 : iterator end() { return list.end(); }
185 41088: const_iterator begin() const { return list.begin(); }
186 41088: const_iterator end() const { return list.end(); }
187 :
188 : std::pair<const_iterator,const_iterator>
189 41088: getNamespacesFor(DeclContext *DC) const {
190 : return std::equal_range(begin(), end(), DC->getPrimaryContext(),
191 41088: UnqualUsingEntry::Comparator());
192 : }
193 : };
194 : }
195 :
196 47652: static bool IsAcceptableIDNS(NamedDecl *D, unsigned IDNS) {
197 47652: return D->isInIdentifierNamespace(IDNS);
198 : }
199 :
200 220: static bool IsAcceptableOperatorName(NamedDecl *D, unsigned IDNS) {
201 : return D->isInIdentifierNamespace(IDNS) &&
200: branch 1 taken
20: branch 2 taken
138: branch 5 taken
62: branch 6 taken
202 220: !D->getDeclContext()->isRecord();
203 : }
204 :
205 4618: static bool IsAcceptableNestedNameSpecifierName(NamedDecl *D, unsigned IDNS) {
206 : // This lookup ignores everything that isn't a type.
207 :
208 : // This is a fast check for the far most common case.
4369: branch 1 taken
249: branch 2 taken
209 4618: if (D->isInIdentifierNamespace(Decl::IDNS_Tag))
210 4369: return true;
211 :
2: branch 1 taken
247: branch 2 taken
212 249: if (isa<UsingShadowDecl>(D))
213 2: D = cast<UsingShadowDecl>(D)->getTargetDecl();
214 :
215 249: return isa<TypeDecl>(D);
216 : }
217 :
218 227: static bool IsAcceptableNamespaceName(NamedDecl *D, unsigned IDNS) {
219 : // We don't need to look through using decls here because
220 : // using decls aren't allowed to name namespaces.
221 :
25: branch 1 taken
202: branch 2 taken
3: branch 4 taken
22: branch 5 taken
222 227: return isa<NamespaceDecl>(D) || isa<NamespaceAliasDecl>(D);
223 : }
224 :
225 : /// Gets the default result filter for the given lookup.
226 : static inline
227 154852: LookupResult::ResultFilter getResultFilter(Sema::LookupNameKind NameKind) {
151655: branch 0 taken
540: branch 1 taken
2537: branch 2 taken
120: branch 3 taken
0: branch 4 not taken
228 154852: switch (NameKind) {
229 : case Sema::LookupOrdinaryName:
230 : case Sema::LookupTagName:
231 : case Sema::LookupMemberName:
232 : case Sema::LookupRedeclarationWithLinkage: // FIXME: check linkage, scoping
233 : case Sema::LookupUsingDeclName:
234 : case Sema::LookupObjCProtocolName:
235 : case Sema::LookupObjCImplementationName:
236 151655: return &IsAcceptableIDNS;
237 :
238 : case Sema::LookupOperatorName:
239 540: return &IsAcceptableOperatorName;
240 :
241 : case Sema::LookupNestedNameSpecifierName:
242 2537: return &IsAcceptableNestedNameSpecifierName;
243 :
244 : case Sema::LookupNamespaceName:
245 120: return &IsAcceptableNamespaceName;
246 : }
247 :
248 0: llvm_unreachable("unkknown lookup kind");
249 : return 0;
250 : }
251 :
252 : // Retrieve the set of identifier namespaces that correspond to a
253 : // specific kind of name lookup.
254 : static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
255 : bool CPlusPlus,
256 154852: bool Redeclaration) {
257 154852: unsigned IDNS = 0;
134583: branch 0 taken
8117: branch 1 taken
7325: branch 2 taken
2657: branch 3 taken
150: branch 4 taken
2020: branch 5 taken
0: branch 6 not taken
0: branch 7 not taken
258 154852: switch (NameKind) {
259 : case Sema::LookupOrdinaryName:
260 : case Sema::LookupOperatorName:
261 : case Sema::LookupRedeclarationWithLinkage:
262 134583: IDNS = Decl::IDNS_Ordinary;
55563: branch 0 taken
79020: branch 1 taken
263 134583: if (CPlusPlus) {
264 55563: IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
23812: branch 0 taken
31751: branch 1 taken
265 55563: if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
266 : }
267 134583: break;
268 :
269 : case Sema::LookupTagName:
270 8117: IDNS = Decl::IDNS_Tag;
4957: branch 0 taken
3160: branch 1 taken
2759: branch 2 taken
2198: branch 3 taken
271 8117: if (CPlusPlus && Redeclaration)
272 2759: IDNS |= Decl::IDNS_TagFriend;
273 8117: break;
274 :
275 : case Sema::LookupMemberName:
276 7325: IDNS = Decl::IDNS_Member;
2652: branch 0 taken
4673: branch 1 taken
277 7325: if (CPlusPlus)
278 2652: IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
279 7325: break;
280 :
281 : case Sema::LookupNestedNameSpecifierName:
282 : case Sema::LookupNamespaceName:
283 2657: IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
284 2657: break;
285 :
286 : case Sema::LookupUsingDeclName:
287 : IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
288 150: | Decl::IDNS_Member | Decl::IDNS_Using;
289 150: break;
290 :
291 : case Sema::LookupObjCProtocolName:
292 2020: IDNS = Decl::IDNS_ObjCProtocol;
293 2020: break;
294 :
295 : case Sema::LookupObjCImplementationName:
296 0: IDNS = Decl::IDNS_ObjCImplementation;
297 : break;
298 : }
299 154852: return IDNS;
300 : }
301 :
302 154852: void LookupResult::configure() {
303 : IDNS = getIDNS(LookupKind,
304 : SemaRef.getLangOptions().CPlusPlus,
305 154852: isForRedeclaration());
306 154852: IsAcceptableFn = getResultFilter(LookupKind);
307 154852: }
308 :
309 : // Necessary because CXXBasePaths is not complete in Sema.h
310 30: void LookupResult::deletePaths(CXXBasePaths *Paths) {
30: branch 0 taken
0: branch 1 not taken
311 30: delete Paths;
312 30: }
313 :
314 : /// Resolves the result kind of this lookup.
315 117308: void LookupResult::resolveKind() {
316 117308: unsigned N = Decls.size();
317 :
318 : // Fast case: no possible ambiguity.
26194: branch 0 taken
91114: branch 1 taken
319 117308: if (N == 0) {
0: branch 0 not taken
26194: branch 1 taken
26194: branch 2 taken
26194: branch 3 taken
320 26194: assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
321 26194: return;
322 : }
323 :
324 : // If there's a single decl, we need to examine it to decide what
325 : // kind of lookup this is.
76958: branch 0 taken
14156: branch 1 taken
326 91114: if (N == 1) {
962: branch 3 taken
75996: branch 4 taken
327 76958: if (isa<FunctionTemplateDecl>(*Decls.begin()))
328 962: ResultKind = FoundOverloaded;
14: branch 3 taken
75982: branch 4 taken
329 75996: else if (isa<UnresolvedUsingValueDecl>(*Decls.begin()))
330 14: ResultKind = FoundUnresolvedValue;
331 76958: return;
332 : }
333 :
334 : // Don't do any extra resolution if we've already resolved as ambiguous.
14142: branch 0 taken
14: branch 1 taken
335 14156: if (ResultKind == Ambiguous) return;
336 :
337 14142: llvm::SmallPtrSet<NamedDecl*, 16> Unique;
338 :
339 14142: bool Ambiguous = false;
340 14142: bool HasTag = false, HasFunction = false, HasNonFunction = false;
341 14142: bool HasFunctionTemplate = false, HasUnresolved = false;
342 :
343 14142: unsigned UniqueTagIndex = 0;
344 :
345 14142: unsigned I = 0;
32225: branch 0 taken
14142: branch 1 taken
346 60509: while (I < N) {
347 32225: NamedDecl *D = Decls[I]->getUnderlyingDecl();
348 32225: D = cast<NamedDecl>(D->getCanonicalDecl());
349 :
14100: branch 1 taken
18125: branch 2 taken
350 32225: if (!Unique.insert(D)) {
351 : // If it's not unique, pull something off the back (and
352 : // continue at this index).
353 14100: Decls[I] = Decls[--N];
354 : } else {
355 : // Otherwise, do some decl type analysis and then continue.
356 :
4: branch 1 taken
18121: branch 2 taken
357 18125: if (isa<UnresolvedUsingValueDecl>(D)) {
358 4: HasUnresolved = true;
4657: branch 1 taken
13464: branch 2 taken
359 18121: } else if (isa<TagDecl>(D)) {
10: branch 0 taken
4647: branch 1 taken
360 4657: if (HasTag)
361 10: Ambiguous = true;
362 4657: UniqueTagIndex = I;
363 4657: HasTag = true;
1620: branch 1 taken
11844: branch 2 taken
364 13464: } else if (isa<FunctionTemplateDecl>(D)) {
365 1620: HasFunction = true;
366 1620: HasFunctionTemplate = true;
7823: branch 1 taken
4021: branch 2 taken
367 11844: } else if (isa<FunctionDecl>(D)) {
368 7823: HasFunction = true;
369 : } else {
23: branch 0 taken
3998: branch 1 taken
370 4021: if (HasNonFunction)
371 23: Ambiguous = true;
372 4021: HasNonFunction = true;
373 : }
374 18125: I++;
375 : }
376 : }
377 :
378 : // C++ [basic.scope.hiding]p2:
379 : // A class name or enumeration name can be hidden by the name of
380 : // an object, function, or enumerator declared in the same
381 : // scope. If a class or enumeration name and an object, function,
382 : // or enumerator are declared in the same scope (in any order)
383 : // with the same name, the class or enumeration name is hidden
384 : // wherever the object, function, or enumerator name is visible.
385 : // But it's still an error if there are distinct tag types found,
386 : // even if they're not visible. (ref?)
14100: branch 0 taken
42: branch 1 taken
4636: branch 2 taken
9464: branch 3 taken
4627: branch 4 taken
9: branch 5 taken
4596: branch 6 taken
31: branch 7 taken
4490: branch 8 taken
106: branch 9 taken
0: branch 10 not taken
4490: branch 11 taken
387 14142: if (HideTags && HasTag && !Ambiguous &&
388 : (HasFunction || HasNonFunction || HasUnresolved))
389 137: Decls[UniqueTagIndex] = Decls[--N];
390 :
391 14142: Decls.set_size(N);
392 :
3998: branch 0 taken
10144: branch 1 taken
3988: branch 2 taken
10: branch 3 taken
0: branch 4 not taken
3988: branch 5 taken
393 14142: if (HasNonFunction && (HasFunction || HasUnresolved))
394 10: Ambiguous = true;
395 :
41: branch 0 taken
14101: branch 1 taken
396 14142: if (Ambiguous)
397 41: setAmbiguous(LookupResult::AmbiguousReference);
4: branch 0 taken
14097: branch 1 taken
398 14101: else if (HasUnresolved)
399 4: ResultKind = LookupResult::FoundUnresolvedValue;
11768: branch 0 taken
2329: branch 1 taken
670: branch 2 taken
11098: branch 3 taken
400 17096: else if (N > 1 || HasFunctionTemplate)
401 2999: ResultKind = LookupResult::FoundOverloaded;
402 : else
403 11098: ResultKind = LookupResult::Found;
404 : }
405 :
406 30: void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
407 30: CXXBasePaths::paths_iterator I, E;
408 : DeclContext::lookup_iterator DI, DE;
63: branch 4 taken
30: branch 5 taken
409 93: for (I = P.begin(), E = P.end(); I != E; ++I)
71: branch 3 taken
63: branch 4 taken
410 134: for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411 71: addDecl(*DI);
412 30: }
413 :
414 10: void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
415 10: Paths = new CXXBasePaths;
416 10: Paths->swap(P);
417 10: addDeclsFromBasePaths(*Paths);
418 10: resolveKind();
419 10: setAmbiguous(AmbiguousBaseSubobjects);
420 10: }
421 :
422 20: void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
423 20: Paths = new CXXBasePaths;
424 20: Paths->swap(P);
425 20: addDeclsFromBasePaths(*Paths);
426 20: resolveKind();
427 20: setAmbiguous(AmbiguousBaseSubobjectTypes);
428 20: }
429 :
430 0: void LookupResult::print(llvm::raw_ostream &Out) {
431 0: Out << Decls.size() << " result(s)";
0: branch 1 not taken
0: branch 2 not taken
432 0: if (isAmbiguous()) Out << ", ambiguous";
0: branch 0 not taken
0: branch 1 not taken
433 0: if (Paths) Out << ", base paths present";
434 :
0: branch 4 not taken
0: branch 5 not taken
435 0: for (iterator I = begin(), E = end(); I != E; ++I) {
436 0: Out << "\n";
437 0: (*I)->print(Out, 2);
438 : }
439 0: }
440 :
441 : // Adds all qualifying matches for a name within a decl context to the
442 : // given lookup result. Returns true if any matches were found.
443 59798: static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
444 59798: bool Found = false;
445 :
446 : DeclContext::lookup_const_iterator I, E;
22630: branch 4 taken
59798: branch 5 taken
447 82428: for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
448 22630: NamedDecl *D = *I;
22374: branch 1 taken
256: branch 2 taken
449 22630: if (R.isAcceptableDecl(D)) {
450 22374: R.addDecl(D);
451 22374: Found = true;
452 : }
453 : }
454 :
531: branch 2 taken
59267: branch 3 taken
474: branch 8 taken
57: branch 9 taken
219: branch 11 taken
255: branch 12 taken
59543: branch 13 taken
255: branch 14 taken
455 59798: if (R.getLookupName().getNameKind()
456 : != DeclarationName::CXXConversionFunctionName ||
457 : R.getLookupName().getCXXNameType()->isDependentType() ||
458 : !isa<CXXRecordDecl>(DC))
459 59543: return Found;
460 :
461 : // C++ [temp.mem]p6:
462 : // A specialization of a conversion function template is not found by
463 : // name lookup. Instead, any conversion function templates visible in the
464 : // context of the use are considered. [...]
465 255: const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
224: branch 1 taken
31: branch 2 taken
466 255: if (!Record->isDefinition())
467 224: return Found;
468 :
469 31: const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
47: branch 4 taken
31: branch 5 taken
470 88: for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
471 31: UEnd = Unresolved->end(); U != UEnd; ++U) {
472 47: FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
20: branch 0 taken
27: branch 1 taken
473 47: if (!ConvTemplate)
474 20: continue;
475 :
476 : // When we're performing lookup for the purposes of redeclaration, just
477 : // add the conversion function template. When we deduce template
478 : // arguments for specializations, we'll end up unifying the return
479 : // type of the new declaration with the type of the function template.
1: branch 1 taken
26: branch 2 taken
480 27: if (R.isForRedeclaration()) {
481 1: R.addDecl(ConvTemplate);
482 1: Found = true;
483 1: continue;
484 : }
485 :
486 : // C++ [temp.mem]p6:
487 : // [...] For each such operator, if argument deduction succeeds
488 : // (14.9.2.3), the resulting specialization is used as if found by
489 : // name lookup.
490 : //
491 : // When referencing a conversion function for any purpose other than
492 : // a redeclaration (such that we'll be building an expression with the
493 : // result), perform template argument deduction and place the
494 : // specialization into the result set. We do this to avoid forcing all
495 : // callers to perform special deduction for conversion functions.
496 26: Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
497 26: FunctionDecl *Specialization = 0;
498 :
499 : const FunctionProtoType *ConvProto
500 26: = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
0: branch 0 not taken
26: branch 1 taken
501 26: assert(ConvProto && "Nonsensical conversion function template type");
502 :
503 : // Compute the type of the function that we would expect the conversion
504 : // function to have, if it were to match the name given.
505 : // FIXME: Calling convention!
506 : QualType ExpectedType
507 : = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
508 : 0, 0, ConvProto->isVariadic(),
509 : ConvProto->getTypeQuals(),
510 : false, false, 0, 0,
511 26: ConvProto->getNoReturnAttr());
512 :
513 : // Perform template argument deduction against the type that we would
514 : // expect the function to have.
24: branch 2 taken
2: branch 3 taken
515 26: if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
516 : Specialization, Info)
517 : == Sema::TDK_Success) {
518 24: R.addDecl(Specialization);
519 24: Found = true;
520 : }
521 : }
522 :
523 31: return Found;
524 : }
525 :
526 : // Performs C++ unqualified lookup into the given file context.
527 : static bool
528 : CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
529 40885: UnqualUsingDirectiveSet &UDirs) {
530 :
40885: branch 0 taken
0: branch 1 not taken
40885: branch 3 taken
0: branch 4 not taken
531 40885: assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
532 :
533 : // Perform direct name lookup into the LookupCtx.
534 40885: bool Found = LookupDirect(R, NS);
535 :
536 : // Perform direct name lookup into the namespaces nominated by the
537 : // using directives whose common ancestor is this namespace.
538 : UnqualUsingDirectiveSet::const_iterator UI, UEnd;
539 40885: llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
540 :
920: branch 0 taken
40885: branch 1 taken
541 41805: for (; UI != UEnd; ++UI)
123: branch 2 taken
797: branch 3 taken
542 920: if (LookupDirect(R, UI->getNominatedNamespace()))
543 123: Found = true;
544 :
545 40885: R.resolveKind();
546 :
547 40885: return Found;
548 : }
549 :
550 90300: static bool isNamespaceOrTranslationUnitScope(Scope *S) {
72739: branch 1 taken
17561: branch 2 taken
551 90300: if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
552 72739: return Ctx->isFileContext();
553 17561: return false;
554 : }
555 :
556 : // Find the next outer declaration context corresponding to this scope.
557 24118: static DeclContext *findOuterContext(Scope *S) {
28058: branch 2 taken
134: branch 3 taken
558 28192: for (S = S->getParent(); S; S = S->getParent())
23984: branch 1 taken
4074: branch 2 taken
559 28058: if (S->getEntity())
560 23984: return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
561 :
562 134: return 0;
563 : }
564 :
565 52058: bool Sema::CppLookupName(LookupResult &R, Scope *S) {
52058: branch 1 taken
0: branch 2 not taken
566 52058: assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
567 :
568 52058: DeclarationName Name = R.getLookupName();
569 :
570 52058: Scope *Initial = S;
571 : IdentifierResolver::iterator
572 52058: I = IdResolver.begin(Name),
573 52058: IEnd = IdResolver.end();
574 :
575 : // First we lookup local scope.
576 : // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
577 : // ...During unqualified name lookup (3.4.1), the names appear as if
578 : // they were declared in the nearest enclosing namespace which contains
579 : // both the using-directive and the nominated namespace.
580 : // [Note: in this context, "contains" means "contains directly or
581 : // indirectly".
582 : //
583 : // For example:
584 : // namespace A { int i; }
585 : // void foo() {
586 : // int i;
587 : // {
588 : // using namespace A;
589 : // ++i; // finds local 'i', A::i appears at global scope
590 : // }
591 : // }
592 : //
90222: branch 1 taken
1: branch 2 taken
50719: branch 4 taken
39503: branch 5 taken
50719: branch 6 taken
39504: branch 7 taken
593 90223: for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
594 : // Check whether the IdResolver has anything in this scope.
595 50719: bool Found = false;
31238: branch 2 taken
31971: branch 3 taken
12490: branch 7 taken
18748: branch 8 taken
12490: branch 9 taken
50719: branch 10 taken
596 63209: for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
12382: branch 2 taken
108: branch 3 taken
597 12490: if (R.isAcceptableDecl(*I)) {
598 12382: Found = true;
599 12382: R.addDecl(*I);
600 : }
601 : }
12068: branch 0 taken
38651: branch 1 taken
602 50719: if (Found) {
603 12068: R.resolveKind();
604 12068: return true;
605 : }
606 :
23915: branch 1 taken
14736: branch 2 taken
607 38651: if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
608 23915: DeclContext *OuterCtx = findOuterContext(S);
48036: branch 1 taken
1: branch 2 taken
24608: branch 4 taken
23428: branch 5 taken
24608: branch 6 taken
23429: branch 7 taken
609 48037: for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
610 : Ctx = Ctx->getLookupParent()) {
611 : // We do not directly look into function or method contexts
612 : // (since all local variables are found via the identifier
613 : // changes) or in transparent contexts (since those entities
614 : // will be found in the nearest enclosing non-transparent
615 : // context).
13315: branch 1 taken
11293: branch 2 taken
2294: branch 4 taken
11021: branch 5 taken
11021: branch 6 taken
13587: branch 7 taken
616 24608: if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
617 13587: continue;
618 :
619 : // Perform qualified name lookup into this context.
620 : // FIXME: In some cases, we know that every name that could be found by
621 : // this qualified name lookup will also be on the identifier chain. For
622 : // example, inside a class without any base classes, we never need to
623 : // perform qualified lookup because all of the members are on top of the
624 : // identifier chain.
486: branch 1 taken
10535: branch 2 taken
625 11021: if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
626 486: return true;
627 : }
628 : }
629 : }
630 :
631 : // Stop if we ran out of scopes.
632 : // FIXME: This really, really shouldn't be happening.
1: branch 0 taken
39503: branch 1 taken
633 39504: if (!S) return false;
634 :
635 : // Collect UsingDirectiveDecls in all scopes, and recursively all
636 : // nominated namespaces by those using-directives.
637 : //
638 : // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
639 : // don't build it for each lookup!
640 :
641 39503: UnqualUsingDirectiveSet UDirs;
642 39503: UDirs.visitScopeChain(Initial, S);
643 39503: UDirs.done();
644 :
645 : // Lookup namespace scope, and global scope.
646 : // Unqualified name lookup in C++ requires looking into scopes
647 : // that aren't strictly lexical, and therefore we walk through the
648 : // context as well as walking through the scopes.
649 :
40888: branch 1 taken
6150: branch 2 taken
650 47038: for (; S; S = S->getParent()) {
651 40888: DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
40886: branch 0 taken
2: branch 1 taken
1: branch 3 taken
40885: branch 4 taken
40887: branch 5 taken
1: branch 6 taken
652 40888: if (Ctx && Ctx->isTransparentContext())
653 1: continue;
654 :
655 : // Check whether the IdResolver has anything in this scope.
656 40887: bool Found = false;
15224: branch 2 taken
39825: branch 3 taken
14162: branch 7 taken
1062: branch 8 taken
14162: branch 9 taken
40887: branch 10 taken
657 55049: for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
14063: branch 2 taken
99: branch 3 taken
658 14162: if (R.isAcceptableDecl(*I)) {
659 : // We found something. Look for anything else in our scope
660 : // with this same name and in an acceptable identifier
661 : // namespace, so that we can construct an overload set if we
662 : // need to.
663 14063: Found = true;
664 14063: R.addDecl(*I);
665 : }
666 : }
667 :
40885: branch 0 taken
2: branch 1 taken
668 40887: if (Ctx) {
669 : assert(Ctx->isFileContext() &&
40885: branch 1 taken
0: branch 2 not taken
670 40885: "We should have been looking only at file context here already.");
671 :
672 : // Look into context considering using-directives.
14732: branch 1 taken
26153: branch 2 taken
673 40885: if (CppNamespaceLookup(R, Context, Ctx, UDirs))
674 14732: Found = true;
675 : }
676 :
14739: branch 0 taken
26148: branch 1 taken
677 40887: if (Found) {
678 14739: R.resolveKind();
679 14739: return true;
680 : }
681 :
18614: branch 1 taken
7534: branch 2 taken
18614: branch 3 taken
0: branch 4 not taken
18614: branch 6 taken
0: branch 7 not taken
18614: branch 8 taken
7534: branch 9 taken
682 26148: if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
683 18614: return false;
684 : }
685 :
686 6150: return !R.empty();
687 : }
688 :
689 : /// @brief Perform unqualified name lookup starting from a given
690 : /// scope.
691 : ///
692 : /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
693 : /// used to find names within the current scope. For example, 'x' in
694 : /// @code
695 : /// int x;
696 : /// int f() {
697 : /// return x; // unqualified name look finds 'x' in the global scope
698 : /// }
699 : /// @endcode
700 : ///
701 : /// Different lookup criteria can find different names. For example, a
702 : /// particular scope can have both a struct and a function of the same
703 : /// name, and each can be found by certain lookup criteria. For more
704 : /// information about lookup criteria, see the documentation for the
705 : /// class LookupCriteria.
706 : ///
707 : /// @param S The scope from which unqualified name lookup will
708 : /// begin. If the lookup criteria permits, name lookup may also search
709 : /// in the parent scopes.
710 : ///
711 : /// @param Name The name of the entity that we are searching for.
712 : ///
713 : /// @param Loc If provided, the source location where we're performing
714 : /// name lookup. At present, this is only used to produce diagnostics when
715 : /// C library functions (like "malloc") are implicitly declared.
716 : ///
717 : /// @returns The result of name lookup, which includes zero or more
718 : /// declarations and possibly additional information used to diagnose
719 : /// ambiguities.
720 130854: bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
721 130854: DeclarationName Name = R.getLookupName();
53: branch 1 taken
130801: branch 2 taken
722 130854: if (!Name) return false;
723 :
724 130801: LookupNameKind NameKind = R.getLookupKind();
725 :
78743: branch 1 taken
52058: branch 2 taken
726 130801: if (!getLangOptions().CPlusPlus) {
727 : // Unqualified name lookup in C/Objective-C is purely lexical, so
728 : // search in the declarations attached to the name.
729 :
7877: branch 0 taken
70866: branch 1 taken
730 78743: if (NameKind == Sema::LookupRedeclarationWithLinkage) {
731 : // Find the nearest non-transparent declaration scope.
7877: branch 1 taken
0: branch 2 not taken
7865: branch 4 taken
12: branch 5 taken
0: branch 8 not taken
7865: branch 9 taken
0: branch 10 not taken
7877: branch 11 taken
732 15754: while (!(S->getFlags() & Scope::DeclScope) ||
733 : (S->getEntity() &&
734 : static_cast<DeclContext *>(S->getEntity())
735 : ->isTransparentContext()))
736 0: S = S->getParent();
737 : }
738 :
739 78743: unsigned IDNS = R.getIdentifierNamespace();
740 :
741 : // Scan up the scope chain looking for a decl that matches this
742 : // identifier that is in the appropriate namespace. This search
743 : // should not take long, as shadowing of names is uncommon, and
744 : // deep shadowing is extremely uncommon.
745 78743: bool LeftStartingScope = false;
746 :
44123: branch 3 taken
35693: branch 4 taken
747 158559: for (IdentifierResolver::iterator I = IdResolver.begin(Name),
748 78743: IEnd = IdResolver.end();
749 : I != IEnd; ++I)
43056: branch 2 taken
1067: branch 3 taken
750 44123: if ((*I)->isInIdentifierNamespace(IDNS)) {
382: branch 0 taken
42674: branch 1 taken
751 43056: if (NameKind == LookupRedeclarationWithLinkage) {
752 : // Determine whether this (or a previous) declaration is
753 : // out-of-scope.
377: branch 0 taken
5: branch 1 taken
29: branch 5 taken
348: branch 6 taken
29: branch 7 taken
353: branch 8 taken
754 382: if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
755 29: LeftStartingScope = true;
756 :
757 : // If we found something outside of our starting scope that
758 : // does not have linkage, skip it.
34: branch 0 taken
348: branch 1 taken
6: branch 4 taken
28: branch 5 taken
376: branch 6 taken
6: branch 7 taken
759 382: if (LeftStartingScope && !((*I)->hasLinkage()))
760 6: continue;
761 : }
762 :
763 43050: R.addDecl(*I);
764 :
58: branch 2 taken
42992: branch 3 taken
765 43050: if ((*I)->getAttr<OverloadableAttr>()) {
766 : // If this declaration has the "overloadable" attribute, we
767 : // might have a set of overloaded functions.
768 :
769 : // Figure out what scope the identifier is in.
91: branch 1 taken
0: branch 2 not taken
33: branch 6 taken
58: branch 7 taken
33: branch 8 taken
58: branch 9 taken
770 149: while (!(S->getFlags() & Scope::DeclScope) ||
771 : !S->isDeclScope(DeclPtrTy::make(*I)))
772 33: S = S->getParent();
773 :
774 : // Find the last declaration in this scope (with the same
775 : // name, naturally).
776 58: IdentifierResolver::iterator LastI = I;
94: branch 3 taken
58: branch 4 taken
777 152: for (++LastI; LastI != IEnd; ++LastI) {
0: branch 3 not taken
94: branch 4 taken
778 94: if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
779 0: break;
780 94: R.addDecl(*LastI);
781 : }
782 : }
783 :
784 43050: R.resolveKind();
785 :
786 43050: return true;
787 : }
788 : } else {
789 : // Perform C++ unqualified name lookup.
27293: branch 1 taken
24765: branch 2 taken
790 52058: if (CppLookupName(R, S))
791 27293: return true;
792 : }
793 :
794 : // If we didn't find a use of this identifier, and if the identifier
795 : // corresponds to a compiler builtin, create the decl object for the builtin
796 : // now, injecting it into translation unit scope, and return it.
25170: branch 0 taken
35288: branch 1 taken
13183: branch 2 taken
11987: branch 3 taken
797 60458: if (NameKind == LookupOrdinaryName ||
798 : NameKind == LookupRedeclarationWithLinkage) {
799 48471: IdentifierInfo *II = Name.getAsIdentifierInfo();
47396: branch 0 taken
1075: branch 1 taken
13453: branch 2 taken
33943: branch 3 taken
800 48471: if (II && AllowBuiltinCreation) {
801 : // If this is a builtin on this (or all) targets, create the decl.
1439: branch 1 taken
12014: branch 2 taken
802 13453: if (unsigned BuiltinID = II->getBuiltinID()) {
803 : // In C++, we don't have any predefined library functions like
804 : // 'malloc'. Instead, we'll just error.
228: branch 1 taken
1211: branch 2 taken
59: branch 4 taken
169: branch 5 taken
59: branch 6 taken
1380: branch 7 taken
805 1439: if (getLangOptions().CPlusPlus &&
806 : Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
807 59: return false;
808 :
809 : NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
810 : S, R.isForRedeclaration(),
811 1380: R.getNameLoc());
1378: branch 0 taken
2: branch 1 taken
812 1380: if (D) R.addDecl(D);
813 1380: return (D != NULL);
814 : }
815 : }
816 : }
817 59019: return false;
818 : }
819 :
820 : /// @brief Perform qualified name lookup in the namespaces nominated by
821 : /// using directives by the given context.
822 : ///
823 : /// C++98 [namespace.qual]p2:
824 : /// Given X::m (where X is a user-declared namespace), or given ::m
825 : /// (where X is the global namespace), let S be the set of all
826 : /// declarations of m in X and in the transitive closure of all
827 : /// namespaces nominated by using-directives in X and its used
828 : /// namespaces, except that using-directives are ignored in any
829 : /// namespace, including X, directly containing one or more
830 : /// declarations of m. No namespace is searched more than once in
831 : /// the lookup of a name. If S is the empty set, the program is
832 : /// ill-formed. Otherwise, if S has exactly one member, or if the
833 : /// context of the reference is a using-declaration
834 : /// (namespace.udecl), S is the required set of declarations of
835 : /// m. Otherwise if the use of m is not one that allows a unique
836 : /// declaration to be chosen from S, the program is ill-formed.
837 : /// C++98 [namespace.qual]p5:
838 : /// During the lookup of a qualified namespace member name, if the
839 : /// lookup finds more than one declaration of the member, and if one
840 : /// declaration introduces a class name or enumeration name and the
841 : /// other declarations either introduce the same object, the same
842 : /// enumerator or a set of functions, the non-type name hides the
843 : /// class or enumeration name if and only if the declarations are
844 : /// from the same namespace; otherwise (the declarations are from
845 : /// different namespaces), the program is ill-formed.
846 : static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
847 92: DeclContext *StartDC) {
92: branch 1 taken
0: branch 2 not taken
848 92: assert(StartDC->isFileContext() && "start context is not a file context");
849 :
850 92: DeclContext::udir_iterator I = StartDC->using_directives_begin();
851 92: DeclContext::udir_iterator E = StartDC->using_directives_end();
852 :
31: branch 0 taken
61: branch 1 taken
853 123: if (I == E) return false;
854 :
855 : // We have at least added all these contexts to the queue.
856 61: llvm::DenseSet<DeclContext*> Visited;
857 61: Visited.insert(StartDC);
858 :
859 : // We have not yet looked into these namespaces, much less added
860 : // their "using-children" to the queue.
861 61: llvm::SmallVector<NamespaceDecl*, 8> Queue;
862 :
863 : // We have already looked into the initial namespace; seed the queue
864 : // with its using-children.
107: branch 0 taken
61: branch 1 taken
865 168: for (; I != E; ++I) {
866 107: NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
107: branch 0 taken
0: branch 1 not taken
107: branch 3 taken
0: branch 4 not taken
867 107: if (Visited.insert(ND).second)
868 107: Queue.push_back(ND);
869 : }
870 :
871 : // The easiest way to implement the restriction in [namespace.qual]p5
872 : // is to check whether any of the individual results found a tag
873 : // and, if so, to declare an ambiguity if the final result is not
874 : // a tag.
875 61: bool FoundTag = false;
876 61: bool FoundNonTag = false;
877 :
878 61: LookupResult LocalR(LookupResult::Temporary, R);
879 :
880 61: bool Found = false;
122: branch 1 taken
61: branch 2 taken
881 244: while (!Queue.empty()) {
882 122: NamespaceDecl *ND = Queue.back();
883 122: Queue.pop_back();
884 :
885 : // We go through some convolutions here to avoid copying results
886 : // between LookupResults.
887 122: bool UseLocal = !R.empty();
50: branch 0 taken
72: branch 1 taken
888 122: LookupResult &DirectR = UseLocal ? LocalR : R;
122: branch 0 taken
0: branch 1 not taken
889 122: bool FoundDirect = LookupDirect(DirectR, ND);
890 :
88: branch 0 taken
34: branch 1 taken
891 122: if (FoundDirect) {
892 : // First do any local hiding.
893 88: DirectR.resolveKind();
894 :
895 : // If the local result is a tag, remember that.
5: branch 1 taken
83: branch 2 taken
896 88: if (DirectR.isSingleTagDecl())
897 5: FoundTag = true;
898 : else
899 83: FoundNonTag = true;
900 :
901 : // Append the local results to the total results if necessary.
32: branch 0 taken
56: branch 1 taken
902 88: if (UseLocal) {
903 32: R.addAllDecls(LocalR);
904 32: LocalR.clear();
905 : }
906 : }
907 :
908 : // If we find names in this namespace, ignore its using directives.
88: branch 0 taken
34: branch 1 taken
909 122: if (FoundDirect) {
910 88: Found = true;
911 88: continue;
912 : }
913 :
27: branch 3 taken
34: branch 4 taken
914 61: for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
915 27: NamespaceDecl *Nom = (*I)->getNominatedNamespace();
27: branch 0 taken
0: branch 1 not taken
15: branch 3 taken
12: branch 4 taken
916 27: if (Visited.insert(Nom).second)
917 15: Queue.push_back(Nom);
918 : }
919 : }
920 :
56: branch 0 taken
5: branch 1 taken
921 61: if (Found) {
4: branch 0 taken
52: branch 1 taken
2: branch 2 taken
2: branch 3 taken
922 58: if (FoundTag && FoundNonTag)
923 2: R.setAmbiguousQualifiedTagHiding();
924 : else
925 54: R.resolveKind();
926 : }
927 :
928 61: return Found;
929 : }
930 :
931 : /// \brief Perform qualified name lookup into a given context.
932 : ///
933 : /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
934 : /// names when the context of those names is explicit specified, e.g.,
935 : /// "std::vector" or "x->member", or as part of unqualified name lookup.
936 : ///
937 : /// Different lookup criteria can find different names. For example, a
938 : /// particular scope can have both a struct and a function of the same
939 : /// name, and each can be found by certain lookup criteria. For more
940 : /// information about lookup criteria, see the documentation for the
941 : /// class LookupCriteria.
942 : ///
943 : /// \param R captures both the lookup criteria and any lookup results found.
944 : ///
945 : /// \param LookupCtx The context in which qualified name lookup will
946 : /// search. If the lookup criteria permits, name lookup may also search
947 : /// in the parent contexts or (for C++ classes) base classes.
948 : ///
949 : /// \param InUnqualifiedLookup true if this is qualified name lookup that
950 : /// occurs as part of unqualified name lookup.
951 : ///
952 : /// \returns true if lookup succeeded, false if it failed.
953 : bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
954 17871: bool InUnqualifiedLookup) {
0: branch 0 not taken
17871: branch 1 taken
955 17871: assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
956 :
0: branch 2 not taken
17871: branch 3 taken
957 17871: if (!R.getLookupName())
958 0: return false;
959 :
960 : // Make sure that the declaration context is complete.
961 : assert((!isa<TagDecl>(LookupCtx) ||
962 : LookupCtx->isDependentContext() ||
963 : cast<TagDecl>(LookupCtx)->isDefinition() ||
964 : Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
965 : ->isBeingDefined()) &&
16722: branch 1 taken
1149: branch 2 taken
12725: branch 4 taken
3997: branch 5 taken
6637: branch 8 taken
6088: branch 9 taken
6637: branch 15 taken
0: branch 16 not taken
966 17871: "Declaration context must already be complete!");
967 :
968 : // Perform qualified name lookup into the LookupCtx.
5520: branch 1 taken
12351: branch 2 taken
969 17871: if (LookupDirect(R, LookupCtx)) {
970 5520: R.resolveKind();
3728: branch 1 taken
1792: branch 2 taken
971 5520: if (isa<CXXRecordDecl>(LookupCtx))
972 3728: R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
973 5520: return true;
974 : }
975 :
976 : // Don't descend into implied contexts for redeclarations.
977 : // C++98 [namespace.qual]p6:
978 : // In a declaration for a namespace member in which the
979 : // declarator-id is a qualified-id, given that the qualified-id
980 : // for the namespace member has the form
981 : // nested-name-specifier unqualified-id
982 : // the unqualified-id shall name a member of the namespace
983 : // designated by the nested-name-specifier.
984 : // See also [class.mfct]p5 and [class.static.data]p2.
6217: branch 1 taken
6134: branch 2 taken
985 12351: if (R.isForRedeclaration())
986 6217: return false;
987 :
988 : // If this is a namespace, look it up in the implied namespaces.
92: branch 1 taken
6042: branch 2 taken
989 6134: if (LookupCtx->isFileContext())
990 92: return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
991 :
992 : // If this isn't a C++ class, we aren't allowed to look into base
993 : // classes, we're done.
994 6042: CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
74: branch 0 taken
5968: branch 1 taken
995 6042: if (!LookupRec)
996 74: return false;
997 :
998 : // If we're performing qualified name lookup into a dependent class,
999 : // then we are actually looking into a current instantiation. If we have any
1000 : // dependent base classes, then we either have to delay lookup until
1001 : // template instantiation time (at which point all bases will be available)
1002 : // or we have to fail.
820: branch 0 taken
5148: branch 1 taken
16: branch 3 taken
804: branch 4 taken
7: branch 6 taken
9: branch 7 taken
7: branch 8 taken
5961: branch 9 taken
1003 5968: if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1004 : LookupRec->hasAnyDependentBases()) {
1005 7: R.setNotFoundInCurrentInstantiation();
1006 7: return false;
1007 : }
1008 :
1009 : // Perform lookup into our base classes.
1010 5961: CXXBasePaths Paths;
1011 5961: Paths.setOrigin(LookupRec);
1012 :
1013 : // Look for this member in our base classes
1014 5961: CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
4406: branch 1 taken
259: branch 2 taken
202: branch 3 taken
1094: branch 4 taken
0: branch 5 not taken
1015 5961: switch (R.getLookupKind()) {
1016 : case LookupOrdinaryName:
1017 : case LookupMemberName:
1018 : case LookupRedeclarationWithLinkage:
1019 4406: BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1020 4406: break;
1021 :
1022 : case LookupTagName:
1023 259: BaseCallback = &CXXRecordDecl::FindTagMember;
1024 259: break;
1025 :
1026 : case LookupUsingDeclName:
1027 : // This lookup is for redeclarations only.
1028 :
1029 : case LookupOperatorName:
1030 : case LookupNamespaceName:
1031 : case LookupObjCProtocolName:
1032 : case LookupObjCImplementationName:
1033 : // These lookups will never find a member in a C++ class (or base class).
1034 202: return false;
1035 :
1036 : case LookupNestedNameSpecifierName:
1037 1094: BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1038 : break;
1039 : }
1040 :
5334: branch 3 taken
425: branch 4 taken
1041 5759: if (!LookupRec->lookupInBases(BaseCallback,
1042 : R.getLookupName().getAsOpaquePtr(), Paths))
1043 5334: return false;
1044 :
1045 425: R.setNamingClass(LookupRec);
1046 :
1047 : // C++ [class.member.lookup]p2:
1048 : // [...] If the resulting set of declarations are not all from
1049 : // sub-objects of the same type, or the set has a nonstatic member
1050 : // and includes members from distinct sub-objects, there is an
1051 : // ambiguity and the program is ill-formed. Otherwise that set is
1052 : // the result of the lookup.
1053 : // FIXME: support using declarations!
1054 425: QualType SubobjectType;
1055 425: int SubobjectNumber = 0;
1056 425: AccessSpecifier SubobjectAccess = AS_private;
521: branch 4 taken
395: branch 5 taken
1057 916: for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1058 : Path != PathEnd; ++Path) {
1059 521: const CXXBasePathElement &PathElement = Path->back();
1060 :
1061 : // Pick the best (i.e. most permissive i.e. numerically lowest) access
1062 : // across all paths.
1063 521: SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1064 :
1065 : // Determine whether we're looking at a distinct sub-object or not.
425: branch 1 taken
96: branch 2 taken
1066 521: if (SubobjectType.isNull()) {
1067 : // This is the first subobject we've looked at. Record its type.
1068 425: SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1069 425: SubobjectNumber = PathElement.SubobjectNumber;
20: branch 4 taken
76: branch 5 taken
1070 96: } else if (SubobjectType
1071 : != Context.getCanonicalType(PathElement.Base->getType())) {
1072 : // We found members of the given name in two subobjects of
1073 : // different types. This lookup is ambiguous.
1074 20: R.setAmbiguousBaseSubobjectTypes(Paths);
1075 20: return true;
52: branch 0 taken
24: branch 1 taken
1076 76: } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1077 : // We have a different subobject of the same type.
1078 :
1079 : // C++ [class.member.lookup]p5:
1080 : // A static member, a nested type or an enumerator defined in
1081 : // a base class T can unambiguously be found even if an object
1082 : // has more than one base class subobject of type T.
1083 52: Decl *FirstDecl = *Path->Decls.first;
50: branch 1 taken
2: branch 2 taken
25: branch 4 taken
25: branch 5 taken
3: branch 7 taken
22: branch 8 taken
22: branch 9 taken
30: branch 10 taken
1084 52: if (isa<VarDecl>(FirstDecl) ||
1085 : isa<TypeDecl>(FirstDecl) ||
1086 : isa<EnumConstantDecl>(FirstDecl))
1087 30: continue;
1088 :
16: branch 1 taken
6: branch 2 taken
1089 22: if (isa<CXXMethodDecl>(FirstDecl)) {
1090 : // Determine whether all of the methods are static.
1091 16: bool AllMethodsAreStatic = true;
32: branch 2 taken
12: branch 3 taken
1092 44: for (DeclContext::lookup_iterator Func = Path->Decls.first;
1093 : Func != Path->Decls.second; ++Func) {
0: branch 1 not taken
32: branch 2 taken
1094 32: if (!isa<CXXMethodDecl>(*Func)) {
0: branch 1 not taken
0: branch 2 not taken
1095 0: assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1096 0: break;
1097 : }
1098 :
4: branch 2 taken
28: branch 3 taken
1099 32: if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1100 4: AllMethodsAreStatic = false;
1101 4: break;
1102 : }
1103 : }
1104 :
12: branch 0 taken
4: branch 1 taken
1105 16: if (AllMethodsAreStatic)
1106 12: continue;
1107 : }
1108 :
1109 : // We have found a nonstatic member name in multiple, distinct
1110 : // subobjects. Name lookup is ambiguous.
1111 10: R.setAmbiguousBaseSubobjects(Paths);
1112 10: return true;
1113 : }
1114 : }
1115 :
1116 : // Lookup in a base class succeeded; return these results.
1117 :
1118 : DeclContext::lookup_iterator I, E;
429: branch 3 taken
395: branch 4 taken
1119 824: for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1120 429: NamedDecl *D = *I;
1121 : AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1122 429: D->getAccess());
1123 429: R.addDecl(D, AS);
1124 : }
1125 395: R.resolveKind();
1126 395: return true;
1127 : }
1128 :
1129 : /// @brief Performs name lookup for a name that was parsed in the
1130 : /// source code, and may contain a C++ scope specifier.
1131 : ///
1132 : /// This routine is a convenience routine meant to be called from
1133 : /// contexts that receive a name and an optional C++ scope specifier
1134 : /// (e.g., "N::M::x"). It will then perform either qualified or
1135 : /// unqualified name lookup (with LookupQualifiedName or LookupName,
1136 : /// respectively) on the given name and return those results.
1137 : ///
1138 : /// @param S The scope from which unqualified name lookup will
1139 : /// begin.
1140 : ///
1141 : /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1142 : ///
1143 : /// @param Name The name of the entity that name lookup will
1144 : /// search for.
1145 : ///
1146 : /// @param Loc If provided, the source location where we're performing
1147 : /// name lookup. At present, this is only used to produce diagnostics when
1148 : /// C library functions (like "malloc") are implicitly declared.
1149 : ///
1150 : /// @param EnteringContext Indicates whether we are going to enter the
1151 : /// context of the scope-specifier SS (if present).
1152 : ///
1153 : /// @returns True if any decls were found (but possibly ambiguous)
1154 : bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
1155 29719: bool AllowBuiltinCreation, bool EnteringContext) {
29697: branch 0 taken
22: branch 1 taken
1: branch 3 taken
29696: branch 4 taken
1: branch 5 taken
29718: branch 6 taken
1156 29719: if (SS && SS->isInvalid()) {
1157 : // When the scope specifier is invalid, don't even look for
1158 : // anything.
1159 1: return false;
1160 : }
1161 :
29696: branch 0 taken
22: branch 1 taken
549: branch 3 taken
29147: branch 4 taken
549: branch 5 taken
29169: branch 6 taken
1162 29718: if (SS && SS->isSet()) {
546: branch 1 taken
3: branch 2 taken
1163 549: if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1164 : // We have resolved the scope specifier to a particular declaration
1165 : // contex, and will perform name lookup in that context.
542: branch 1 taken
4: branch 2 taken
2: branch 4 taken
540: branch 5 taken
2: branch 6 taken
544: branch 7 taken
1166 546: if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
1167 2: return false;
1168 :
1169 544: R.setContextRange(SS->getRange());
1170 :
1171 544: return LookupQualifiedName(R, DC);
1172 : }
1173 :
1174 : // We could not resolve the scope specified to a specific declaration
1175 : // context, which means that SS refers to an unknown specialization.
1176 : // Name lookup can't find anything in this case.
1177 3: return false;
1178 : }
1179 :
1180 : // Perform unqualified name lookup starting in the given scope.
1181 29169: return LookupName(R, S, AllowBuiltinCreation);
1182 : }
1183 :
1184 :
1185 : /// @brief Produce a diagnostic describing the ambiguity that resulted
1186 : /// from name lookup.
1187 : ///
1188 : /// @param Result The ambiguous name lookup result.
1189 : ///
1190 : /// @param Name The name of the entity that name lookup was
1191 : /// searching for.
1192 : ///
1193 : /// @param NameLoc The location of the name within the source code.
1194 : ///
1195 : /// @param LookupRange A source range that provides more
1196 : /// source-location information concerning the lookup itself. For
1197 : /// example, this range might highlight a nested-name-specifier that
1198 : /// precedes the name.
1199 : ///
1200 : /// @returns true
1201 33: bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
33: branch 1 taken
0: branch 2 not taken
1202 33: assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1203 :
1204 33: DeclarationName Name = Result.getLookupName();
1205 33: SourceLocation NameLoc = Result.getNameLoc();
1206 33: SourceRange LookupRange = Result.getContextRange();
1207 :
6: branch 1 taken
15: branch 2 taken
1: branch 3 taken
11: branch 4 taken
0: branch 5 not taken
1208 33: switch (Result.getAmbiguityKind()) {
1209 : case LookupResult::AmbiguousBaseSubobjects: {
1210 6: CXXBasePaths *Paths = Result.getBasePaths();
1211 6: QualType SubobjectType = Paths->front().back().Base->getType();
1212 : Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1213 : << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1214 6: << LookupRange;
1215 :
1216 6: DeclContext::lookup_iterator Found = Paths->front().Decls.first;
4: branch 1 taken
4: branch 2 taken
2: branch 5 taken
2: branch 6 taken
2: branch 7 taken
6: branch 8 taken
1217 14: while (isa<CXXMethodDecl>(*Found) &&
1218 : cast<CXXMethodDecl>(*Found)->isStatic())
1219 2: ++Found;
1220 :
1221 6: Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1222 :
1223 6: return true;
1224 : }
1225 :
1226 : case LookupResult::AmbiguousBaseSubobjectTypes: {
1227 : Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1228 15: << Name << LookupRange;
1229 :
1230 15: CXXBasePaths *Paths = Result.getBasePaths();
1231 15: std::set<Decl *> DeclsPrinted;
30: branch 3 taken
15: branch 4 taken
1232 60: for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1233 15: PathEnd = Paths->end();
1234 : Path != PathEnd; ++Path) {
1235 30: Decl *D = *Path->Decls.first;
30: branch 1 taken
0: branch 2 not taken
1236 30: if (DeclsPrinted.insert(D).second)
1237 30: Diag(D->getLocation(), diag::note_ambiguous_member_found);
1238 : }
1239 :
1240 15: return true;
1241 : }
1242 :
1243 : case LookupResult::AmbiguousTagHiding: {
1244 1: Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1245 :
1246 1: llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1247 :
1248 1: LookupResult::iterator DI, DE = Result.end();
2: branch 3 taken
1: branch 4 taken
1249 3: for (DI = Result.begin(); DI != DE; ++DI)
1: branch 2 taken
1: branch 3 taken
1250 2: if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1251 1: TagDecls.insert(TD);
1252 1: Diag(TD->getLocation(), diag::note_hidden_tag);
1253 : }
1254 :
2: branch 3 taken
1: branch 4 taken
1255 3: for (DI = Result.begin(); DI != DE; ++DI)
1: branch 2 taken
1: branch 3 taken
1256 2: if (!isa<TagDecl>(*DI))
1257 1: Diag((*DI)->getLocation(), diag::note_hiding_object);
1258 :
1259 : // For recovery purposes, go ahead and implement the hiding.
1260 1: LookupResult::Filter F = Result.makeFilter();
2: branch 1 taken
1: branch 2 taken
1261 4: while (F.hasNext()) {
1: branch 2 taken
1: branch 3 taken
1262 2: if (TagDecls.count(F.next()))
1263 1: F.erase();
1264 : }
1265 1: F.done();
1266 :
1267 1: return true;
1268 : }
1269 :
1270 : case LookupResult::AmbiguousReference: {
1271 11: Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1272 :
1273 11: LookupResult::iterator DI = Result.begin(), DE = Result.end();
25: branch 2 taken
11: branch 3 taken
1274 36: for (; DI != DE; ++DI)
1275 25: Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1276 :
1277 11: return true;
1278 : }
1279 : }
1280 :
1281 0: llvm_unreachable("unknown ambiguity kind");
1282 : return true;
1283 : }
1284 :
1285 : static void
1286 : addAssociatedClassesAndNamespaces(QualType T,
1287 : ASTContext &Context,
1288 : Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1289 : Sema::AssociatedClassSet &AssociatedClasses);
1290 :
1291 : static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1292 1080: DeclContext *Ctx) {
1043: branch 1 taken
37: branch 2 taken
1293 1080: if (Ctx->isFileContext())
1294 1043: Namespaces.insert(Ctx);
1295 1080: }
1296 :
1297 : // \brief Add the associated classes and namespaces for argument-dependent
1298 : // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1299 : static void
1300 : addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
1301 : ASTContext &Context,
1302 : Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1303 48: Sema::AssociatedClassSet &AssociatedClasses) {
1304 : // C++ [basic.lookup.koenig]p2, last bullet:
1305 : // -- [...] ;
0: branch 1 not taken
35: branch 2 taken
0: branch 3 not taken
13: branch 4 taken
0: branch 5 not taken
0: branch 6 not taken
1306 48: switch (Arg.getKind()) {
1307 : case TemplateArgument::Null:
1308 0: break;
1309 :
1310 : case TemplateArgument::Type:
1311 : // [...] the namespaces and classes associated with the types of the
1312 : // template arguments provided for template type parameters (excluding
1313 : // template template parameters)
1314 : addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1315 : AssociatedNamespaces,
1316 35: AssociatedClasses);
1317 35: break;
1318 :
1319 : case TemplateArgument::Template: {
1320 : // [...] the namespaces in which any template template arguments are
1321 : // defined; and the classes in which any member templates used as
1322 : // template template arguments are defined.
1323 0: TemplateName Template = Arg.getAsTemplate();
0: branch 0 not taken
0: branch 1 not taken
1324 0: if (ClassTemplateDecl *ClassTemplate
1325 0: = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1326 0: DeclContext *Ctx = ClassTemplate->getDeclContext();
0: branch 1 not taken
0: branch 2 not taken
1327 0: if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1328 0: AssociatedClasses.insert(EnclosingClass);
1329 : // Add the associated namespace for this class.
0: branch 1 not taken
0: branch 2 not taken
1330 0: while (Ctx->isRecord())
1331 0: Ctx = Ctx->getParent();
1332 0: CollectNamespace(AssociatedNamespaces, Ctx);
1333 : }
1334 0: break;
1335 : }
1336 :
1337 : case TemplateArgument::Declaration:
1338 : case TemplateArgument::Integral:
1339 : case TemplateArgument::Expression:
1340 : // [Note: non-type template arguments do not contribute to the set of
1341 : // associated namespaces. ]
1342 13: break;
1343 :
1344 : case TemplateArgument::Pack:
0: branch 1 not taken
0: branch 2 not taken
1345 0: for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1346 0: PEnd = Arg.pack_end();
1347 : P != PEnd; ++P)
1348 : addAssociatedClassesAndNamespaces(*P, Context,
1349 : AssociatedNamespaces,
1350 0: AssociatedClasses);
1351 : break;
1352 : }
1353 48: }
1354 :
1355 : // \brief Add the associated classes and namespaces for
1356 : // argument-dependent lookup with an argument of class type
1357 : // (C++ [basic.lookup.koenig]p2).
1358 : static void
1359 : addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1360 : ASTContext &Context,
1361 : Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1362 715: Sema::AssociatedClassSet &AssociatedClasses) {
1363 : // C++ [basic.lookup.koenig]p2:
1364 : // [...]
1365 : // -- If T is a class type (including unions), its associated
1366 : // classes are: the class itself; the class of which it is a
1367 : // member, if any; and its direct and indirect base
1368 : // classes. Its associated namespaces are the namespaces in
1369 : // which its associated classes are defined.
1370 :
1371 : // Add the class of which it is a member, if any.
1372 715: DeclContext *Ctx = Class->getDeclContext();
4: branch 1 taken
711: branch 2 taken
1373 715: if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1374 4: AssociatedClasses.insert(EnclosingClass);
1375 : // Add the associated namespace for this class.
4: branch 1 taken
715: branch 2 taken
1376 1434: while (Ctx->isRecord())
1377 4: Ctx = Ctx->getParent();
1378 715: CollectNamespace(AssociatedNamespaces, Ctx);
1379 :
1380 : // Add the class itself. If we've already seen this class, we don't
1381 : // need to visit base classes.
117: branch 1 taken
598: branch 2 taken
1382 715: if (!AssociatedClasses.insert(Class))
1383 117: return;
1384 :
1385 : // -- If T is a template-id, its associated namespaces and classes are
1386 : // the namespace in which the template is defined; for member
1387 : // templates, the member template’s class; the namespaces and classes
1388 : // associated with the types of the template arguments provided for
1389 : // template type parameters (excluding template template parameters); the
1390 : // namespaces in which any template template arguments are defined; and
1391 : // the classes in which any member templates used as template template
1392 : // arguments are defined. [Note: non-type template arguments do not
1393 : // contribute to the set of associated namespaces. ]
46: branch 0 taken
552: branch 1 taken
1394 598: if (ClassTemplateSpecializationDecl *Spec
1395 598: = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1396 46: DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1: branch 1 taken
45: branch 2 taken
1397 46: if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1398 1: AssociatedClasses.insert(EnclosingClass);
1399 : // Add the associated namespace for this class.
1: branch 1 taken
46: branch 2 taken
1400 93: while (Ctx->isRecord())
1401 1: Ctx = Ctx->getParent();
1402 46: CollectNamespace(AssociatedNamespaces, Ctx);
1403 :
1404 46: const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
48: branch 1 taken
46: branch 2 taken
1405 94: for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1406 : addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1407 : AssociatedNamespaces,
1408 48: AssociatedClasses);
1409 : }
1410 :
1411 : // Only recurse into base classes for complete types.
11: branch 1 taken
587: branch 2 taken
1412 598: if (!Class->hasDefinition()) {
1413 : // FIXME: we might need to instantiate templates here
1414 11: return;
1415 : }
1416 :
1417 : // Add direct and indirect base classes along with their associated
1418 : // namespaces.
1419 587: llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1420 587: Bases.push_back(Class);
640: branch 1 taken
587: branch 2 taken
1421 1814: while (!Bases.empty()) {
1422 : // Pop this class off the stack.
1423 640: Class = Bases.back();
1424 640: Bases.pop_back();
1425 :
1426 : // Visit the base classes.
216: branch 1 taken
640: branch 2 taken
1427 1496: for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1428 640: BaseEnd = Class->bases_end();
1429 : Base != BaseEnd; ++Base) {
1430 216: const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1431 : // In dependent contexts, we do ADL twice, and the first time around,
1432 : // the base type might be a dependent TemplateSpecializationType, or a
1433 : // TemplateTypeParmType. If that happens, simply ignore it.
1434 : // FIXME: If we want to support export, we probably need to add the
1435 : // namespace of the template in a TemplateSpecializationType, or even
1436 : // the classes and namespaces of known non-dependent arguments.
0: branch 0 not taken
216: branch 1 taken
1437 216: if (!BaseType)
1438 0: continue;
1439 216: CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
199: branch 1 taken
17: branch 2 taken
1440 216: if (AssociatedClasses.insert(BaseDecl)) {
1441 : // Find the associated namespace for this base class.
1442 199: DeclContext *BaseCtx = BaseDecl->getDeclContext();
0: branch 1 not taken
199: branch 2 taken
1443 398: while (BaseCtx->isRecord())
1444 0: BaseCtx = BaseCtx->getParent();
1445 199: CollectNamespace(AssociatedNamespaces, BaseCtx);
1446 :
1447 : // Make sure we visit the bases of this base class.
53: branch 2 taken
146: branch 3 taken
1448 199: if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1449 53: Bases.push_back(BaseDecl);
1450 : }
1451 : }
1452 587: }
1453 : }
1454 :
1455 : // \brief Add the associated classes and namespaces for
1456 : // argument-dependent lookup with an argument of type T
1457 : // (C++ [basic.lookup.koenig]p2).
1458 : static void
1459 : addAssociatedClassesAndNamespaces(QualType T,
1460 : ASTContext &Context,
1461 : Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1462 2602: Sema::AssociatedClassSet &AssociatedClasses) {
1463 : // C++ [basic.lookup.koenig]p2:
1464 : //
1465 : // For each argument type T in the function call, there is a set
1466 : // of zero or more associated namespaces and a set of zero or more
1467 : // associated classes to be considered. The sets of namespaces and
1468 : // classes is determined entirely by the types of the function
1469 : // arguments (and the namespace of any template template
1470 : // argument). Typedef names and using-declarations used to specify
1471 : // the types do not contribute to this set. The sets of namespaces
1472 : // and classes are determined in the following way:
1473 2602: T = Context.getCanonicalType(T).getUnqualifiedType();
1474 :
1475 : // -- If T is a pointer to U or an array of U, its associated
1476 : // namespaces and classes are those associated with U.
1477 : //
1478 : // We handle this by unwrapping pointer and array types immediately,
1479 : // to avoid unnecessary recursion.
1480 630: while (true) {
163: branch 2 taken
3069: branch 3 taken
1481 3232: if (const PointerType *Ptr = T->getAs<PointerType>())
1482 163: T = Ptr->getPointeeType();
467: branch 1 taken
2602: branch 2 taken
1483 3069: else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1484 467: T = Ptr->getElementType();
1485 : else
1486 2602: break;
1487 : }
1488 :
1489 : // -- If T is a fundamental type, its associated sets of
1490 : // namespaces and classes are both empty.
1499: branch 2 taken
1103: branch 3 taken
1491 2602: if (T->getAs<BuiltinType>())
1492 1499: return;
1493 :
1494 : // -- If T is a class type (including unions), its associated
1495 : // classes are: the class itself; the class of which it is a
1496 : // member, if any; and its direct and indirect base
1497 : // classes. Its associated namespaces are the namespaces in
1498 : // which its associated classes are defined.
682: branch 2 taken
421: branch 3 taken
1499 1103: if (const RecordType *ClassType = T->getAs<RecordType>())
682: branch 0 taken
0: branch 1 not taken
1500 682: if (CXXRecordDecl *ClassDecl
1501 682: = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1502 : addAssociatedClassesAndNamespaces(ClassDecl, Context,
1503 : AssociatedNamespaces,
1504 682: AssociatedClasses);
1505 682: return;
1506 : }
1507 :
1508 : // -- If T is an enumeration type, its associated namespace is
1509 : // the namespace in which it is defined. If it is class
1510 : // member, its associated class is the member’s class; else
1511 : // it has no associated class.
120: branch 2 taken
301: branch 3 taken
1512 421: if (const EnumType *EnumT = T->getAs<EnumType>()) {
1513 120: EnumDecl *Enum = EnumT->getDecl();
1514 :
1515 120: DeclContext *Ctx = Enum->getDeclContext();
51: branch 1 taken
69: branch 2 taken
1516 120: if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1517 51: AssociatedClasses.insert(EnclosingClass);
1518 :
1519 : // Add the associated namespace for this class.
81: branch 1 taken
120: branch 2 taken
1520 321: while (Ctx->isRecord())
1521 81: Ctx = Ctx->getParent();
1522 120: CollectNamespace(AssociatedNamespaces, Ctx);
1523 :
1524 120: return;
1525 : }
1526 :
1527 : // -- If T is a function type, its associated namespaces and
1528 : // classes are those associated with the function parameter
1529 : // types and those associated with the return type.
99: branch 2 taken
202: branch 3 taken
1530 301: if (const FunctionType *FnType = T->getAs<FunctionType>()) {
1531 : // Return type
1532 : addAssociatedClassesAndNamespaces(FnType->getResultType(),
1533 : Context,
1534 99: AssociatedNamespaces, AssociatedClasses);
1535 :
1536 99: const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
0: branch 0 not taken
99: branch 1 taken
1537 99: if (!Proto)
1538 0: return;
1539 :
1540 : // Argument types
85: branch 1 taken
99: branch 2 taken
1541 283: for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1542 99: ArgEnd = Proto->arg_type_end();
1543 : Arg != ArgEnd; ++Arg)
1544 : addAssociatedClassesAndNamespaces(*Arg, Context,
1545 85: AssociatedNamespaces, AssociatedClasses);
1546 :
1547 99: return;
1548 : }
1549 :
1550 : // -- If T is a pointer to a member function of a class X, its
1551 : // associated namespaces and classes are those associated
1552 : // with the function parameter types and return type,
1553 : // together with those associated with X.
1554 : //
1555 : // -- If T is a pointer to a data member of class X, its
1556 : // associated namespaces and classes are those associated
1557 : // with the member type together with those associated with
1558 : // X.
33: branch 2 taken
169: branch 3 taken
1559 202: if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
1560 : // Handle the type that the pointer to member points to.
1561 : addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1562 : Context,
1563 : AssociatedNamespaces,
1564 33: AssociatedClasses);
1565 :
1566 : // Handle the class type into which this points.
33: branch 2 taken
0: branch 3 not taken
1567 33: if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
1568 : addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1569 : Context,
1570 : AssociatedNamespaces,
1571 33: AssociatedClasses);
1572 :
1573 33: return;
1574 : }
1575 :
1576 : // FIXME: What about block pointers?
1577 : // FIXME: What about Objective-C message sends?
1578 : }
1579 :
1580 : /// \brief Find the associated classes and namespaces for
1581 : /// argument-dependent lookup for a call with the given set of
1582 : /// arguments.
1583 : ///
1584 : /// This routine computes the sets of associated classes and associated
1585 : /// namespaces searched by argument-dependent lookup
1586 : /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1587 : void
1588 : Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1589 : AssociatedNamespaceSet &AssociatedNamespaces,
1590 1633: AssociatedClassSet &AssociatedClasses) {
1591 1633: AssociatedNamespaces.clear();
1592 1633: AssociatedClasses.clear();
1593 :
1594 : // C++ [basic.lookup.koenig]p2:
1595 : // For each argument type T in the function call, there is a set
1596 : // of zero or more associated namespaces and a set of zero or more
1597 : // associated classes to be considered. The sets of namespaces and
1598 : // classes is determined entirely by the types of the function
1599 : // arguments (and the namespace of any template template
1600 : // argument).
47: branch 1 taken
1: branch 2 taken
2316: branch 3 taken
1633: branch 4 taken
1601 3997: for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1602 2316: Expr *Arg = Args[ArgIdx];
1603 :
2268: branch 3 taken
48: branch 4 taken
1604 2316: if (Arg->getType() != Context.OverloadTy) {
1605 : addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1606 : AssociatedNamespaces,
1607 2268: AssociatedClasses);
1608 2268: continue;
1609 : }
1610 :
1611 : // [...] In addition, if the argument is the name or address of a
1612 : // set of overloaded functions and/or function templates, its
1613 : // associated classes and namespaces are the union of those
1614 : // associated with each of the members of the set: the namespace
1615 : // in which the function or function template is defined and the
1616 : // classes and namespaces associated with its (non-dependent)
1617 : // parameter types and return type.
1618 48: Arg = Arg->IgnoreParens();
26: branch 1 taken
22: branch 2 taken
1619 48: if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
26: branch 1 taken
0: branch 2 not taken
1620 26: if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1621 26: Arg = unaryOp->getSubExpr();
1622 :
1623 : // TODO: avoid the copies. This should be easy when the cases
1624 : // share a storage implementation.
1625 48: llvm::SmallVector<NamedDecl*, 8> Functions;
1626 :
1: branch 1 taken
47: branch 2 taken
1627 48: if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1628 47: Functions.append(ULE->decls_begin(), ULE->decls_end());
1629 : else
1630 1: continue;
1631 :
82: branch 1 taken
47: branch 2 taken
1632 176: for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1633 47: E = Functions.end(); I != E; ++I) {
1634 : // Look through any using declarations to find the underlying function.
1635 82: NamedDecl *Fn = (*I)->getUnderlyingDecl();
1636 :
1637 82: FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
39: branch 0 taken
43: branch 1 taken
1638 82: if (!FDecl)
1639 39: FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
1640 :
1641 : // Add the classes and namespaces associated with the parameter
1642 : // types and return type of this function.
1643 : addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1644 : AssociatedNamespaces,
1645 82: AssociatedClasses);
1646 : }
1647 : }
1648 1633: }
1649 :
1650 : /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1651 : /// an acceptable non-member overloaded operator for a call whose
1652 : /// arguments have types T1 (and, if non-empty, T2). This routine
1653 : /// implements the check in C++ [over.match.oper]p3b2 concerning
1654 : /// enumeration types.
1655 : static bool
1656 : IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1657 : QualType T1, QualType T2,
1658 166: ASTContext &Context) {
162: branch 2 taken
4: branch 3 taken
157: branch 5 taken
5: branch 6 taken
0: branch 9 not taken
157: branch 10 taken
4: branch 11 taken
162: branch 12 taken
1659 166: if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1660 4: return true;
1661 :
26: branch 2 taken
136: branch 3 taken
26: branch 5 taken
0: branch 6 not taken
8: branch 9 taken
18: branch 10 taken
144: branch 11 taken
18: branch 12 taken
1662 162: if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1663 144: return true;
1664 :
1665 18: const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
0: branch 1 not taken
18: branch 2 taken
1666 18: if (Proto->getNumArgs() < 1)
1667 0: return false;
1668 :
16: branch 2 taken
2: branch 3 taken
1669 18: if (T1->isEnumeralType()) {
1670 16: QualType ArgType = Proto->getArgType(0).getNonReferenceType();
0: branch 1 not taken
16: branch 2 taken
1671 16: if (Context.hasSameUnqualifiedType(T1, ArgType))
1672 0: return true;
1673 : }
1674 :
0: branch 1 not taken
18: branch 2 taken
1675 18: if (Proto->getNumArgs() < 2)
1676 0: return false;
1677 :
18: branch 1 taken
0: branch 2 not taken
14: branch 5 taken
4: branch 6 taken
14: branch 7 taken
4: branch 8 taken
1678 18: if (!T2.isNull() && T2->isEnumeralType()) {
1679 14: QualType ArgType = Proto->getArgType(1).getNonReferenceType();
0: branch 1 not taken
14: branch 2 taken
1680 14: if (Context.hasSameUnqualifiedType(T2, ArgType))
1681 0: return true;
1682 : }
1683 :
1684 18: return false;
1685 : }
1686 :
1687 : NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1688 : LookupNameKind NameKind,
1689 25842: RedeclarationKind Redecl) {
1690 25842: LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1691 25842: LookupName(R, S);
1692 25842: return R.getAsSingle<NamedDecl>();
1693 : }
1694 :
1695 : /// \brief Find the protocol with the given name, if any.
1696 2010: ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
1697 2010: Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
1698 2010: return cast_or_null<ObjCProtocolDecl>(D);
1699 : }
1700 :
1701 : void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1702 : QualType T1, QualType T2,
1703 540: UnresolvedSetImpl &Functions) {
1704 : // C++ [over.match.oper]p3:
1705 : // -- The set of non-member candidates is the result of the
1706 : // unqualified lookup of operator@ in the context of the
1707 : // expression according to the usual rules for name lookup in
1708 : // unqualified function calls (3.4.2) except that all member
1709 : // functions are ignored. However, if no operand has a class
1710 : // type, only those non-member functions in the lookup set
1711 : // that have a first parameter of type T1 or "reference to
1712 : // (possibly cv-qualified) T1", when T1 is an enumeration
1713 : // type, or (if there is a right operand) a second parameter
1714 : // of type T2 or "reference to (possibly cv-qualified) T2",
1715 : // when T2 is an enumeration type, are candidate functions.
1716 540: DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1717 540: LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1718 540: LookupName(Operators, S);
1719 :
540: branch 1 taken
0: branch 2 not taken
1720 540: assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1721 :
493: branch 1 taken
47: branch 2 taken
1722 540: if (Operators.empty())
1723 493: return;
1724 :
70: branch 4 taken
47: branch 5 taken
1725 117: for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1726 : Op != OpEnd; ++Op) {
68: branch 2 taken
2: branch 3 taken
1727 70: if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
58: branch 1 taken
10: branch 2 taken
1728 68: if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1729 58: Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
2: branch 0 taken
0: branch 1 not taken
1730 2: } else if (FunctionTemplateDecl *FunTmpl
1731 2: = dyn_cast<FunctionTemplateDecl>(*Op)) {
1732 : // FIXME: friend operators?
1733 : // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
1734 : // later?
2: branch 2 taken
0: branch 3 not taken
1735 2: if (!FunTmpl->getDeclContext()->isRecord())
1736 2: Functions.addDecl(FunTmpl, Op.getAccess());
1737 : }
47: branch 1 taken
493: branch 2 taken
1738 540: }
1739 : }
1740 :
1741 376: void ADLResult::insert(NamedDecl *New) {
1742 376: NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1743 :
1744 : // If we haven't yet seen a decl for this key, or the last decl
1745 : // was exactly this one, we're done.
3: branch 0 taken
373: branch 1 taken
0: branch 2 not taken
3: branch 3 taken
1746 376: if (Old == 0 || Old == New) {
1747 373: Old = New;
1748 373: return;
1749 : }
1750 :
1751 : // Otherwise, decide which is a more recent redeclaration.
1752 : FunctionDecl *OldFD, *NewFD;
0: branch 1 not taken
3: branch 2 taken
1753 3: if (isa<FunctionTemplateDecl>(New)) {
1754 0: OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1755 0: NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1756 : } else {
1757 3: OldFD = cast<FunctionDecl>(Old);
1758 3: NewFD = cast<FunctionDecl>(New);
1759 : }
1760 :
1761 3: FunctionDecl *Cursor = NewFD;
1762 0: while (true) {
1763 3: Cursor = Cursor->getPreviousDeclaration();
1764 :
1765 : // If we got to the end without finding OldFD, OldFD is the newer
1766 : // declaration; leave things as they are.
3: branch 0 taken
0: branch 1 not taken
1767 3: if (!Cursor) return;
1768 :
1769 : // If we do find OldFD, then NewFD is newer.
0: branch 0 not taken
3: branch 1 taken
1770 3: if (Cursor == OldFD) break;
1771 :
1772 : // Otherwise, keep looking.
1773 : }
1774 :
1775 3: Old = New;
1776 : }
1777 :
1778 : void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
1779 : Expr **Args, unsigned NumArgs,
1780 1633: ADLResult &Result) {
1781 : // Find all of the associated namespaces and classes based on the
1782 : // arguments we have.
1783 1633: AssociatedNamespaceSet AssociatedNamespaces;
1784 1633: AssociatedClassSet AssociatedClasses;
1785 : FindAssociatedClassesAndNamespaces(Args, NumArgs,
1786 : AssociatedNamespaces,
1787 1633: AssociatedClasses);
1788 :
1789 1633: QualType T1, T2;
401: branch 0 taken
1232: branch 1 taken
1790 1633: if (Operator) {
1791 401: T1 = Args[0]->getType();
304: branch 0 taken
97: branch 1 taken
1792 401: if (NumArgs >= 2)
1793 304: T2 = Args[1]->getType();
1794 : }
1795 :
1796 : // C++ [basic.lookup.argdep]p3:
1797 : // Let X be the lookup set produced by unqualified lookup (3.4.1)
1798 : // and let Y be the lookup set produced by argument dependent
1799 : // lookup (defined as follows). If X contains [...] then Y is
1800 : // empty. Otherwise Y is the set of declarations found in the
1801 : // namespaces associated with the argument types as described
1802 : // below. The set of declarations found by the lookup of the name
1803 : // is the union of X and Y.
1804 : //
1805 : // Here, we compute Y and add its members to the overloaded
1806 : // candidate set.
617: branch 3 taken
1633: branch 4 taken
1807 3883: for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1808 1633: NSEnd = AssociatedNamespaces.end();
1809 : NS != NSEnd; ++NS) {
1810 : // When considering an associated namespace, the lookup is the
1811 : // same as the lookup performed when the associated namespace is
1812 : // used as a qualifier (3.4.3.2) except that:
1813 : //
1814 : // -- Any using-directives in the associated namespace are
1815 : // ignored.
1816 : //
1817 : // -- Any namespace-scope friend functions declared in
1818 : // associated classes are visible within their respective
1819 : // namespaces even if they are not visible during an ordinary
1820 : // lookup (11.4).
1821 : DeclContext::lookup_iterator I, E;
392: branch 4 taken
617: branch 5 taken
1822 1009: for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
1823 392: NamedDecl *D = *I;
1824 : // If the only declaration here is an ordinary friend, consider
1825 : // it only if it was declared in an associated classes.
22: branch 1 taken
370: branch 2 taken
1826 392: if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
1827 22: DeclContext *LexDC = D->getLexicalDeclContext();
0: branch 2 not taken
22: branch 3 taken
1828 22: if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1829 0: continue;
1830 : }
1831 :
7: branch 1 taken
385: branch 2 taken
1832 392: if (isa<UsingShadowDecl>(D))
1833 7: D = cast<UsingShadowDecl>(D)->getTargetDecl();
1834 :
312: branch 1 taken
80: branch 2 taken
1835 392: if (isa<FunctionDecl>(D)) {
98: branch 0 taken
214: branch 1 taken
8: branch 4 taken
90: branch 5 taken
8: branch 6 taken
304: branch 7 taken
1836 312: if (Operator &&
1837 : !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1838 : T1, T2, Context))
1839 8: continue;
8: branch 1 taken
72: branch 2 taken
1840 80: } else if (!isa<FunctionTemplateDecl>(D))
1841 8: continue;
1842 :
1843 376: Result.insert(D);
1844 : }
1845 1633: }
1846 1633: }
1847 :
1848 : //----------------------------------------------------------------------------
1849 : // Search for all visible declarations.
1850 : //----------------------------------------------------------------------------
223: branch 0 taken
223: branch 1 taken
0: branch 3 not taken
0: branch 4 not taken
0: branch 6 not taken
223: branch 7 taken
1851 223: VisibleDeclConsumer::~VisibleDeclConsumer() { }
1852 :
1853 : namespace {
1854 :
1855 : class ShadowContextRAII;
1856 :
1857 442: class VisibleDeclsRecord {
1858 : public:
1859 : /// \brief An entry in the shadow map, which is optimized to store a
1860 : /// single declaration (the common case) but can also store a list
1861 : /// of declarations.
1862 1768: class ShadowMapEntry {
1863 : typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1864 :
1865 : /// \brief Contains either the solitary NamedDecl * or a vector
1866 : /// of declarations.
1867 : llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1868 :
1869 : public:
1870 1674: ShadowMapEntry() : DeclOrVector() { }
1871 :
1872 : void Add(NamedDecl *ND);
1873 : void Destroy();
1874 :
1875 : // Iteration.
1876 : typedef NamedDecl **iterator;
1877 : iterator begin();
1878 : iterator end();
1879 : };
1880 :
1881 : private:
1882 : /// \brief A mapping from declaration names to the declarations that have
1883 : /// this name within a particular scope.
1884 : typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1885 :
1886 : /// \brief A list of shadow maps, which is used to model name hiding.
1887 : std::list<ShadowMap> ShadowMaps;
1888 :
1889 : /// \brief The declaration contexts we have already visited.
1890 : llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1891 :
1892 : friend class ShadowContextRAII;
1893 :
1894 : public:
1895 : /// \brief Determine whether we have already visited this context
1896 : /// (and, if not, note that we are going to visit that context now).
1897 330: bool visitedContext(DeclContext *Ctx) {
1898 330: return !VisitedContexts.insert(Ctx);
1899 : }
1900 :
1901 : /// \brief Determine whether the given declaration is hidden in the
1902 : /// current scope.
1903 : ///
1904 : /// \returns the declaration that hides the given declaration, or
1905 : /// NULL if no such declaration exists.
1906 : NamedDecl *checkHidden(NamedDecl *ND);
1907 :
1908 : /// \brief Add a declaration to the current shadow map.
1909 2750: void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1910 : };
1911 :
1912 : /// \brief RAII object that records when we've entered a shadow context.
1913 : class ShadowContextRAII {
1914 : VisibleDeclsRecord &Visible;
1915 :
1916 : typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1917 :
1918 : public:
1919 640: ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1920 640: Visible.ShadowMaps.push_back(ShadowMap());
1921 640: }
1922 :
1923 640: ~ShadowContextRAII() {
1674: branch 5 taken
640: branch 6 taken
1924 2954: for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1925 640: EEnd = Visible.ShadowMaps.back().end();
1926 : E != EEnd;
1927 : ++E)
1928 1674: E->second.Destroy();
1929 :
1930 640: Visible.ShadowMaps.pop_back();
1931 640: }
1932 : };
1933 :
1934 : } // end anonymous namespace
1935 :
1936 2750: void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1674: branch 1 taken
1076: branch 2 taken
1937 2750: if (DeclOrVector.isNull()) {
1938 : // 0 - > 1 elements: just set the single element information.
1939 1674: DeclOrVector = ND;
1940 1674: return;
1941 : }
1942 :
1028: branch 1 taken
48: branch 2 taken
1943 1076: if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1944 : // 1 -> 2 elements: create the vector of results and push in the
1945 : // existing declaration.
1946 1028: DeclVector *Vec = new DeclVector;
1947 1028: Vec->push_back(PrevND);
1948 1028: DeclOrVector = Vec;
1949 : }
1950 :
1951 : // Add the new element to the end of the vector.
1952 1076: DeclOrVector.get<DeclVector*>()->push_back(ND);
1953 : }
1954 :
1955 1674: void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1028: branch 1 taken
646: branch 2 taken
1956 1674: if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
1028: branch 0 taken
0: branch 1 not taken
1957 1028: delete Vec;
1958 1028: DeclOrVector = ((NamedDecl *)0);
1959 : }
1960 1674: }
1961 :
1962 : VisibleDeclsRecord::ShadowMapEntry::iterator
1963 1117: VisibleDeclsRecord::ShadowMapEntry::begin() {
0: branch 1 not taken
1117: branch 2 taken
1964 1117: if (DeclOrVector.isNull())
1965 0: return 0;
1966 :
1065: branch 1 taken
52: branch 2 taken
1967 1117: if (DeclOrVector.dyn_cast<NamedDecl *>())
1968 1065: return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
1969 :
1970 52: return DeclOrVector.get<DeclVector *>()->begin();
1971 : }
1972 :
1973 : VisibleDeclsRecord::ShadowMapEntry::iterator
1974 1117: VisibleDeclsRecord::ShadowMapEntry::end() {
0: branch 1 not taken
1117: branch 2 taken
1975 1117: if (DeclOrVector.isNull())
1976 0: return 0;
1977 :
1065: branch 1 taken
52: branch 2 taken
1978 1117: if (DeclOrVector.dyn_cast<NamedDecl *>())
1979 1065: return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
1980 :
1981 52: return DeclOrVector.get<DeclVector *>()->end();
1982 : }
1983 :
1984 2750: NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
1985 : // Look through using declarations.
1986 2750: ND = ND->getUnderlyingDecl();
1987 :
1988 2750: unsigned IDNS = ND->getIdentifierNamespace();
1989 2750: std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3836: branch 3 taken
1959: branch 4 taken
1990 5795: for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
1991 : SM != SMEnd; ++SM) {
1992 3836: ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2719: branch 4 taken
1117: branch 5 taken
1993 3836: if (Pos == SM->end())
1994 2719: continue;
1995 :
1170: branch 2 taken
326: branch 3 taken
1996 2613: for (ShadowMapEntry::iterator I = Pos->second.begin(),
1997 1117: IEnd = Pos->second.end();
1998 : I != IEnd; ++I) {
1999 : // A tag declaration does not hide a non-tag declaration.
154: branch 1 taken
1016: branch 2 taken
34: branch 3 taken
120: branch 4 taken
1136: branch 5 taken
34: branch 6 taken
2000 1170: if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
2001 : (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2002 : Decl::IDNS_ObjCProtocol)))
2003 34: continue;
2004 :
2005 : // Protocols are in distinct namespaces from everything else.
1126: branch 1 taken
10: branch 2 taken
0: branch 3 not taken
1126: branch 4 taken
0: branch 6 not taken
10: branch 7 taken
0: branch 8 not taken
1136: branch 9 taken
2006 1136: if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2007 : || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2008 : (*I)->getIdentifierNamespace() != IDNS)
2009 0: continue;
2010 :
2011 : // Functions and function templates in the same scope overload
2012 : // rather than hide. FIXME: Look for hiding based on function
2013 : // signatures!
368: branch 1 taken
768: branch 2 taken
368: branch 4 taken
0: branch 5 not taken
345: branch 8 taken
23: branch 9 taken
345: branch 10 taken
791: branch 11 taken
2014 1136: if ((*I)->isFunctionOrFunctionTemplate() &&
2015 : ND->isFunctionOrFunctionTemplate() &&
2016 : SM == ShadowMaps.rbegin())
2017 345: continue;
2018 :
2019 : // We've found a declaration that hides this one.
2020 791: return *I;
2021 : }
2022 : }
2023 :
2024 1959: return 0;
2025 : }
2026 :
2027 : static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2028 : bool QualifiedNameLookup,
2029 : bool InBaseClass,
2030 : VisibleDeclConsumer &Consumer,
2031 330: VisibleDeclsRecord &Visited) {
0: branch 0 not taken
330: branch 1 taken
2032 330: if (!Ctx)
2033 0: return;
2034 :
2035 : // Make sure we don't visit the same context twice.
0: branch 2 not taken
330: branch 3 taken
2036 330: if (Visited.visitedContext(Ctx->getPrimaryContext()))
2037 0: return;
2038 :
2039 : // Enumerate all of the results in this context.
332: branch 2 taken
330: branch 3 taken
2040 662: for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2041 : CurCtx = CurCtx->getNextContext()) {
2171: branch 3 taken
332: branch 4 taken
2042 2835: for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2043 332: DEnd = CurCtx->decls_end();
2044 : D != DEnd; ++D) {
2119: branch 2 taken
52: branch 3 taken
2045 2171: if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1653: branch 1 taken
466: branch 2 taken
2046 2119: if (Result.isAcceptableDecl(ND)) {
2047 1653: Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
2048 1653: Visited.add(ND);
2049 : }
2050 :
2051 : // Visit transparent contexts inside this context.
1300: branch 2 taken
871: branch 3 taken
2052 2171: if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
19: branch 1 taken
1281: branch 2 taken
2053 1300: if (InnerCtx->isTransparentContext())
2054 : LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
2055 19: Consumer, Visited);
2056 : }
2057 : }
2058 : }
2059 :
2060 : // Traverse using directives for qualified name lookup.
141: branch 0 taken
189: branch 1 taken
2061 330: if (QualifiedNameLookup) {
2062 141: ShadowContextRAII Shadow(Visited);
2063 : DeclContext::udir_iterator I, E;
4: branch 3 taken
141: branch 4 taken
2064 145: for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2065 : LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
4: branch 1 taken
0: branch 2 not taken
2066 4: QualifiedNameLookup, InBaseClass, Consumer, Visited);
2067 141: }
2068 : }
2069 :
2070 : // Traverse the contexts of inherited C++ classes.
70: branch 1 taken
260: branch 2 taken
2071 330: if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
1: branch 1 taken
69: branch 2 taken
2072 70: if (!Record->hasDefinition())
2073 1: return;
2074 :
20: branch 2 taken
69: branch 3 taken
2075 158: for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2076 69: BEnd = Record->bases_end();
2077 : B != BEnd; ++B) {
2078 20: QualType BaseType = B->getType();
2079 :
2080 : // Don't look into dependent bases, because name lookup can't look
2081 : // there anyway.
0: branch 2 not taken
20: branch 3 taken
2082 20: if (BaseType->isDependentType())
2083 0: continue;
2084 :
2085 20: const RecordType *Record = BaseType->getAs<RecordType>();
0: branch 0 not taken
20: branch 1 taken
2086 20: if (!Record)
2087 0: continue;
2088 :
2089 : // FIXME: It would be nice to be able to determine whether referencing
2090 : // a particular member would be ambiguous. For example, given
2091 : //
2092 : // struct A { int member; };
2093 : // struct B { int member; };
2094 : // struct C : A, B { };
2095 : //
2096 : // void f(C *c) { c->### }
2097 : //
2098 : // accessing 'member' would result in an ambiguity. However, we
2099 : // could be smart enough to qualify the member with the base
2100 : // class, e.g.,
2101 : //
2102 : // c->B::member
2103 : //
2104 : // or
2105 : //
2106 : // c->A::member
2107 :
2108 : // Find results in this base class (and its bases).
2109 20: ShadowContextRAII Shadow(Visited);
2110 : LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
20: branch 1 taken
0: branch 2 not taken
2111 20: true, Consumer, Visited);
2112 : }
2113 : }
2114 :
2115 : // Traverse the contexts of Objective-C classes.
44: branch 1 taken
285: branch 2 taken
2116 329: if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2117 : // Traverse categories.
1: branch 3 taken
44: branch 4 taken
2118 45: for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2119 : Category; Category = Category->getNextClassCategory()) {
2120 1: ShadowContextRAII Shadow(Visited);
2121 : LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
1: branch 0 taken
0: branch 1 not taken
2122 1: Consumer, Visited);
2123 : }
2124 :
2125 : // Traverse protocols.
17: branch 2 taken
44: branch 3 taken
2126 105: for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2127 44: E = IFace->protocol_end(); I != E; ++I) {
2128 17: ShadowContextRAII Shadow(Visited);
2129 : LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
17: branch 0 taken
0: branch 1 not taken
2130 17: Visited);
2131 : }
2132 :
2133 : // Traverse the superclass.
16: branch 1 taken
28: branch 2 taken
2134 44: if (IFace->getSuperClass()) {
2135 16: ShadowContextRAII Shadow(Visited);
2136 : LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
16: branch 1 taken
0: branch 2 not taken
2137 16: true, Consumer, Visited);
2138 : }
17: branch 1 taken
268: branch 2 taken
2139 285: } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
0: branch 2 not taken
17: branch 3 taken
2140 34: for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2141 17: E = Protocol->protocol_end(); I != E; ++I) {
2142 0: ShadowContextRAII Shadow(Visited);
2143 : LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
0: branch 0 not taken
0: branch 1 not taken
2144 0: Visited);
2145 : }
1: branch 1 taken
267: branch 2 taken
2146 268: } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
0: branch 2 not taken
1: branch 3 taken
2147 2: for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2148 1: E = Category->protocol_end(); I != E; ++I) {
2149 0: ShadowContextRAII Shadow(Visited);
2150 : LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
0: branch 0 not taken
0: branch 1 not taken
2151 0: Visited);
2152 : }
2153 : }
2154 : }
2155 :
2156 : static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2157 : UnqualUsingDirectiveSet &UDirs,
2158 : VisibleDeclConsumer &Consumer,
2159 358: VisibleDeclsRecord &Visited) {
134: branch 0 taken
224: branch 1 taken
2160 358: if (!S)
2161 134: return;
2162 :
203: branch 1 taken
21: branch 2 taken
69: branch 4 taken
134: branch 5 taken
59: branch 8 taken
10: branch 9 taken
214: branch 10 taken
10: branch 11 taken
2163 224: if (!S->getEntity() || !S->getParent() ||
2164 : ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2165 : // Walk through the declarations in this Scope.
1316: branch 4 taken
214: branch 5 taken
2166 1530: for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2167 : D != DEnd; ++D) {
1316: branch 3 taken
0: branch 4 not taken
2168 1316: if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
1097: branch 1 taken
219: branch 2 taken
2169 1316: if (Result.isAcceptableDecl(ND)) {
2170 1097: Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
2171 1097: Visited.add(ND);
2172 : }
2173 : }
2174 : }
2175 :
2176 224: DeclContext *Entity = 0;
203: branch 1 taken
21: branch 2 taken
2177 224: if (S->getEntity()) {
2178 : // Look into this scope's declaration context, along with any of its
2179 : // parent lookup contexts (e.g., enclosing classes), up to the point
2180 : // where we hit the context stored in the next outer scope.
2181 203: Entity = (DeclContext *)S->getEntity();
2182 203: DeclContext *OuterCtx = findOuterContext(S);
2183 :
267: branch 1 taken
134: branch 2 taken
207: branch 4 taken
60: branch 5 taken
207: branch 6 taken
194: branch 7 taken
2184 401: for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2185 : Ctx = Ctx->getLookupParent()) {
9: branch 1 taken
198: branch 2 taken
2186 207: if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
7: branch 1 taken
2: branch 2 taken
2187 9: if (Method->isInstanceMethod()) {
2188 : // For instance methods, look for ivars in the method's interface.
2189 : LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2190 7: Result.getNameLoc(), Sema::LookupMemberName);
6: branch 1 taken
1: branch 2 taken
2191 7: if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2192 : LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
6: branch 0 taken
0: branch 1 not taken
2193 6: /*InBaseClass=*/false, Consumer, Visited);
2194 : }
2195 :
2196 : // We've already performed all of the name lookup that we need
2197 : // to for Objective-C methods; the next context will be the
2198 : // outer scope.
2199 9: break;
2200 : }
2201 :
50: branch 1 taken
148: branch 2 taken
2202 198: if (Ctx->isFunctionOrMethod())
2203 50: continue;
2204 :
2205 : LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
2206 148: /*InBaseClass=*/false, Consumer, Visited);
2207 : }
0: branch 1 not taken
21: branch 2 taken
2208 21: } else if (!S->getParent()) {
2209 : // Look into the translation unit scope. We walk through the translation
2210 : // unit's declaration context, because the Scope itself won't have all of
2211 : // the declarations if we loaded a precompiled header.
2212 : // FIXME: We would like the translation unit's Scope object to point to the
2213 : // translation unit, so we don't need this special "if" branch. However,
2214 : // doing so would force the normal C++ name-lookup code to look into the
2215 : // translation unit decl when the IdentifierInfo chains would suffice.
2216 : // Once we fix that problem (which is part of a more general "don't look
2217 : // in DeclContexts unless we have to" optimization), we can eliminate this.
0: branch 2 not taken
0: branch 3 not taken
2218 0: Entity = Result.getSema().Context.getTranslationUnitDecl();
2219 : LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
2220 0: /*InBaseClass=*/false, Consumer, Visited);
2221 : }
2222 :
203: branch 0 taken
21: branch 1 taken
2223 224: if (Entity) {
2224 : // Lookup visible declarations in any namespaces found by using
2225 : // directives.
2226 : UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2227 203: llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
12: branch 0 taken
203: branch 1 taken
2228 215: for (; UI != UEnd; ++UI)
2229 : LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2230 : Result, /*QualifiedNameLookup=*/false,
2231 12: /*InBaseClass=*/false, Consumer, Visited);
2232 : }
2233 :
2234 : // Lookup names in the parent scope.
2235 224: ShadowContextRAII Shadow(Visited);
2236 224: LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2237 : }
2238 :
2239 : void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2240 134: VisibleDeclConsumer &Consumer) {
2241 : // Determine the set of using directives available during
2242 : // unqualified name lookup.
2243 134: Scope *Initial = S;
2244 134: UnqualUsingDirectiveSet UDirs;
43: branch 1 taken
91: branch 2 taken
2245 134: if (getLangOptions().CPlusPlus) {
2246 : // Find the first namespace or translation-unit scope.
78: branch 0 taken
0: branch 1 not taken
35: branch 3 taken
43: branch 4 taken
35: branch 5 taken
43: branch 6 taken
2247 121: while (S && !isNamespaceOrTranslationUnitScope(S))
2248 35: S = S->getParent();
2249 :
2250 43: UDirs.visitScopeChain(Initial, S);
2251 : }
2252 134: UDirs.done();
2253 :
2254 : // Look for visible declarations.
2255 134: LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2256 134: VisibleDeclsRecord Visited;
2257 134: ShadowContextRAII Shadow(Visited);
2258 134: ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2259 134: }
2260 :
2261 : void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2262 87: VisibleDeclConsumer &Consumer) {
2263 87: LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2264 87: VisibleDeclsRecord Visited;
2265 87: ShadowContextRAII Shadow(Visited);
2266 : ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2267 87: /*InBaseClass=*/false, Consumer, Visited);
2268 87: }
2269 :
2270 : //----------------------------------------------------------------------------
2271 : // Typo correction
2272 : //----------------------------------------------------------------------------
2273 :
2274 : namespace {
0: branch 2 not taken
0: branch 3 not taken
0: branch 7 not taken
190: branch 8 taken
2275 190: class TypoCorrectionConsumer : public VisibleDeclConsumer {
2276 : /// \brief The name written that is a typo in the source.
2277 : llvm::StringRef Typo;
2278 :
2279 : /// \brief The results found that have the smallest edit distance
2280 : /// found (so far) with the typo name.
2281 : llvm::SmallVector<NamedDecl *, 4> BestResults;
2282 :
2283 : /// \brief The best edit distance found so far.
2284 : unsigned BestEditDistance;
2285 :
2286 : public:
2287 190: explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2288 190: : Typo(Typo->getName()) { }
2289 :
2290 : virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
2291 :
2292 : typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2293 179: iterator begin() const { return BestResults.begin(); }
2294 179: iterator end() const { return BestResults.end(); }
2295 188: bool empty() const { return BestResults.empty(); }
2296 :
2297 115: unsigned getBestEditDistance() const { return BestEditDistance; }
2298 : };
2299 :
2300 : }
2301 :
2302 : void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2303 2445: bool InBaseClass) {
2304 : // Don't consider hidden names for typo correction.
699: branch 0 taken
1746: branch 1 taken
2305 2445: if (Hiding)
2306 699: return;
2307 :
2308 : // Only consider entities with identifiers for names, ignoring
2309 : // special names (constructors, overloaded operators, selectors,
2310 : // etc.).
2311 1746: IdentifierInfo *Name = ND->getIdentifier();
240: branch 0 taken
1506: branch 1 taken
2312 1746: if (!Name)
2313 240: return;
2314 :
2315 : // Compute the edit distance between the typo and the name of this
2316 : // entity. If this edit distance is not worse than the best edit
2317 : // distance we've seen so far, add it to the list of results.
2318 1506: unsigned ED = Typo.edit_distance(Name->getName());
1327: branch 1 taken
179: branch 2 taken
2319 1506: if (!BestResults.empty()) {
188: branch 0 taken
1139: branch 1 taken
2320 1327: if (ED < BestEditDistance) {
2321 : // This result is better than any we've seen before; clear out
2322 : // the previous results.
2323 188: BestResults.clear();
2324 188: BestEditDistance = ED;
844: branch 0 taken
295: branch 1 taken
2325 1139: } else if (ED > BestEditDistance) {
2326 : // This result is worse than the best results we've seen so far;
2327 : // ignore it.
2328 844: return;
2329 : }
2330 : } else
2331 179: BestEditDistance = ED;
2332 :
2333 662: BestResults.push_back(ND);
2334 : }
2335 :
2336 : /// \brief Try to "correct" a typo in the source code by finding
2337 : /// visible declarations whose names are similar to the name that was
2338 : /// present in the source code.
2339 : ///
2340 : /// \param Res the \c LookupResult structure that contains the name
2341 : /// that was present in the source code along with the name-lookup
2342 : /// criteria used to search for the name. On success, this structure
2343 : /// will contain the results of name lookup.
2344 : ///
2345 : /// \param S the scope in which name lookup occurs.
2346 : ///
2347 : /// \param SS the nested-name-specifier that precedes the name we're
2348 : /// looking for, if present.
2349 : ///
2350 : /// \param MemberContext if non-NULL, the context in which to look for
2351 : /// a member access expression.
2352 : ///
2353 : /// \param EnteringContext whether we're entering the context described by
2354 : /// the nested-name-specifier SS.
2355 : ///
2356 : /// \param OPT when non-NULL, the search for visible declarations will
2357 : /// also walk the protocols in the qualified interfaces of \p OPT.
2358 : ///
2359 : /// \returns true if the typo was corrected, in which case the \p Res
2360 : /// structure will contain the results of name lookup for the
2361 : /// corrected name. Otherwise, returns false.
2362 : bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
2363 : DeclContext *MemberContext, bool EnteringContext,
2364 206: const ObjCObjectPointerType *OPT) {
0: branch 1 not taken
206: branch 2 taken
2365 206: if (Diags.hasFatalErrorOccurred())
2366 0: return false;
2367 :
2368 : // Provide a stop gap for files that are just seriously broken. Trying
2369 : // to correct all typos can turn into a HUGE performance penalty, causing
2370 : // some files to take minutes to get rejected by the parser.
2371 : // FIXME: Is this the right solution?
0: branch 0 not taken
206: branch 1 taken
2372 206: if (TyposCorrected == 20)
2373 0: return false;
2374 206: ++TyposCorrected;
2375 :
2376 : // We only attempt to correct typos for identifiers.
2377 206: IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
7: branch 0 taken
199: branch 1 taken
2378 206: if (!Typo)
2379 7: return false;
2380 :
2381 : // If the scope specifier itself was invalid, don't try to correct
2382 : // typos.
116: branch 0 taken
83: branch 1 taken
4: branch 3 taken
112: branch 4 taken
4: branch 5 taken
195: branch 6 taken
2383 199: if (SS && SS->isInvalid())
2384 4: return false;
2385 :
2386 : // Never try to correct typos during template deduction or
2387 : // instantiation.
5: branch 1 taken
190: branch 2 taken
2388 195: if (!ActiveTemplateInstantiations.empty())
2389 5: return false;
2390 :
2391 190: TypoCorrectionConsumer Consumer(Typo);
52: branch 0 taken
138: branch 1 taken
2392 190: if (MemberContext) {
2393 52: LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
2394 :
2395 : // Look in qualified interfaces.
13: branch 0 taken
39: branch 1 taken
2396 52: if (OPT) {
0: branch 0 not taken
13: branch 1 taken
2397 13: for (ObjCObjectPointerType::qual_iterator
2398 13: I = OPT->qual_begin(), E = OPT->qual_end();
2399 : I != E; ++I)
0: branch 1 not taken
0: branch 2 not taken
2400 0: LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2401 : }
84: branch 0 taken
54: branch 1 taken
24: branch 3 taken
60: branch 4 taken
24: branch 5 taken
114: branch 6 taken
2402 138: } else if (SS && SS->isSet()) {
2403 24: DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2: branch 0 taken
22: branch 1 taken
2404 24: if (!DC)
2405 2: return false;
2406 :
2407 22: LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2408 : } else {
2409 114: LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2410 : }
2411 :
9: branch 1 taken
179: branch 2 taken
2412 188: if (Consumer.empty())
2413 9: return false;
2414 :
2415 : // Only allow a single, closest name in the result set (it's okay to
2416 : // have overloads of that name, though).
2417 179: TypoCorrectionConsumer::iterator I = Consumer.begin();
2418 179: DeclarationName BestName = (*I)->getDeclName();
2419 :
2420 : // If we've found an Objective-C ivar or property, don't perform
2421 : // name lookup again; we'll just return the result directly.
2422 179: NamedDecl *FoundBest = 0;
169: branch 1 taken
10: branch 2 taken
9: branch 4 taken
160: branch 5 taken
19: branch 6 taken
160: branch 7 taken
2423 179: if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2424 19: FoundBest = *I;
2425 179: ++I;
74: branch 1 taken
115: branch 2 taken
2426 189: for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
64: branch 2 taken
10: branch 3 taken
2427 74: if (BestName != (*I)->getDeclName())
2428 64: return false;
2429 :
2430 : // FIXME: If there are both ivars and properties of the same name,
2431 : // don't return both because the callee can't handle two
2432 : // results. We really need to separate ivar lookup from property
2433 : // lookup to avoid this problem.
2434 10: FoundBest = 0;
2435 : }
2436 :
2437 : // BestName is the closest viable name to what the user
2438 : // typed. However, to make sure that we don't pick something that's
2439 : // way off, make sure that the user typed at least 3 characters for
2440 : // each correction.
2441 115: unsigned ED = Consumer.getBestEditDistance();
109: branch 0 taken
6: branch 1 taken
48: branch 5 taken
61: branch 6 taken
54: branch 7 taken
61: branch 8 taken
2442 115: if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2443 54: return false;
2444 :
2445 : // Perform name lookup again with the name we chose, and declare
2446 : // success if we found something that was not ambiguous.
2447 61: Res.clear();
2448 61: Res.setLookupName(BestName);
2449 :
2450 : // If we found an ivar or property, add that result; no further
2451 : // lookup is required.
18: branch 0 taken
43: branch 1 taken
2452 61: if (FoundBest)
2453 18: Res.addDecl(FoundBest);
2454 : // If we're looking into the context of a member, perform qualified
2455 : // name lookup on the best name.
14: branch 0 taken
29: branch 1 taken
2456 43: else if (MemberContext)
2457 14: LookupQualifiedName(Res, MemberContext);
2458 : // Perform lookup as if we had just parsed the best name.
2459 : else
2460 : LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2461 29: EnteringContext);
2462 :
0: branch 1 not taken
61: branch 2 taken
2463 61: if (Res.isAmbiguous()) {
2464 0: Res.suppressDiagnostics();
2465 0: return false;
2466 : }
2467 :
2468 61: return Res.getResultKind() != LookupResult::NotFound;
2469 0: }
Generated: 2010-02-10 01:31 by zcov