Coverage Report

Created: 2020-10-24 06:27

/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.52M
                                                DeclContext *CurContext) {
29
5.52M
  if (T.isNull())
30
0
    return nullptr;
31
32
5.52M
  const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
33
5.52M
  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
12.1k
      return Record;
38
39
13.4k
    return nullptr;
40
5.49M
  } else if (isa<InjectedClassNameType>(Ty))
41
1.61M
    return cast<InjectedClassNameType>(Ty)->getDecl();
42
3.87M
  else
43
3.87M
    return nullptr;
44
5.52M
}
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
861k
DeclContext *Sema::computeDeclContext(QualType T) {
54
861k
  if (!T->isDependentType())
55
178k
    if (const TagType *Tag = T->getAs<TagType>())
56
177k
      return Tag->getDecl();
57
58
683k
  return ::getCurrentInstantiationOf(T, CurContext);
59
683k
}
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
9.40M
                                      bool EnteringContext) {
76
9.40M
  if (!SS.isSet() || 
SS.isInvalid()9.40M
)
77
395
    return nullptr;
78
79
9.40M
  NestedNameSpecifier *NNS = SS.getScopeRep();
80
9.40M
  if (NNS->isDependent()) {
81
    // If this nested-name-specifier refers to the current
82
    // instantiation, return its DeclContext.
83
4.87M
    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
84
953k
      return Record;
85
86
3.92M
    if (EnteringContext) {
87
240k
      const Type *NNSType = NNS->getAsType();
88
240k
      if (!NNSType) {
89
48
        return nullptr;
90
48
      }
91
92
      // Look through type alias templates, per C++0x [temp.dep.type]p1.
93
240k
      NNSType = Context.getCanonicalType(NNSType);
94
240k
      if (const TemplateSpecializationType *SpecType
95
237k
            = NNSType->getAs<TemplateSpecializationType>()) {
96
        // We are entering the context of the nested name specifier, so try to
97
        // match the nested name specifier to either a primary class template
98
        // or a class template partial specialization.
99
237k
        if (ClassTemplateDecl *ClassTemplate
100
237k
              = dyn_cast_or_null<ClassTemplateDecl>(
101
237k
                            SpecType->getTemplateName().getAsTemplateDecl())) {
102
237k
          QualType ContextType
103
237k
            = Context.getCanonicalType(QualType(SpecType, 0));
104
105
          // If the type of the nested name specifier is the same as the
106
          // injected class name of the named class template, we're entering
107
          // into that class template definition.
108
237k
          QualType Injected
109
237k
            = ClassTemplate->getInjectedClassNameSpecialization();
110
237k
          if (Context.hasSameType(Injected, ContextType))
111
177k
            return ClassTemplate->getTemplatedDecl();
112
113
          // If the type of the nested name specifier is the same as the
114
          // type of one of the class template's class template partial
115
          // specializations, we're entering into the definition of that
116
          // class template partial specialization.
117
59.2k
          if (ClassTemplatePartialSpecializationDecl *PartialSpec
118
58.3k
                = ClassTemplate->findPartialSpecialization(ContextType)) {
119
            // A declaration of the partial specialization must be visible.
120
            // We can always recover here, because this only happens when we're
121
            // entering the context, and that can't happen in a SFINAE context.
122
58.3k
            assert(!isSFINAEContext() &&
123
58.3k
                   "partial specialization scope specifier in SFINAE context?");
124
58.3k
            if (!hasVisibleDeclaration(PartialSpec))
125
30
              diagnoseMissingImport(SS.getLastQualifierNameLoc(), PartialSpec,
126
30
                                    MissingImportKind::PartialSpecialization,
127
30
                                    /*Recover*/true);
128
58.3k
            return PartialSpec;
129
58.3k
          }
130
3.29k
        }
131
3.29k
      } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
132
        // The nested name specifier refers to a member of a class template.
133
2.90k
        return RecordT->getDecl();
134
2.90k
      }
135
3.68M
    }
136
137
3.68M
    return nullptr;
138
3.68M
  }
139
140
4.52M
  switch (NNS->getKind()) {
141
0
  case NestedNameSpecifier::Identifier:
142
0
    llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
143
144
1.82M
  case NestedNameSpecifier::Namespace:
145
1.82M
    return NNS->getAsNamespace();
146
147
731
  case NestedNameSpecifier::NamespaceAlias:
148
731
    return NNS->getAsNamespaceAlias()->getNamespace();
149
150
2.29M
  case NestedNameSpecifier::TypeSpec:
151
2.29M
  case NestedNameSpecifier::TypeSpecWithTemplate: {
152
2.29M
    const TagType *Tag = NNS->getAsType()->getAs<TagType>();
153
2.29M
    assert(Tag && "Non-tag type in nested-name-specifier");
154
2.29M
    return Tag->getDecl();
155
2.29M
  }
156
157
396k
  case NestedNameSpecifier::Global:
158
396k
    return Context.getTranslationUnitDecl();
159
160
70
  case NestedNameSpecifier::Super:
161
70
    return NNS->getAsRecordDecl();
162
0
  }
163
164
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
165
0
}
166
167
2.36M
bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
168
2.36M
  if (!SS.isSet() || 
SS.isInvalid()2.00M
)
169
354k
    return false;
170
171
2.00M
  return SS.getScopeRep()->isDependent();
172
2.00M
}
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
4.87M
CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
180
4.87M
  assert(getLangOpts().CPlusPlus && "Only callable in C++");
181
4.87M
  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
182
183
4.87M
  if (!NNS->getAsType())
184
39.4k
    return nullptr;
185
186
4.83M
  QualType T = QualType(NNS->getAsType(), 0);
187
4.83M
  return ::getCurrentInstantiationOf(T, CurContext);
188
4.83M
}
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
3.99M
                                      DeclContext *DC) {
201
3.99M
  assert(DC && "given null context");
202
203
3.99M
  TagDecl *tag = dyn_cast<TagDecl>(DC);
204
205
  // If this is a dependent type, then we consider it complete.
206
  // FIXME: This is wrong; we should require a (visible) definition to
207
  // exist in this case too.
208
3.99M
  if (!tag || 
tag->isDependentContext()2.13M
)
209
1.91M
    return false;
210
211
  // Grab the tag definition, if there is one.
212
2.07M
  QualType type = Context.getTypeDeclType(tag);
213
2.07M
  tag = type->getAsTagDecl();
214
215
  // If we're currently defining this type, then lookup into the
216
  // type is okay: don't complain that it isn't complete yet.
217
2.07M
  if (tag->isBeingDefined())
218
2.87k
    return false;
219
220
2.07M
  SourceLocation loc = SS.getLastQualifierNameLoc();
221
2.07M
  if (loc.isInvalid()) 
loc = SS.getRange().getBegin()505
;
222
223
  // The type must be complete.
224
2.07M
  if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
225
676
                          SS.getRange())) {
226
676
    SS.SetInvalid(SS.getRange());
227
676
    return true;
228
676
  }
229
230
  // Fixed enum types are complete, but they aren't valid as scopes
231
  // until we see a definition, so awkwardly pull out this special
232
  // case.
233
2.07M
  auto *EnumD = dyn_cast<EnumDecl>(tag);
234
2.07M
  if (!EnumD)
235
2.05M
    return false;
236
19.3k
  if (EnumD->isCompleteDefinition()) {
237
    // If we know about the definition but it is not visible, complain.
238
19.3k
    NamedDecl *SuggestedDef = nullptr;
239
19.3k
    if (!hasVisibleDefinition(EnumD, &SuggestedDef,
240
25
                              /*OnlyNeedComplete*/false)) {
241
      // If the user is going to see an error here, recover by making the
242
      // 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
19.2k
    return false;
249
19.2k
  }
250
251
  // Try to instantiate the definition, if this is a specialization of an
252
  // enumeration temploid.
253
23
  if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {
254
18
    MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();
255
18
    if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
256
17
      if (InstantiateEnum(loc, EnumD, Pattern,
257
17
                          getTemplateInstantiationArgs(EnumD),
258
3
                          TSK_ImplicitInstantiation)) {
259
3
        SS.SetInvalid(SS.getRange());
260
3
        return true;
261
3
      }
262
14
      return false;
263
14
    }
264
18
  }
265
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
129k
                                        CXXScopeSpec &SS) {
274
129k
  SS.MakeGlobal(Context, CCLoc);
275
129k
  return false;
276
129k
}
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
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
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.27M
                                           bool *IsExtension) {
316
1.27M
  if (!SD)
317
1.16k
    return false;
318
319
1.27M
  SD = SD->getUnderlyingDecl();
320
321
  // Namespace and namespace aliases are fine.
322
1.27M
  if (isa<NamespaceDecl>(SD))
323
828k
    return true;
324
325
448k
  if (!isa<TypeDecl>(SD))
326
10
    return false;
327
328
  // Determine whether we have a class (or, in C++11, an enum) or
329
  // a typedef thereof. If so, build the nested-name-specifier.
330
448k
  QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
331
448k
  if (T->isDependentType())
332
331k
    return true;
333
117k
  if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
334
14.9k
    if (TD->getUnderlyingType()->isRecordType())
335
14.8k
      return true;
336
32
    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
102k
  } else if (isa<RecordDecl>(SD)) {
343
97.3k
    return true;
344
4.70k
  } else if (isa<EnumDecl>(SD)) {
345
4.70k
    if (Context.getLangOpts().CPlusPlus11)
346
4.68k
      return true;
347
22
    if (IsExtension)
348
13
      *IsExtension = true;
349
22
  }
350
351
35
  return false;
352
117k
}
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
644
NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
359
644
  if (!S || !NNS)
360
0
    return nullptr;
361
362
810
  
while (644
NNS->getPrefix())
363
166
    NNS = NNS->getPrefix();
364
365
644
  if (NNS->getKind() != NestedNameSpecifier::Identifier)
366
575
    return nullptr;
367
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
373
69
  if (!Found.isSingleResult())
374
15
    return nullptr;
375
376
54
  NamedDecl *Result = Found.getFoundDecl();
377
54
  if (isAcceptableNestedNameSpecifier(Result))
378
53
    return Result;
379
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
389
  // Determine where to perform name lookup
390
0
  DeclContext *LookupCtx = nullptr;
391
0
  bool isDependent = false;
392
0
  if (!ObjectType.isNull()) {
393
    // This nested-name-specifier occurs in a member access expression, e.g.,
394
    // 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
    // This nested-name-specifier occurs after another nested-name-specifier,
400
    // 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
406
0
  if (LookupCtx) {
407
    // Perform "qualified" name lookup into the declaration context we
408
    // computed, which is either the type of the base of a member access
409
    // expression or the declaration context associated with a prior
410
    // nested-name-specifier.
411
412
    // The declaration context must be complete.
413
0
    if (!LookupCtx->isDependentContext() &&
414
0
        RequireCompleteDeclContext(SS, LookupCtx))
415
0
      return false;
416
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
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
174
      : SRef(SRef) {}
437
438
79
  bool ValidateCandidate(const TypoCorrection &candidate) override {
439
79
    return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
440
79
  }
441
442
149
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
443
149
    return std::make_unique<NestedNameSpecifierValidatorCCC>(*this);
444
149
  }
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.29M
                                       bool OnlyNamespace) {
489
1.29M
  if (IdInfo.Identifier->isEditorPlaceholder())
490
4
    return true;
491
1.29M
  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
492
205
                     OnlyNamespace ? LookupNamespaceName
493
1.29M
                                   : LookupNestedNameSpecifierName);
494
1.29M
  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
495
496
  // Determine where to perform name lookup
497
1.29M
  DeclContext *LookupCtx = nullptr;
498
1.29M
  bool isDependent = false;
499
1.29M
  if (IsCorrectedToColon)
500
98.4k
    *IsCorrectedToColon = false;
501
1.29M
  if (!ObjectType.isNull()) {
502
    // This nested-name-specifier occurs in a member access expression, e.g.,
503
    // x->B::f, and we are looking into the type of the object.
504
671
    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
505
671
    LookupCtx = computeDeclContext(ObjectType);
506
671
    isDependent = ObjectType->isDependentType();
507
1.28M
  } else if (SS.isSet()) {
508
    // This nested-name-specifier occurs after another nested-name-specifier,
509
    // so look into the context associated with the prior nested-name-specifier.
510
368k
    LookupCtx = computeDeclContext(SS, EnteringContext);
511
368k
    isDependent = isDependentScopeSpecifier(SS);
512
368k
    Found.setContextRange(SS.getRange());
513
368k
  }
514
515
1.29M
  bool ObjectTypeSearchedInScope = false;
516
1.29M
  if (LookupCtx) {
517
    // Perform "qualified" name lookup into the declaration context we
518
    // computed, which is either the type of the base of a member access
519
    // expression or the declaration context associated with a prior
520
    // nested-name-specifier.
521
522
    // The declaration context must be complete.
523
356k
    if (!LookupCtx->isDependentContext() &&
524
355k
        RequireCompleteDeclContext(SS, LookupCtx))
525
0
      return true;
526
527
356k
    LookupQualifiedName(Found, LookupCtx);
528
529
356k
    if (!ObjectType.isNull() && 
Found.empty()562
) {
530
      // C++ [basic.lookup.classref]p4:
531
      //   If the id-expression in a class member access is a qualified-id of
532
      //   the form
533
      //
534
      //        class-name-or-namespace-name::...
535
      //
536
      //   the class-name-or-namespace-name following the . or -> operator is
537
      //   looked up both in the context of the entire postfix-expression and in
538
      //   the scope of the class of the object expression. If the name is found
539
      //   only in the scope of the class of the object expression, the name
540
      //   shall refer to a class-name. If the name is found only in the
541
      //   context of the entire postfix-expression, the name shall refer to a
542
      //   class-name or namespace-name. [...]
543
      //
544
      // Qualified name lookup into a class will not find a namespace-name,
545
      // so we do not need to diagnose that case specifically. However,
546
      // this qualified name lookup may find nothing. In that case, perform
547
      // unqualified name lookup in the given scope (if available) or
548
      // reconstruct the result from when name lookup was performed at template
549
      // definition time.
550
256
      if (S)
551
229
        LookupName(Found, S);
552
27
      else if (ScopeLookupResult)
553
22
        Found.addDecl(ScopeLookupResult);
554
555
256
      ObjectTypeSearchedInScope = true;
556
256
    }
557
934k
  } else if (!isDependent) {
558
    // Perform unqualified name lookup in the current scope.
559
921k
    LookupName(Found, S);
560
921k
  }
561
562
1.29M
  if (Found.isAmbiguous())
563
5
    return true;
564
565
  // If we performed lookup into a dependent context and did not find anything,
566
  // that's fine: just build a dependent nested-name-specifier.
567
1.29M
  if (Found.empty() && 
isDependent13.7k
&&
568
12.5k
      !(LookupCtx && 
LookupCtx->isRecord()6
&&
569
6
        (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
570
12.5k
         
!cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()3
))) {
571
    // Don't speculate if we're just trying to improve error recovery.
572
12.5k
    if (ErrorRecoveryLookup)
573
0
      return true;
574
575
    // We were not able to compute the declaration context for a dependent
576
    // base object type or prior nested-name-specifier, so this
577
    // nested-name-specifier refers to an unknown specialization. Just build
578
    // 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
583
1.27M
  if (Found.empty() && 
!ErrorRecoveryLookup1.24k
) {
584
    // If identifier is not found as class-name-or-namespace-name, but is found
585
    // as other entity, don't look for typos.
586
212
    LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
587
212
    if (LookupCtx)
588
46
      LookupQualifiedName(R, LookupCtx);
589
166
    else if (S && 
!isDependent164
)
590
164
      LookupName(R, S);
591
212
    if (!R.empty()) {
592
      // Don't diagnose problems with this speculative lookup.
593
24
      R.suppressDiagnostics();
594
      // The identifier is found in ordinary lookup. If correction to colon is
595
      // 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
      // Replacement '::' -> ':' is not allowed, just issue respective error.
606
15
      Diag(R.getNameLoc(), OnlyNamespace
607
9
                               ? unsigned(diag::err_expected_namespace_name)
608
6
                               : unsigned(diag::err_expected_class_or_namespace))
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
212
  }
616
617
1.27M
  if (Found.empty() && 
!ErrorRecoveryLookup1.21k
&&
!getLangOpts().MSVCCompat188
) {
618
    // We haven't found anything, and we're not recovering from a
619
    // different kind of error, so look for typos.
620
174
    DeclarationName Name = Found.getLookupName();
621
174
    Found.clear();
622
174
    NestedNameSpecifierValidatorCCC CCC(*this);
623
174
    if (TypoCorrection Corrected = CorrectTypo(
624
66
            Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, CCC,
625
66
            CTK_ErrorRecovery, LookupCtx, EnteringContext)) {
626
66
      if (LookupCtx) {
627
10
        bool DroppedSpecifier =
628
10
            Corrected.WillReplaceSpecifier() &&
629
6
            Name.getAsString() == Corrected.getAsString(getLangOpts());
630
10
        if (DroppedSpecifier)
631
2
          SS.clear();
632
10
        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
633
10
                                  << Name << LookupCtx << DroppedSpecifier
634
10
                                  << SS.getRange());
635
10
      } else
636
56
        diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
637
56
                                  << Name);
638
639
66
      if (Corrected.getCorrectionSpecifier())
640
12
        SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
641
12
                       SourceRange(Found.getNameLoc()));
642
643
66
      if (NamedDecl *ND = Corrected.getFoundDecl())
644
66
        Found.addDecl(ND);
645
66
      Found.setLookupName(Corrected.getCorrection());
646
108
    } else {
647
108
      Found.setLookupName(IdInfo.Identifier);
648
108
    }
649
174
  }
650
651
1.27M
  NamedDecl *SD =
652
1.27M
      Found.isSingleResult() ? Found.getRepresentativeDecl() : 
nullptr1.15k
;
653
1.27M
  bool IsExtension = false;
654
1.27M
  bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);
655
1.27M
  if (!AcceptSpec && 
IsExtension1.17k
) {
656
13
    AcceptSpec = true;
657
13
    Diag(IdInfo.IdentifierLoc, diag::ext_nested_name_spec_is_enum);
658
13
  }
659
1.27M
  if (AcceptSpec) {
660
1.27M
    if (!ObjectType.isNull() && 
!ObjectTypeSearchedInScope583
&&
661
341
        !getLangOpts().CPlusPlus11) {
662
      // C++03 [basic.lookup.classref]p4:
663
      //   [...] If the name is found in both contexts, the
664
      //   class-name-or-namespace-name shall refer to the same entity.
665
      //
666
      // We already found the name in the scope of the object. Now, look
667
      // into the current scope (the scope of the postfix-expression) to
668
      // see if we can find the same name there. As above, if there is no
669
      // scope, reconstruct the result from the template instantiation itself.
670
      //
671
      // Note that C++11 does *not* perform this redundant lookup.
672
50
      NamedDecl *OuterDecl;
673
50
      if (S) {
674
41
        LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
675
41
                                LookupNestedNameSpecifierName);
676
41
        LookupName(FoundOuter, S);
677
41
        OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
678
41
      } else
679
9
        OuterDecl = ScopeLookupResult;
680
681
50
      if (isAcceptableNestedNameSpecifier(OuterDecl) &&
682
39
          OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
683
28
          (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
684
28
           !Context.hasSameType(
685
28
                            Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
686
2
                               Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
687
2
        if (ErrorRecoveryLookup)
688
0
          return true;
689
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
697
         // Fall through so that we'll pick the name we found in the object
698
         // type, since that's probably what the user wanted anyway.
699
2
       }
700
50
    }
701
702
1.27M
    if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))
703
206k
      MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
704
705
    // If we're just performing this lookup for error-recovery purposes,
706
    // don't extend the nested-name-specifier. Just return now.
707
1.27M
    if (ErrorRecoveryLookup)
708
159
      return false;
709
710
    // The use of a nested name specifier may trigger deprecation warnings.
711
1.27M
    DiagnoseUseOfDecl(SD, IdInfo.CCLoc);
712
713
1.27M
    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
714
828k
      SS.Extend(Context, Namespace, IdInfo.IdentifierLoc, IdInfo.CCLoc);
715
828k
      return false;
716
828k
    }
717
718
448k
    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
719
216
      SS.Extend(Context, Alias, IdInfo.IdentifierLoc, IdInfo.CCLoc);
720
216
      return false;
721
216
    }
722
723
448k
    QualType T =
724
448k
        Context.getTypeDeclType(cast<TypeDecl>(SD->getUnderlyingDecl()));
725
448k
    TypeLocBuilder TLB;
726
448k
    if (isa<InjectedClassNameType>(T)) {
727
1.11k
      InjectedClassNameTypeLoc InjectedTL
728
1.11k
        = TLB.push<InjectedClassNameTypeLoc>(T);
729
1.11k
      InjectedTL.setNameLoc(IdInfo.IdentifierLoc);
730
447k
    } else if (isa<RecordType>(T)) {
731
100k
      RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
732
100k
      RecordTL.setNameLoc(IdInfo.IdentifierLoc);
733
347k
    } else if (isa<TypedefType>(T)) {
734
206k
      TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
735
206k
      TypedefTL.setNameLoc(IdInfo.IdentifierLoc);
736
140k
    } else if (isa<EnumType>(T)) {
737
4.70k
      EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
738
4.70k
      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
1
    } else if (isa<UnresolvedUsingType>(T)) {
744
1
      UnresolvedUsingTypeLoc UnresolvedTL
745
1
        = TLB.push<UnresolvedUsingTypeLoc>(T);
746
1
      UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc);
747
0
    } else if (isa<SubstTemplateTypeParmType>(T)) {
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
759
448k
    if (T->isEnumeralType())
760
4.72k
      Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
761
762
448k
    SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
763
448k
              IdInfo.CCLoc);
764
448k
    return false;
765
448k
  }
766
767
  // Otherwise, we have an error case.  If we don't want diagnostics, just
768
  // return an error now.
769
1.16k
  if (ErrorRecoveryLookup)
770
1.03k
    return true;
771
772
  // If we didn't find anything during our lookup, try again with
773
  // ordinary name lookup, which can help us produce better error
774
  // messages.
775
133
  if (Found.empty()) {
776
122
    Found.clear(LookupOrdinaryName);
777
122
    LookupName(Found, S);
778
122
  }
779
780
  // In Microsoft mode, if we are within a templated function and we can't
781
  // resolve Identifier, then extend the SS with Identifier. This will have
782
  // the effect of resolving Identifier during template instantiation.
783
  // The goal is to be able to resolve a function call whose
784
  // nested-name-specifier is located inside a dependent base class.
785
  // Example:
786
  //
787
  // class C {
788
  // public:
789
  //    static void foo2() {  }
790
  // };
791
  // template <class T> class A { public: typedef C D; };
792
  //
793
  // template <class T> class B : public A<T> {
794
  // public:
795
  //   void foo() { D::foo2(); }
796
  // };
797
133
  if (getLangOpts().MSVCCompat) {
798
12
    DeclContext *DC = LookupCtx ? 
LookupCtx4
: CurContext;
799
16
    if (DC->isDependentContext() && 
DC->isFunctionOrMethod()9
) {
800
9
      CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());
801
9
      if (ContainingClass && 
ContainingClass->hasAnyDependentBases()7
) {
802
6
        Diag(IdInfo.IdentifierLoc,
803
6
             diag::ext_undeclared_unqual_id_with_dependent_base)
804
6
            << IdInfo.Identifier << ContainingClass;
805
6
        SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc,
806
6
                  IdInfo.CCLoc);
807
6
        return false;
808
6
      }
809
127
    }
810
16
  }
811
812
127
  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
117
  } else if (SS.isSet())
824
15
    Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier
825
15
        << LookupCtx << SS.getRange();
826
102
  else
827
102
    Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)
828
102
        << IdInfo.Identifier;
829
830
127
  return true;
831
127
}
832
833
bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
834
                                       bool EnteringContext, CXXScopeSpec &SS,
835
                                       bool ErrorRecoveryLookup,
836
                                       bool *IsCorrectedToColon,
837
1.28M
                                       bool OnlyNamespace) {
838
1.28M
  if (SS.isInvalid())
839
17
    return true;
840
841
1.28M
  return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
842
1.28M
                                     /*ScopeLookupResult=*/nullptr, false,
843
1.28M
                                     IsCorrectedToColon, OnlyNamespace);
844
1.28M
}
845
846
bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
847
                                               const DeclSpec &DS,
848
989
                                               SourceLocation ColonColonLoc) {
849
989
  if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
850
4
    return true;
851
852
985
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
853
854
985
  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
855
985
  if (T.isNull())
856
0
    return true;
857
858
985
  if (!T->isDependentType() && 
!T->getAs<TagType>()84
) {
859
7
    Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)
860
7
      << T << getLangOpts().CPlusPlus;
861
7
    return true;
862
7
  }
863
864
978
  TypeLocBuilder TLB;
865
978
  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
866
978
  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
867
978
  SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
868
978
            ColonColonLoc);
869
978
  return false;
870
978
}
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
1.18k
                                     bool EnteringContext) {
881
1.18k
  if (SS.isInvalid())
882
0
    return false;
883
884
1.18k
  return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
885
1.18k
                                      /*ScopeLookupResult=*/nullptr, true);
886
1.18k
}
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.06M
                                       bool EnteringContext) {
898
1.06M
  if (SS.isInvalid())
899
0
    return true;
900
901
1.06M
  TemplateName Template = OpaqueTemplate.get();
902
903
  // Translate the parser's template argument list in our AST format.
904
1.06M
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
905
1.06M
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
906
907
1.06M
  DependentTemplateName *DTN = Template.getAsDependentTemplateName();
908
1.06M
  if (DTN && 
DTN->isIdentifier()1.28k
) {
909
    // Handle a dependent template specialization for which we cannot resolve
910
    // the template name.
911
1.27k
    assert(DTN->getQualifier() == SS.getScopeRep());
912
1.27k
    QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
913
1.27k
                                                          DTN->getQualifier(),
914
1.27k
                                                          DTN->getIdentifier(),
915
1.27k
                                                                TemplateArgs);
916
917
    // Create source-location information for this type.
918
1.27k
    TypeLocBuilder Builder;
919
1.27k
    DependentTemplateSpecializationTypeLoc SpecTL
920
1.27k
      = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
921
1.27k
    SpecTL.setElaboratedKeywordLoc(SourceLocation());
922
1.27k
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
923
1.27k
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
924
1.27k
    SpecTL.setTemplateNameLoc(TemplateNameLoc);
925
1.27k
    SpecTL.setLAngleLoc(LAngleLoc);
926
1.27k
    SpecTL.setRAngleLoc(RAngleLoc);
927
2.55k
    for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I1.27k
)
928
1.27k
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
929
930
1.27k
    SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
931
1.27k
              CCLoc);
932
1.27k
    return false;
933
1.27k
  }
934
935
  // If we assumed an undeclared identifier was a template name, try to
936
  // typo-correct it now.
937
1.05M
  if (Template.getAsAssumedTemplateName() &&
938
11
      resolveAssumedTemplateNameAsType(S, Template, TemplateNameLoc))
939
8
    return true;
940
941
1.05M
  TemplateDecl *TD = Template.getAsTemplateDecl();
942
1.05M
  if (Template.getAsOverloadedTemplate() || 
DTN1.05M
||
943
1.05M
      isa<FunctionTemplateDecl>(TD) || 
isa<VarTemplateDecl>(TD)1.05M
) {
944
17
    SourceRange R(TemplateNameLoc, RAngleLoc);
945
17
    if (SS.getRange().isValid())
946
8
      R.setBegin(SS.getRange().getBegin());
947
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
954
  // We were able to resolve the template name to an actual template.
955
  // Build an appropriate nested-name-specifier.
956
1.05M
  QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
957
1.05M
  if (T.isNull())
958
10
    return true;
959
960
  // Alias template specializations can produce types which are not valid
961
  // nested name specifiers.
962
1.05M
  if (!T->isDependentType() && 
!T->getAs<TagType>()61.7k
) {
963
2
    Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
964
2
    NoteAllFoundTemplates(Template);
965
2
    return true;
966
2
  }
967
968
  // Provide source-location information for the template specialization type.
969
1.05M
  TypeLocBuilder Builder;
970
1.05M
  TemplateSpecializationTypeLoc SpecTL
971
1.05M
    = Builder.push<TemplateSpecializationTypeLoc>(T);
972
1.05M
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
973
1.05M
  SpecTL.setTemplateNameLoc(TemplateNameLoc);
974
1.05M
  SpecTL.setLAngleLoc(LAngleLoc);
975
1.05M
  SpecTL.setRAngleLoc(RAngleLoc);
976
2.67M
  for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I1.62M
)
977
1.62M
    SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
978
979
980
1.05M
  SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
981
1.05M
            CCLoc);
982
1.05M
  return false;
983
1.05M
}
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.50M
void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
994
2.50M
  if (SS.isEmpty() || SS.isInvalid())
995
284
    return nullptr;
996
997
2.50M
  void *Mem = Context.Allocate(
998
2.50M
      (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
999
2.50M
      alignof(NestedNameSpecifierAnnotation));
1000
2.50M
  NestedNameSpecifierAnnotation *Annotation
1001
2.50M
    = new (Mem) NestedNameSpecifierAnnotation;
1002
2.50M
  Annotation->NNS = SS.getScopeRep();
1003
2.50M
  memcpy(Annotation + 1, SS.location_data(), SS.location_size());
1004
2.50M
  return Annotation;
1005
2.50M
}
1006
1007
void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
1008
                                                SourceRange AnnotationRange,
1009
3.04M
                                                CXXScopeSpec &SS) {
1010
3.04M
  if (!AnnotationPtr) {
1011
331
    SS.SetInvalid(AnnotationRange);
1012
331
    return;
1013
331
  }
1014
1015
3.04M
  NestedNameSpecifierAnnotation *Annotation
1016
3.04M
    = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
1017
3.04M
  SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
1018
3.04M
}
1019
1020
259k
bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1021
259k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1022
1023
  // Don't enter a declarator context when the current context is an Objective-C
1024
  // declaration.
1025
259k
  if (isa<ObjCContainerDecl>(CurContext) || 
isa<ObjCMethodDecl>(CurContext)259k
)
1026
12
    return false;
1027
1028
259k
  NestedNameSpecifier *Qualifier = SS.getScopeRep();
1029
1030
  // There are only two places a well-formed program may qualify a
1031
  // declarator: first, when defining a namespace or class member
1032
  // out-of-line, and second, when naming an explicitly-qualified
1033
  // friend function.  The latter case is governed by
1034
  // C++03 [basic.lookup.unqual]p10:
1035
  //   In a friend declaration naming a member function, a name used
1036
  //   in the function declarator and not part of a template-argument
1037
  //   in a template-id is first looked up in the scope of the member
1038
  //   function's class. If it is not found, or if the name is part of
1039
  //   a template-argument in a template-id, the look up is as
1040
  //   described for unqualified names in the definition of the class
1041
  //   granting friendship.
1042
  // i.e. we don't push a scope unless it's a class member.
1043
1044
259k
  switch (Qualifier->getKind()) {
1045
975
  case NestedNameSpecifier::Global:
1046
975
  case NestedNameSpecifier::Namespace:
1047
975
  case NestedNameSpecifier::NamespaceAlias:
1048
    // These are always namespace scopes.  We never want to enter a
1049
    // namespace scope from anything but a file context.
1050
975
    return CurContext->getRedeclContext()->isFileContext();
1051
1052
258k
  case NestedNameSpecifier::Identifier:
1053
258k
  case NestedNameSpecifier::TypeSpec:
1054
258k
  case NestedNameSpecifier::TypeSpecWithTemplate:
1055
258k
  case NestedNameSpecifier::Super:
1056
    // These are never namespace scopes.
1057
258k
    return true;
1058
0
  }
1059
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
258k
bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
1070
258k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1071
1072
258k
  if (SS.isInvalid()) 
return true0
;
1073
1074
258k
  DeclContext *DC = computeDeclContext(SS, true);
1075
258k
  if (!DC) 
return true38
;
1076
1077
  // Before we enter a declarator's context, we need to make sure that
1078
  // it is a complete declaration context.
1079
258k
  if (!DC->isDependentContext() && 
RequireCompleteDeclContext(SS, DC)53.1k
)
1080
8
    return true;
1081
1082
258k
  EnterDeclaratorContext(S, DC);
1083
1084
  // Rebuild the nested name specifier for the new scope.
1085
258k
  if (DC->isDependentContext())
1086
205k
    RebuildNestedNameSpecifierInCurrentInstantiation(SS);
1087
1088
258k
  return false;
1089
258k
}
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
258k
void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1097
258k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1098
258k
  if (SS.isInvalid())
1099
0
    return;
1100
258k
  assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
1101
258k
         "exiting declarator scope we never really entered");
1102
258k
  ExitDeclaratorContext(S);
1103
258k
}