Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaCXXScopeSpec.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements C++ semantic analysis for scope specifiers.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/ExprCXX.h"
17
#include "clang/AST/NestedNameSpecifier.h"
18
#include "clang/Basic/PartialDiagnostic.h"
19
#include "clang/Sema/DeclSpec.h"
20
#include "clang/Sema/Lookup.h"
21
#include "clang/Sema/SemaInternal.h"
22
#include "clang/Sema/Template.h"
23
#include "llvm/ADT/STLExtras.h"
24
using namespace clang;
25
26
/// Find the current instantiation that associated with the given type.
27
static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
28
5.87M
                                                DeclContext *CurContext) {
29
5.87M
  if (T.isNull())
30
0
    return nullptr;
31
5.87M
32
5.87M
  const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
33
5.87M
  if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
34
25.6k
    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
35
25.6k
    if (!Record->isDependentContext() ||
36
25.6k
        Record->isCurrentInstantiation(CurContext))
37
14.3k
      return Record;
38
11.3k
39
11.3k
    return nullptr;
40
5.85M
  } else if (isa<InjectedClassNameType>(Ty))
41
1.66M
    return cast<InjectedClassNameType>(Ty)->getDecl();
42
4.19M
  else
43
4.19M
    return nullptr;
44
5.87M
}
45
46
/// Compute the DeclContext that is associated with the given type.
47
///
48
/// \param T the type for which we are attempting to find a DeclContext.
49
///
50
/// \returns the declaration context represented by the type T,
51
/// or NULL if the declaration context cannot be computed (e.g., because it is
52
/// dependent and not the current instantiation).
53
849k
DeclContext *Sema::computeDeclContext(QualType T) {
54
849k
  if (!T->isDependentType())
55
175k
    if (const TagType *Tag = T->getAs<TagType>())
56
175k
      return Tag->getDecl();
57
673k
58
673k
  return ::getCurrentInstantiationOf(T, CurContext);
59
673k
}
60
61
/// Compute the DeclContext that is associated with the given
62
/// scope specifier.
63
///
64
/// \param SS the C++ scope specifier as it appears in the source
65
///
66
/// \param EnteringContext when true, we will be entering the context of
67
/// this scope specifier, so we can retrieve the declaration context of a
68
/// class template or class template partial specialization even if it is
69
/// not the current instantiation.
70
///
71
/// \returns the declaration context represented by the scope specifier @p SS,
72
/// or NULL if the declaration context cannot be computed (e.g., because it is
73
/// dependent and not the current instantiation).
74
DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
75
10.2M
                                      bool EnteringContext) {
76
10.2M
  if (!SS.isSet() || 
SS.isInvalid()10.2M
)
77
371
    return nullptr;
78
10.2M
79
10.2M
  NestedNameSpecifier *NNS = SS.getScopeRep();
80
10.2M
  if (NNS->isDependent()) {
81
5.24M
    // If this nested-name-specifier refers to the current
82
5.24M
    // instantiation, return its DeclContext.
83
5.24M
    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
84
1.00M
      return Record;
85
4.23M
86
4.23M
    if (EnteringContext) {
87
258k
      const Type *NNSType = NNS->getAsType();
88
258k
      if (!NNSType) {
89
48
        return nullptr;
90
48
      }
91
258k
92
258k
      // Look through type alias templates, per C++0x [temp.dep.type]p1.
93
258k
      NNSType = Context.getCanonicalType(NNSType);
94
258k
      if (const TemplateSpecializationType *SpecType
95
254k
            = NNSType->getAs<TemplateSpecializationType>()) {
96
254k
        // We are entering the context of the nested name specifier, so try to
97
254k
        // match the nested name specifier to either a primary class template
98
254k
        // or a class template partial specialization.
99
254k
        if (ClassTemplateDecl *ClassTemplate
100
254k
              = dyn_cast_or_null<ClassTemplateDecl>(
101
254k
                            SpecType->getTemplateName().getAsTemplateDecl())) {
102
254k
          QualType ContextType
103
254k
            = Context.getCanonicalType(QualType(SpecType, 0));
104
254k
105
254k
          // If the type of the nested name specifier is the same as the
106
254k
          // injected class name of the named class template, we're entering
107
254k
          // into that class template definition.
108
254k
          QualType Injected
109
254k
            = ClassTemplate->getInjectedClassNameSpecialization();
110
254k
          if (Context.hasSameType(Injected, ContextType))
111
183k
            return ClassTemplate->getTemplatedDecl();
112
70.5k
113
70.5k
          // If the type of the nested name specifier is the same as the
114
70.5k
          // type of one of the class template's class template partial
115
70.5k
          // specializations, we're entering into the definition of that
116
70.5k
          // class template partial specialization.
117
70.5k
          if (ClassTemplatePartialSpecializationDecl *PartialSpec
118
69.5k
                = ClassTemplate->findPartialSpecialization(ContextType)) {
119
69.5k
            // A declaration of the partial specialization must be visible.
120
69.5k
            // We can always recover here, because this only happens when we're
121
69.5k
            // entering the context, and that can't happen in a SFINAE context.
122
69.5k
            assert(!isSFINAEContext() &&
123
69.5k
                   "partial specialization scope specifier in SFINAE context?");
124
69.5k
            if (!hasVisibleDeclaration(PartialSpec))
125
30
              diagnoseMissingImport(SS.getLastQualifierNameLoc(), PartialSpec,
126
30
                                    MissingImportKind::PartialSpecialization,
127
30
                                    /*Recover*/true);
128
69.5k
            return PartialSpec;
129
69.5k
          }
130
3.83k
        }
131
3.83k
      } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
132
3.49k
        // The nested name specifier refers to a member of a class template.
133
3.49k
        return RecordT->getDecl();
134
3.49k
      }
135
3.98M
    }
136
3.98M
137
3.98M
    return nullptr;
138
3.98M
  }
139
5.01M
140
5.01M
  switch (NNS->getKind()) {
141
0
  case NestedNameSpecifier::Identifier:
142
0
    llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
143
0
144
1.94M
  case NestedNameSpecifier::Namespace:
145
1.94M
    return NNS->getAsNamespace();
146
0
147
720
  case NestedNameSpecifier::NamespaceAlias:
148
720
    return NNS->getAsNamespaceAlias()->getNamespace();
149
0
150
2.34M
  case NestedNameSpecifier::TypeSpec:
151
2.34M
  case NestedNameSpecifier::TypeSpecWithTemplate: {
152
2.34M
    const TagType *Tag = NNS->getAsType()->getAs<TagType>();
153
2.34M
    assert(Tag && "Non-tag type in nested-name-specifier");
154
2.34M
    return Tag->getDecl();
155
2.34M
  }
156
2.34M
157
2.34M
  case NestedNameSpecifier::Global:
158
732k
    return Context.getTranslationUnitDecl();
159
2.34M
160
2.34M
  case NestedNameSpecifier::Super:
161
70
    return NNS->getAsRecordDecl();
162
0
  }
163
0
164
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
165
0
}
166
167
2.39M
bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
168
2.39M
  if (!SS.isSet() || 
SS.isInvalid()2.05M
)
169
336k
    return false;
170
2.05M
171
2.05M
  return SS.getScopeRep()->isDependent();
172
2.05M
}
173
174
/// If the given nested name specifier refers to the current
175
/// instantiation, return the declaration that corresponds to that
176
/// current instantiation (C++0x [temp.dep.type]p1).
177
///
178
/// \param NNS a dependent nested name specifier.
179
5.24M
CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
180
5.24M
  assert(getLangOpts().CPlusPlus && "Only callable in C++");
181
5.24M
  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
182
5.24M
183
5.24M
  if (!NNS->getAsType())
184
39.5k
    return nullptr;
185
5.20M
186
5.20M
  QualType T = QualType(NNS->getAsType(), 0);
187
5.20M
  return ::getCurrentInstantiationOf(T, CurContext);
188
5.20M
}
189
190
/// Require that the context specified by SS be complete.
191
///
192
/// If SS refers to a type, this routine checks whether the type is
193
/// complete enough (or can be made complete enough) for name lookup
194
/// into the DeclContext. A type that is not yet completed can be
195
/// considered "complete enough" if it is a class/struct/union/enum
196
/// that is currently being defined. Or, if we have a type that names
197
/// a class template specialization that is not a complete type, we
198
/// will attempt to instantiate that class template.
199
bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
200
4.50M
                                      DeclContext *DC) {
201
4.50M
  assert(DC && "given null context");
202
4.50M
203
4.50M
  TagDecl *tag = dyn_cast<TagDecl>(DC);
204
4.50M
205
4.50M
  // If this is a dependent type, then we consider it complete.
206
4.50M
  // FIXME: This is wrong; we should require a (visible) definition to
207
4.50M
  // exist in this case too.
208
4.50M
  if (!tag || 
tag->isDependentContext()2.18M
)
209
2.38M
    return false;
210
2.12M
211
2.12M
  // Grab the tag definition, if there is one.
212
2.12M
  QualType type = Context.getTypeDeclType(tag);
213
2.12M
  tag = type->getAsTagDecl();
214
2.12M
215
2.12M
  // If we're currently defining this type, then lookup into the
216
2.12M
  // type is okay: don't complain that it isn't complete yet.
217
2.12M
  if (tag->isBeingDefined())
218
2.25k
    return false;
219
2.12M
220
2.12M
  SourceLocation loc = SS.getLastQualifierNameLoc();
221
2.12M
  if (loc.isInvalid()) 
loc = SS.getRange().getBegin()474
;
222
2.12M
223
2.12M
  // The type must be complete.
224
2.12M
  if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
225
2.12M
                          SS.getRange())) {
226
676
    SS.SetInvalid(SS.getRange());
227
676
    return true;
228
676
  }
229
2.12M
230
2.12M
  // Fixed enum types are complete, but they aren't valid as scopes
231
2.12M
  // until we see a definition, so awkwardly pull out this special
232
2.12M
  // case.
233
2.12M
  auto *EnumD = dyn_cast<EnumDecl>(tag);
234
2.12M
  if (!EnumD)
235
2.10M
    return false;
236
21.7k
  if (EnumD->isCompleteDefinition()) {
237
21.7k
    // If we know about the definition but it is not visible, complain.
238
21.7k
    NamedDecl *SuggestedDef = nullptr;
239
21.7k
    if (!hasVisibleDefinition(EnumD, &SuggestedDef,
240
21.7k
                              /*OnlyNeedComplete*/false)) {
241
25
      // If the user is going to see an error here, recover by making the
242
25
      // definition visible.
243
25
      bool TreatAsComplete = !isSFINAEContext();
244
25
      diagnoseMissingImport(loc, SuggestedDef, MissingImportKind::Definition,
245
25
                            /*Recover*/TreatAsComplete);
246
25
      return !TreatAsComplete;
247
25
    }
248
21.7k
    return false;
249
21.7k
  }
250
20
251
20
  // Try to instantiate the definition, if this is a specialization of an
252
20
  // enumeration temploid.
253
20
  if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {
254
15
    MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();
255
15
    if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
256
14
      if (InstantiateEnum(loc, EnumD, Pattern,
257
14
                          getTemplateInstantiationArgs(EnumD),
258
14
                          TSK_ImplicitInstantiation)) {
259
3
        SS.SetInvalid(SS.getRange());
260
3
        return true;
261
3
      }
262
11
      return false;
263
11
    }
264
15
  }
265
6
266
6
  Diag(loc, diag::err_incomplete_nested_name_spec)
267
6
    << type << SS.getRange();
268
6
  SS.SetInvalid(SS.getRange());
269
6
  return true;
270
6
}
271
272
bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,
273
210k
                                        CXXScopeSpec &SS) {
274
210k
  SS.MakeGlobal(Context, CCLoc);
275
210k
  return false;
276
210k
}
277
278
bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
279
                                    SourceLocation ColonColonLoc,
280
42
                                    CXXScopeSpec &SS) {
281
42
  CXXRecordDecl *RD = nullptr;
282
45
  for (Scope *S = getCurScope(); S; 
S = S->getParent()3
) {
283
45
    if (S->isFunctionScope()) {
284
27
      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(S->getEntity()))
285
27
        RD = MD->getParent();
286
27
      break;
287
27
    }
288
18
    if (S->isClassScope()) {
289
15
      RD = cast<CXXRecordDecl>(S->getEntity());
290
15
      break;
291
15
    }
292
18
  }
293
42
294
42
  if (!RD) {
295
0
    Diag(SuperLoc, diag::err_invalid_super_scope);
296
0
    return true;
297
42
  } else if (RD->isLambda()) {
298
1
    Diag(SuperLoc, diag::err_super_in_lambda_unsupported);
299
1
    return true;
300
41
  } else if (RD->getNumBases() == 0) {
301
1
    Diag(SuperLoc, diag::err_no_base_classes) << RD->getName();
302
1
    return true;
303
1
  }
304
40
305
40
  SS.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);
306
40
  return false;
307
40
}
308
309
/// Determines whether the given declaration is an valid acceptable
310
/// result for name lookup of a nested-name-specifier.
311
/// \param SD Declaration checked for nested-name-specifier.
312
/// \param IsExtension If not null and the declaration is accepted as an
313
/// extension, the pointed variable is assigned true.
314
bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,
315
1.42M
                                           bool *IsExtension) {
316
1.42M
  if (!SD)
317
924
    return false;
318
1.41M
319
1.41M
  SD = SD->getUnderlyingDecl();
320
1.41M
321
1.41M
  // Namespace and namespace aliases are fine.
322
1.41M
  if (isa<NamespaceDecl>(SD))
323
945k
    return true;
324
473k
325
473k
  if (!isa<TypeDecl>(SD))
326
9
    return false;
327
473k
328
473k
  // Determine whether we have a class (or, in C++11, an enum) or
329
473k
  // a typedef thereof. If so, build the nested-name-specifier.
330
473k
  QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
331
473k
  if (T->isDependentType())
332
350k
    return true;
333
122k
  if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
334
13.9k
    if (TD->getUnderlyingType()->isRecordType())
335
13.9k
      return true;
336
30
    if (TD->getUnderlyingType()->isEnumeralType()) {
337
19
      if (Context.getLangOpts().CPlusPlus11)
338
19
        return true;
339
0
      if (IsExtension)
340
0
        *IsExtension = true;
341
0
    }
342
108k
  } else if (isa<RecordDecl>(SD)) {
343
103k
    return true;
344
103k
  } else 
if (5.17k
isa<EnumDecl>(SD)5.17k
) {
345
5.17k
    if (Context.getLangOpts().CPlusPlus11)
346
5.15k
      return true;
347
22
    if (IsExtension)
348
13
      *IsExtension = true;
349
22
  }
350
122k
351
122k
  
return false33
;
352
122k
}
353
354
/// If the given nested-name-specifier begins with a bare identifier
355
/// (e.g., Base::), perform name lookup for that identifier as a
356
/// nested-name-specifier within the given scope, and return the result of that
357
/// name lookup.
358
588
NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
359
588
  if (!S || !NNS)
360
0
    return nullptr;
361
588
362
743
  
while (588
NNS->getPrefix())
363
155
    NNS = NNS->getPrefix();
364
588
365
588
  if (NNS->getKind() != NestedNameSpecifier::Identifier)
366
519
    return nullptr;
367
69
368
69
  LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
369
69
                     LookupNestedNameSpecifierName);
370
69
  LookupName(Found, S);
371
69
  assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
372
69
373
69
  if (!Found.isSingleResult())
374
15
    return nullptr;
375
54
376
54
  NamedDecl *Result = Found.getFoundDecl();
377
54
  if (isAcceptableNestedNameSpecifier(Result))
378
53
    return Result;
379
1
380
1
  return nullptr;
381
1
}
382
383
bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
384
0
                                        NestedNameSpecInfo &IdInfo) {
385
0
  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
386
0
  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
387
0
                     LookupNestedNameSpecifierName);
388
0
389
0
  // Determine where to perform name lookup
390
0
  DeclContext *LookupCtx = nullptr;
391
0
  bool isDependent = false;
392
0
  if (!ObjectType.isNull()) {
393
0
    // This nested-name-specifier occurs in a member access expression, e.g.,
394
0
    // x->B::f, and we are looking into the type of the object.
395
0
    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
396
0
    LookupCtx = computeDeclContext(ObjectType);
397
0
    isDependent = ObjectType->isDependentType();
398
0
  } else if (SS.isSet()) {
399
0
    // This nested-name-specifier occurs after another nested-name-specifier,
400
0
    // so long into the context associated with the prior nested-name-specifier.
401
0
    LookupCtx = computeDeclContext(SS, false);
402
0
    isDependent = isDependentScopeSpecifier(SS);
403
0
    Found.setContextRange(SS.getRange());
404
0
  }
405
0
406
0
  if (LookupCtx) {
407
0
    // Perform "qualified" name lookup into the declaration context we
408
0
    // computed, which is either the type of the base of a member access
409
0
    // expression or the declaration context associated with a prior
410
0
    // nested-name-specifier.
411
0
412
0
    // The declaration context must be complete.
413
0
    if (!LookupCtx->isDependentContext() &&
414
0
        RequireCompleteDeclContext(SS, LookupCtx))
415
0
      return false;
416
0
417
0
    LookupQualifiedName(Found, LookupCtx);
418
0
  } else if (isDependent) {
419
0
    return false;
420
0
  } else {
421
0
    LookupName(Found, S);
422
0
  }
423
0
  Found.suppressDiagnostics();
424
0
425
0
  return Found.getAsSingle<NamespaceDecl>();
426
0
}
427
428
namespace {
429
430
// Callback to only accept typo corrections that can be a valid C++ member
431
// intializer: either a non-static field member or a base class.
432
class NestedNameSpecifierValidatorCCC final
433
    : public CorrectionCandidateCallback {
434
public:
435
  explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
436
169
      : SRef(SRef) {}
437
438
74
  bool ValidateCandidate(const TypoCorrection &candidate) override {
439
74
    return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
440
74
  }
441
442
144
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
443
144
    return std::make_unique<NestedNameSpecifierValidatorCCC>(*this);
444
144
  }
445
446
 private:
447
  Sema &SRef;
448
};
449
450
}
451
452
/// Build a new nested-name-specifier for "identifier::", as described
453
/// by ActOnCXXNestedNameSpecifier.
454
///
455
/// \param S Scope in which the nested-name-specifier occurs.
456
/// \param IdInfo Parser information about an identifier in the
457
///        nested-name-spec.
458
/// \param EnteringContext If true, enter the context specified by the
459
///        nested-name-specifier.
460
/// \param SS Optional nested name specifier preceding the identifier.
461
/// \param ScopeLookupResult Provides the result of name lookup within the
462
///        scope of the nested-name-specifier that was computed at template
463
///        definition time.
464
/// \param ErrorRecoveryLookup Specifies if the method is called to improve
465
///        error recovery and what kind of recovery is performed.
466
/// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
467
///        are allowed.  The bool value pointed by this parameter is set to
468
///       'true' if the identifier is treated as if it was followed by ':',
469
///        not '::'.
470
/// \param OnlyNamespace If true, only considers namespaces in lookup.
471
///
472
/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
473
/// that it contains an extra parameter \p ScopeLookupResult, which provides
474
/// the result of name lookup within the scope of the nested-name-specifier
475
/// that was computed at template definition time.
476
///
477
/// If ErrorRecoveryLookup is true, then this call is used to improve error
478
/// recovery.  This means that it should not emit diagnostics, it should
479
/// just return true on failure.  It also means it should only return a valid
480
/// scope if it *knows* that the result is correct.  It should not return in a
481
/// dependent context, for example. Nor will it extend \p SS with the scope
482
/// specifier.
483
bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
484
                                       bool EnteringContext, CXXScopeSpec &SS,
485
                                       NamedDecl *ScopeLookupResult,
486
                                       bool ErrorRecoveryLookup,
487
                                       bool *IsCorrectedToColon,
488
1.43M
                                       bool OnlyNamespace) {
489
1.43M
  if (IdInfo.Identifier->isEditorPlaceholder())
490
4
    return true;
491
1.43M
  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
492
1.43M
                     OnlyNamespace ? 
LookupNamespaceName207
493
1.43M
                                   : 
LookupNestedNameSpecifierName1.43M
);
494
1.43M
  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
495
1.43M
496
1.43M
  // Determine where to perform name lookup
497
1.43M
  DeclContext *LookupCtx = nullptr;
498
1.43M
  bool isDependent = false;
499
1.43M
  if (IsCorrectedToColon)
500
99.1k
    *IsCorrectedToColon = false;
501
1.43M
  if (!ObjectType.isNull()) {
502
633
    // This nested-name-specifier occurs in a member access expression, e.g.,
503
633
    // x->B::f, and we are looking into the type of the object.
504
633
    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
505
633
    LookupCtx = computeDeclContext(ObjectType);
506
633
    isDependent = ObjectType->isDependentType();
507
1.43M
  } else if (SS.isSet()) {
508
369k
    // This nested-name-specifier occurs after another nested-name-specifier,
509
369k
    // so look into the context associated with the prior nested-name-specifier.
510
369k
    LookupCtx = computeDeclContext(SS, EnteringContext);
511
369k
    isDependent = isDependentScopeSpecifier(SS);
512
369k
    Found.setContextRange(SS.getRange());
513
369k
  }
514
1.43M
515
1.43M
  bool ObjectTypeSearchedInScope = false;
516
1.43M
  if (LookupCtx) {
517
357k
    // Perform "qualified" name lookup into the declaration context we
518
357k
    // computed, which is either the type of the base of a member access
519
357k
    // expression or the declaration context associated with a prior
520
357k
    // nested-name-specifier.
521
357k
522
357k
    // The declaration context must be complete.
523
357k
    if (!LookupCtx->isDependentContext() &&
524
357k
        
RequireCompleteDeclContext(SS, LookupCtx)356k
)
525
0
      return true;
526
357k
527
357k
    LookupQualifiedName(Found, LookupCtx);
528
357k
529
357k
    if (!ObjectType.isNull() && 
Found.empty()527
) {
530
251
      // C++ [basic.lookup.classref]p4:
531
251
      //   If the id-expression in a class member access is a qualified-id of
532
251
      //   the form
533
251
      //
534
251
      //        class-name-or-namespace-name::...
535
251
      //
536
251
      //   the class-name-or-namespace-name following the . or -> operator is
537
251
      //   looked up both in the context of the entire postfix-expression and in
538
251
      //   the scope of the class of the object expression. If the name is found
539
251
      //   only in the scope of the class of the object expression, the name
540
251
      //   shall refer to a class-name. If the name is found only in the
541
251
      //   context of the entire postfix-expression, the name shall refer to a
542
251
      //   class-name or namespace-name. [...]
543
251
      //
544
251
      // Qualified name lookup into a class will not find a namespace-name,
545
251
      // so we do not need to diagnose that case specifically. However,
546
251
      // this qualified name lookup may find nothing. In that case, perform
547
251
      // unqualified name lookup in the given scope (if available) or
548
251
      // reconstruct the result from when name lookup was performed at template
549
251
      // definition time.
550
251
      if (S)
551
225
        LookupName(Found, S);
552
26
      else if (ScopeLookupResult)
553
22
        Found.addDecl(ScopeLookupResult);
554
251
555
251
      ObjectTypeSearchedInScope = true;
556
251
    }
557
1.07M
  } else if (!isDependent) {
558
1.06M
    // Perform unqualified name lookup in the current scope.
559
1.06M
    LookupName(Found, S);
560
1.06M
  }
561
1.43M
562
1.43M
  if (Found.isAmbiguous())
563
5
    return true;
564
1.43M
565
1.43M
  // If we performed lookup into a dependent context and did not find anything,
566
1.43M
  // that's fine: just build a dependent nested-name-specifier.
567
1.43M
  if (Found.empty() && 
isDependent13.5k
&&
568
1.43M
      
!(12.5k
LookupCtx12.5k
&&
LookupCtx->isRecord()6
&&
569
12.5k
        
(6
!cast<CXXRecordDecl>(LookupCtx)->hasDefinition()6
||
570
12.5k
         
!cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()3
))) {
571
12.5k
    // Don't speculate if we're just trying to improve error recovery.
572
12.5k
    if (ErrorRecoveryLookup)
573
0
      return true;
574
12.5k
575
12.5k
    // We were not able to compute the declaration context for a dependent
576
12.5k
    // base object type or prior nested-name-specifier, so this
577
12.5k
    // nested-name-specifier refers to an unknown specialization. Just build
578
12.5k
    // a dependent nested-name-specifier.
579
12.5k
    SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc, IdInfo.CCLoc);
580
12.5k
    return false;
581
12.5k
  }
582
1.41M
583
1.41M
  if (Found.empty() && 
!ErrorRecoveryLookup996
) {
584
202
    // If identifier is not found as class-name-or-namespace-name, but is found
585
202
    // as other entity, don't look for typos.
586
202
    LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
587
202
    if (LookupCtx)
588
43
      LookupQualifiedName(R, LookupCtx);
589
159
    else if (S && 
!isDependent158
)
590
158
      LookupName(R, S);
591
202
    if (!R.empty()) {
592
24
      // Don't diagnose problems with this speculative lookup.
593
24
      R.suppressDiagnostics();
594
24
      // The identifier is found in ordinary lookup. If correction to colon is
595
24
      // allowed, suggest replacement to ':'.
596
24
      if (IsCorrectedToColon) {
597
9
        *IsCorrectedToColon = true;
598
9
        Diag(IdInfo.CCLoc, diag::err_nested_name_spec_is_not_class)
599
9
            << IdInfo.Identifier << getLangOpts().CPlusPlus
600
9
            << FixItHint::CreateReplacement(IdInfo.CCLoc, ":");
601
9
        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
602
9
          Diag(ND->getLocation(), diag::note_declared_at);
603
9
        return true;
604
9
      }
605
15
      // Replacement '::' -> ':' is not allowed, just issue respective error.
606
15
      Diag(R.getNameLoc(), OnlyNamespace
607
15
                               ? 
unsigned(diag::err_expected_namespace_name)9
608
15
                               : 
unsigned(diag::err_expected_class_or_namespace)6
)
609
15
          << IdInfo.Identifier << getLangOpts().CPlusPlus;
610
15
      if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
611
15
        Diag(ND->getLocation(), diag::note_entity_declared_at)
612
15
            << IdInfo.Identifier;
613
15
      return true;
614
15
    }
615
202
  }
616
1.41M
617
1.41M
  if (Found.empty() && 
!ErrorRecoveryLookup972
&&
!getLangOpts().MSVCCompat178
) {
618
169
    // We haven't found anything, and we're not recovering from a
619
169
    // different kind of error, so look for typos.
620
169
    DeclarationName Name = Found.getLookupName();
621
169
    Found.clear();
622
169
    NestedNameSpecifierValidatorCCC CCC(*this);
623
169
    if (TypoCorrection Corrected = CorrectTypo(
624
64
            Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, CCC,
625
64
            CTK_ErrorRecovery, LookupCtx, EnteringContext)) {
626
64
      if (LookupCtx) {
627
9
        bool DroppedSpecifier =
628
9
            Corrected.WillReplaceSpecifier() &&
629
9
            
Name.getAsString() == Corrected.getAsString(getLangOpts())5
;
630
9
        if (DroppedSpecifier)
631
1
          SS.clear();
632
9
        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
633
9
                                  << Name << LookupCtx << DroppedSpecifier
634
9
                                  << SS.getRange());
635
9
      } else
636
55
        diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
637
55
                                  << Name);
638
64
639
64
      if (Corrected.getCorrectionSpecifier())
640
12
        SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
641
12
                       SourceRange(Found.getNameLoc()));
642
64
643
64
      if (NamedDecl *ND = Corrected.getFoundDecl())
644
64
        Found.addDecl(ND);
645
64
      Found.setLookupName(Corrected.getCorrection());
646
105
    } else {
647
105
      Found.setLookupName(IdInfo.Identifier);
648
105
    }
649
169
  }
650
1.41M
651
1.41M
  NamedDecl *SD =
652
1.41M
      Found.isSingleResult() ? 
Found.getRepresentativeDecl()1.41M
:
nullptr908
;
653
1.41M
  bool IsExtension = false;
654
1.41M
  bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);
655
1.41M
  if (!AcceptSpec && 
IsExtension931
) {
656
13
    AcceptSpec = true;
657
13
    Diag(IdInfo.IdentifierLoc, diag::ext_nested_name_spec_is_enum);
658
13
  }
659
1.41M
  if (AcceptSpec) {
660
1.41M
    if (!ObjectType.isNull() && 
!ObjectTypeSearchedInScope546
&&
661
1.41M
        
!getLangOpts().CPlusPlus11308
) {
662
44
      // C++03 [basic.lookup.classref]p4:
663
44
      //   [...] If the name is found in both contexts, the
664
44
      //   class-name-or-namespace-name shall refer to the same entity.
665
44
      //
666
44
      // We already found the name in the scope of the object. Now, look
667
44
      // into the current scope (the scope of the postfix-expression) to
668
44
      // see if we can find the same name there. As above, if there is no
669
44
      // scope, reconstruct the result from the template instantiation itself.
670
44
      //
671
44
      // Note that C++11 does *not* perform this redundant lookup.
672
44
      NamedDecl *OuterDecl;
673
44
      if (S) {
674
35
        LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
675
35
                                LookupNestedNameSpecifierName);
676
35
        LookupName(FoundOuter, S);
677
35
        OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
678
35
      } else
679
9
        OuterDecl = ScopeLookupResult;
680
44
681
44
      if (isAcceptableNestedNameSpecifier(OuterDecl) &&
682
44
          
OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl()33
&&
683
44
          
(24
!isa<TypeDecl>(OuterDecl)24
||
!isa<TypeDecl>(SD)24
||
684
24
           !Context.hasSameType(
685
24
                            Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
686
24
                               Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
687
2
        if (ErrorRecoveryLookup)
688
0
          return true;
689
2
690
2
         Diag(IdInfo.IdentifierLoc,
691
2
              diag::err_nested_name_member_ref_lookup_ambiguous)
692
2
           << IdInfo.Identifier;
693
2
         Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
694
2
           << ObjectType;
695
2
         Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
696
2
697
2
         // Fall through so that we'll pick the name we found in the object
698
2
         // type, since that's probably what the user wanted anyway.
699
2
       }
700
44
    }
701
1.41M
702
1.41M
    if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))
703
225k
      MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
704
1.41M
705
1.41M
    // If we're just performing this lookup for error-recovery purposes,
706
1.41M
    // don't extend the nested-name-specifier. Just return now.
707
1.41M
    if (ErrorRecoveryLookup)
708
159
      return false;
709
1.41M
710
1.41M
    // The use of a nested name specifier may trigger deprecation warnings.
711
1.41M
    DiagnoseUseOfDecl(SD, IdInfo.CCLoc);
712
1.41M
713
1.41M
    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
714
945k
      SS.Extend(Context, Namespace, IdInfo.IdentifierLoc, IdInfo.CCLoc);
715
945k
      return false;
716
945k
    }
717
473k
718
473k
    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
719
211
      SS.Extend(Context, Alias, IdInfo.IdentifierLoc, IdInfo.CCLoc);
720
211
      return false;
721
211
    }
722
472k
723
472k
    QualType T =
724
472k
        Context.getTypeDeclType(cast<TypeDecl>(SD->getUnderlyingDecl()));
725
472k
    TypeLocBuilder TLB;
726
472k
    if (isa<InjectedClassNameType>(T)) {
727
377
      InjectedClassNameTypeLoc InjectedTL
728
377
        = TLB.push<InjectedClassNameTypeLoc>(T);
729
377
      InjectedTL.setNameLoc(IdInfo.IdentifierLoc);
730
472k
    } else if (isa<RecordType>(T)) {
731
106k
      RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
732
106k
      RecordTL.setNameLoc(IdInfo.IdentifierLoc);
733
365k
    } else if (isa<TypedefType>(T)) {
734
225k
      TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
735
225k
      TypedefTL.setNameLoc(IdInfo.IdentifierLoc);
736
225k
    } else 
if (140k
isa<EnumType>(T)140k
) {
737
5.17k
      EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
738
5.17k
      EnumTL.setNameLoc(IdInfo.IdentifierLoc);
739
135k
    } else if (isa<TemplateTypeParmType>(T)) {
740
135k
      TemplateTypeParmTypeLoc TemplateTypeTL
741
135k
        = TLB.push<TemplateTypeParmTypeLoc>(T);
742
135k
      TemplateTypeTL.setNameLoc(IdInfo.IdentifierLoc);
743
135k
    } else 
if (1
isa<UnresolvedUsingType>(T)1
) {
744
1
      UnresolvedUsingTypeLoc UnresolvedTL
745
1
        = TLB.push<UnresolvedUsingTypeLoc>(T);
746
1
      UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc);
747
1
    } else 
if (0
isa<SubstTemplateTypeParmType>(T)0
) {
748
0
      SubstTemplateTypeParmTypeLoc TL
749
0
        = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
750
0
      TL.setNameLoc(IdInfo.IdentifierLoc);
751
0
    } else if (isa<SubstTemplateTypeParmPackType>(T)) {
752
0
      SubstTemplateTypeParmPackTypeLoc TL
753
0
        = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
754
0
      TL.setNameLoc(IdInfo.IdentifierLoc);
755
0
    } else {
756
0
      llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
757
0
    }
758
472k
759
472k
    if (T->isEnumeralType())
760
5.19k
      Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
761
472k
762
472k
    SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
763
472k
              IdInfo.CCLoc);
764
472k
    return false;
765
472k
  }
766
918
767
918
  // Otherwise, we have an error case.  If we don't want diagnostics, just
768
918
  // return an error now.
769
918
  if (ErrorRecoveryLookup)
770
794
    return true;
771
124
772
124
  // If we didn't find anything during our lookup, try again with
773
124
  // ordinary name lookup, which can help us produce better error
774
124
  // messages.
775
124
  if (Found.empty()) {
776
114
    Found.clear(LookupOrdinaryName);
777
114
    LookupName(Found, S);
778
114
  }
779
124
780
124
  // In Microsoft mode, if we are within a templated function and we can't
781
124
  // resolve Identifier, then extend the SS with Identifier. This will have
782
124
  // the effect of resolving Identifier during template instantiation.
783
124
  // The goal is to be able to resolve a function call whose
784
124
  // nested-name-specifier is located inside a dependent base class.
785
124
  // Example:
786
124
  //
787
124
  // class C {
788
124
  // public:
789
124
  //    static void foo2() {  }
790
124
  // };
791
124
  // template <class T> class A { public: typedef C D; };
792
124
  //
793
124
  // template <class T> class B : public A<T> {
794
124
  // public:
795
124
  //   void foo() { D::foo2(); }
796
124
  // };
797
124
  if (getLangOpts().MSVCCompat) {
798
10
    DeclContext *DC = LookupCtx ? 
LookupCtx2
:
CurContext8
;
799
10
    if (DC->isDependentContext() && 
DC->isFunctionOrMethod()6
) {
800
6
      CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());
801
6
      if (ContainingClass && 
ContainingClass->hasAnyDependentBases()5
) {
802
4
        Diag(IdInfo.IdentifierLoc,
803
4
             diag::ext_undeclared_unqual_id_with_dependent_base)
804
4
            << IdInfo.Identifier << ContainingClass;
805
4
        SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc,
806
4
                  IdInfo.CCLoc);
807
4
        return false;
808
4
      }
809
120
    }
810
10
  }
811
120
812
120
  if (!Found.empty()) {
813
10
    if (TypeDecl *TD = Found.getAsSingle<TypeDecl>())
814
8
      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
815
8
          << Context.getTypeDeclType(TD) << getLangOpts().CPlusPlus;
816
2
    else {
817
2
      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
818
2
          << IdInfo.Identifier << getLangOpts().CPlusPlus;
819
2
      if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
820
2
        Diag(ND->getLocation(), diag::note_entity_declared_at)
821
2
            << IdInfo.Identifier;
822
2
    }
823
110
  } else if (SS.isSet())
824
14
    Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier
825
14
        << LookupCtx << SS.getRange();
826
96
  else
827
96
    Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)
828
96
        << IdInfo.Identifier;
829
120
830
120
  return true;
831
120
}
832
833
bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
834
                                       bool EnteringContext, CXXScopeSpec &SS,
835
                                       bool ErrorRecoveryLookup,
836
                                       bool *IsCorrectedToColon,
837
1.42M
                                       bool OnlyNamespace) {
838
1.42M
  if (SS.isInvalid())
839
17
    return true;
840
1.42M
841
1.42M
  return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
842
1.42M
                                     /*ScopeLookupResult=*/nullptr, false,
843
1.42M
                                     IsCorrectedToColon, OnlyNamespace);
844
1.42M
}
845
846
bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
847
                                               const DeclSpec &DS,
848
1.24k
                                               SourceLocation ColonColonLoc) {
849
1.24k
  if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
850
3
    return true;
851
1.24k
852
1.24k
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
853
1.24k
854
1.24k
  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
855
1.24k
  if (T.isNull())
856
0
    return true;
857
1.24k
858
1.24k
  if (!T->isDependentType() && 
!T->getAs<TagType>()70
) {
859
7
    Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)
860
7
      << T << getLangOpts().CPlusPlus;
861
7
    return true;
862
7
  }
863
1.23k
864
1.23k
  TypeLocBuilder TLB;
865
1.23k
  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
866
1.23k
  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
867
1.23k
  SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
868
1.23k
            ColonColonLoc);
869
1.23k
  return false;
870
1.23k
}
871
872
/// IsInvalidUnlessNestedName - This method is used for error recovery
873
/// purposes to determine whether the specified identifier is only valid as
874
/// a nested name specifier, for example a namespace name.  It is
875
/// conservatively correct to always return false from this method.
876
///
877
/// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
878
bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
879
                                     NestedNameSpecInfo &IdInfo,
880
953
                                     bool EnteringContext) {
881
953
  if (SS.isInvalid())
882
0
    return false;
883
953
884
953
  return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
885
953
                                      /*ScopeLookupResult=*/nullptr, true);
886
953
}
887
888
bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
889
                                       CXXScopeSpec &SS,
890
                                       SourceLocation TemplateKWLoc,
891
                                       TemplateTy OpaqueTemplate,
892
                                       SourceLocation TemplateNameLoc,
893
                                       SourceLocation LAngleLoc,
894
                                       ASTTemplateArgsPtr TemplateArgsIn,
895
                                       SourceLocation RAngleLoc,
896
                                       SourceLocation CCLoc,
897
1.19M
                                       bool EnteringContext) {
898
1.19M
  if (SS.isInvalid())
899
0
    return true;
900
1.19M
901
1.19M
  TemplateName Template = OpaqueTemplate.get();
902
1.19M
903
1.19M
  // Translate the parser's template argument list in our AST format.
904
1.19M
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
905
1.19M
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
906
1.19M
907
1.19M
  DependentTemplateName *DTN = Template.getAsDependentTemplateName();
908
1.19M
  if (DTN && 
DTN->isIdentifier()1.20k
) {
909
1.19k
    // Handle a dependent template specialization for which we cannot resolve
910
1.19k
    // the template name.
911
1.19k
    assert(DTN->getQualifier() == SS.getScopeRep());
912
1.19k
    QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
913
1.19k
                                                          DTN->getQualifier(),
914
1.19k
                                                          DTN->getIdentifier(),
915
1.19k
                                                                TemplateArgs);
916
1.19k
917
1.19k
    // Create source-location information for this type.
918
1.19k
    TypeLocBuilder Builder;
919
1.19k
    DependentTemplateSpecializationTypeLoc SpecTL
920
1.19k
      = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
921
1.19k
    SpecTL.setElaboratedKeywordLoc(SourceLocation());
922
1.19k
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
923
1.19k
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
924
1.19k
    SpecTL.setTemplateNameLoc(TemplateNameLoc);
925
1.19k
    SpecTL.setLAngleLoc(LAngleLoc);
926
1.19k
    SpecTL.setRAngleLoc(RAngleLoc);
927
2.40k
    for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I1.20k
)
928
1.20k
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
929
1.19k
930
1.19k
    SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
931
1.19k
              CCLoc);
932
1.19k
    return false;
933
1.19k
  }
934
1.19M
935
1.19M
  // If we assumed an undeclared identifier was a template name, try to
936
1.19M
  // typo-correct it now.
937
1.19M
  if (Template.getAsAssumedTemplateName() &&
938
1.19M
      
resolveAssumedTemplateNameAsType(S, Template, TemplateNameLoc)8
)
939
5
    return true;
940
1.19M
941
1.19M
  TemplateDecl *TD = Template.getAsTemplateDecl();
942
1.19M
  if (Template.getAsOverloadedTemplate() || 
DTN1.19M
||
943
1.19M
      
isa<FunctionTemplateDecl>(TD)1.19M
||
isa<VarTemplateDecl>(TD)1.19M
) {
944
17
    SourceRange R(TemplateNameLoc, RAngleLoc);
945
17
    if (SS.getRange().isValid())
946
8
      R.setBegin(SS.getRange().getBegin());
947
17
948
17
    Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
949
17
      << (TD && 
isa<VarTemplateDecl>(TD)6
) << Template << R;
950
17
    NoteAllFoundTemplates(Template);
951
17
    return true;
952
17
  }
953
1.19M
954
1.19M
  // We were able to resolve the template name to an actual template.
955
1.19M
  // Build an appropriate nested-name-specifier.
956
1.19M
  QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
957
1.19M
  if (T.isNull())
958
10
    return true;
959
1.19M
960
1.19M
  // Alias template specializations can produce types which are not valid
961
1.19M
  // nested name specifiers.
962
1.19M
  if (!T->isDependentType() && 
!T->getAs<TagType>()58.8k
) {
963
2
    Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
964
2
    NoteAllFoundTemplates(Template);
965
2
    return true;
966
2
  }
967
1.19M
968
1.19M
  // Provide source-location information for the template specialization type.
969
1.19M
  TypeLocBuilder Builder;
970
1.19M
  TemplateSpecializationTypeLoc SpecTL
971
1.19M
    = Builder.push<TemplateSpecializationTypeLoc>(T);
972
1.19M
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
973
1.19M
  SpecTL.setTemplateNameLoc(TemplateNameLoc);
974
1.19M
  SpecTL.setLAngleLoc(LAngleLoc);
975
1.19M
  SpecTL.setRAngleLoc(RAngleLoc);
976
3.00M
  for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I1.81M
)
977
1.81M
    SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
978
1.19M
979
1.19M
980
1.19M
  SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
981
1.19M
            CCLoc);
982
1.19M
  return false;
983
1.19M
}
984
985
namespace {
986
  /// A structure that stores a nested-name-specifier annotation,
987
  /// including both the nested-name-specifier
988
  struct NestedNameSpecifierAnnotation {
989
    NestedNameSpecifier *NNS;
990
  };
991
}
992
993
2.93M
void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
994
2.93M
  if (SS.isEmpty() || SS.isInvalid())
995
249
    return nullptr;
996
2.93M
997
2.93M
  void *Mem = Context.Allocate(
998
2.93M
      (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
999
2.93M
      alignof(NestedNameSpecifierAnnotation));
1000
2.93M
  NestedNameSpecifierAnnotation *Annotation
1001
2.93M
    = new (Mem) NestedNameSpecifierAnnotation;
1002
2.93M
  Annotation->NNS = SS.getScopeRep();
1003
2.93M
  memcpy(Annotation + 1, SS.location_data(), SS.location_size());
1004
2.93M
  return Annotation;
1005
2.93M
}
1006
1007
void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
1008
                                                SourceRange AnnotationRange,
1009
3.56M
                                                CXXScopeSpec &SS) {
1010
3.56M
  if (!AnnotationPtr) {
1011
293
    SS.SetInvalid(AnnotationRange);
1012
293
    return;
1013
293
  }
1014
3.56M
1015
3.56M
  NestedNameSpecifierAnnotation *Annotation
1016
3.56M
    = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
1017
3.56M
  SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
1018
3.56M
}
1019
1020
273k
bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1021
273k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1022
273k
1023
273k
  // Don't enter a declarator context when the current context is an Objective-C
1024
273k
  // declaration.
1025
273k
  if (isa<ObjCContainerDecl>(CurContext) || 
isa<ObjCMethodDecl>(CurContext)273k
)
1026
12
    return false;
1027
273k
1028
273k
  NestedNameSpecifier *Qualifier = SS.getScopeRep();
1029
273k
1030
273k
  // There are only two places a well-formed program may qualify a
1031
273k
  // declarator: first, when defining a namespace or class member
1032
273k
  // out-of-line, and second, when naming an explicitly-qualified
1033
273k
  // friend function.  The latter case is governed by
1034
273k
  // C++03 [basic.lookup.unqual]p10:
1035
273k
  //   In a friend declaration naming a member function, a name used
1036
273k
  //   in the function declarator and not part of a template-argument
1037
273k
  //   in a template-id is first looked up in the scope of the member
1038
273k
  //   function's class. If it is not found, or if the name is part of
1039
273k
  //   a template-argument in a template-id, the look up is as
1040
273k
  //   described for unqualified names in the definition of the class
1041
273k
  //   granting friendship.
1042
273k
  // i.e. we don't push a scope unless it's a class member.
1043
273k
1044
273k
  switch (Qualifier->getKind()) {
1045
930
  case NestedNameSpecifier::Global:
1046
930
  case NestedNameSpecifier::Namespace:
1047
930
  case NestedNameSpecifier::NamespaceAlias:
1048
930
    // These are always namespace scopes.  We never want to enter a
1049
930
    // namespace scope from anything but a file context.
1050
930
    return CurContext->getRedeclContext()->isFileContext();
1051
930
1052
272k
  case NestedNameSpecifier::Identifier:
1053
272k
  case NestedNameSpecifier::TypeSpec:
1054
272k
  case NestedNameSpecifier::TypeSpecWithTemplate:
1055
272k
  case NestedNameSpecifier::Super:
1056
272k
    // These are never namespace scopes.
1057
272k
    return true;
1058
0
  }
1059
0
1060
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1061
0
}
1062
1063
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
1064
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
1065
/// After this method is called, according to [C++ 3.4.3p3], names should be
1066
/// looked up in the declarator-id's scope, until the declarator is parsed and
1067
/// ActOnCXXExitDeclaratorScope is called.
1068
/// The 'SS' should be a non-empty valid CXXScopeSpec.
1069
272k
bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
1070
272k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1071
272k
1072
272k
  if (SS.isInvalid()) 
return true0
;
1073
272k
1074
272k
  DeclContext *DC = computeDeclContext(SS, true);
1075
272k
  if (!DC) 
return true38
;
1076
272k
1077
272k
  // Before we enter a declarator's context, we need to make sure that
1078
272k
  // it is a complete declaration context.
1079
272k
  if (!DC->isDependentContext() && 
RequireCompleteDeclContext(SS, DC)50.2k
)
1080
8
    return true;
1081
272k
1082
272k
  EnterDeclaratorContext(S, DC);
1083
272k
1084
272k
  // Rebuild the nested name specifier for the new scope.
1085
272k
  if (DC->isDependentContext())
1086
222k
    RebuildNestedNameSpecifierInCurrentInstantiation(SS);
1087
272k
1088
272k
  return false;
1089
272k
}
1090
1091
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
1092
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
1093
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
1094
/// Used to indicate that names should revert to being looked up in the
1095
/// defining scope.
1096
272k
void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1097
272k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1098
272k
  if (SS.isInvalid())
1099
0
    return;
1100
272k
  assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
1101
272k
         "exiting declarator scope we never really entered");
1102
272k
  ExitDeclaratorContext(S);
1103
272k
}