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/Template.h"
22#include "clang/Sema/TypoCorrection.h"
23#include "llvm/ADT/STLExtras.h"
24using namespace clang;
25
26/// Find the current instantiation that associated with the given type.
27static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
28 DeclContext *CurContext) {
29 if (T.isNull())
30 return nullptr;
31
32 const TagType *TagTy = dyn_cast<TagType>(Val: T->getCanonicalTypeInternal());
33 if (!isa_and_present<RecordType, InjectedClassNameType>(Val: TagTy))
34 return nullptr;
35 auto *RD = cast<CXXRecordDecl>(Val: TagTy->getDecl())->getDefinitionOrSelf();
36 if (isa<InjectedClassNameType>(Val: TagTy) ||
37 RD->isCurrentInstantiation(CurContext))
38 return RD;
39 return nullptr;
40}
41
42DeclContext *Sema::computeDeclContext(QualType T) {
43 if (!T->isDependentType())
44 if (auto *D = T->getAsTagDecl())
45 return D;
46 return ::getCurrentInstantiationOf(T, CurContext);
47}
48
49DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
50 bool EnteringContext) {
51 if (!SS.isSet() || SS.isInvalid())
52 return nullptr;
53
54 NestedNameSpecifier NNS = SS.getScopeRep();
55 if (NNS.isDependent()) {
56 // If this nested-name-specifier refers to the current
57 // instantiation, return its DeclContext.
58 if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
59 return Record;
60
61 if (EnteringContext) {
62 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
63 return nullptr;
64 const Type *NNSType = NNS.getAsType();
65
66 // Look through type alias templates, per C++0x [temp.dep.type]p1.
67 NNSType = Context.getCanonicalType(T: NNSType);
68 if (const auto *SpecType =
69 dyn_cast<TemplateSpecializationType>(Val: NNSType)) {
70 // We are entering the context of the nested name specifier, so try to
71 // match the nested name specifier to either a primary class template
72 // or a class template partial specialization.
73 if (ClassTemplateDecl *ClassTemplate =
74 dyn_cast_or_null<ClassTemplateDecl>(
75 Val: SpecType->getTemplateName().getAsTemplateDecl())) {
76 // FIXME: The fallback on the search of partial
77 // specialization using ContextType should be eventually removed since
78 // it doesn't handle the case of constrained template parameters
79 // correctly. Currently removing this fallback would change the
80 // diagnostic output for invalid code in a number of tests.
81 ClassTemplatePartialSpecializationDecl *PartialSpec = nullptr;
82 ArrayRef<TemplateParameterList *> TemplateParamLists =
83 SS.getTemplateParamLists();
84 if (!TemplateParamLists.empty()) {
85 unsigned Depth = ClassTemplate->getTemplateParameters()->getDepth();
86 auto L = find_if(Range&: TemplateParamLists,
87 P: [Depth](TemplateParameterList *TPL) {
88 return TPL->getDepth() == Depth;
89 });
90 if (L != TemplateParamLists.end()) {
91 void *Pos = nullptr;
92 PartialSpec = ClassTemplate->findPartialSpecialization(
93 Args: SpecType->template_arguments(), TPL: *L, InsertPos&: Pos);
94 }
95 } else {
96 PartialSpec =
97 ClassTemplate->findPartialSpecialization(T: QualType(SpecType, 0));
98 }
99
100 if (PartialSpec) {
101 // A declaration of the partial specialization must be visible.
102 // We can always recover here, because this only happens when we're
103 // entering the context, and that can't happen in a SFINAE context.
104 assert(!isSFINAEContext() && "partial specialization scope "
105 "specifier in SFINAE context?");
106 if (PartialSpec->hasDefinition() &&
107 !hasReachableDefinition(D: PartialSpec))
108 diagnoseMissingImport(Loc: SS.getLastQualifierNameLoc(), Decl: PartialSpec,
109 MIK: MissingImportKind::PartialSpecialization,
110 Recover: true);
111 return PartialSpec;
112 }
113
114 // If the type of the nested name specifier is the same as the
115 // injected class name of the named class template, we're entering
116 // into that class template definition.
117 CanQualType Injected =
118 ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context);
119 if (Context.hasSameType(T1: Injected, T2: QualType(SpecType, 0)))
120 return ClassTemplate->getTemplatedDecl();
121 }
122 } else if (const auto *RecordT = dyn_cast<RecordType>(Val: NNSType)) {
123 // The nested name specifier refers to a member of a class template.
124 return RecordT->getDecl()->getDefinitionOrSelf();
125 }
126 }
127
128 return nullptr;
129 }
130
131 switch (NNS.getKind()) {
132 case NestedNameSpecifier::Kind::Namespace:
133 return const_cast<NamespaceDecl *>(
134 NNS.getAsNamespaceAndPrefix().Namespace->getNamespace());
135
136 case NestedNameSpecifier::Kind::Type:
137 return NNS.getAsType()->castAsTagDecl();
138
139 case NestedNameSpecifier::Kind::Global:
140 return Context.getTranslationUnitDecl();
141
142 case NestedNameSpecifier::Kind::MicrosoftSuper:
143 return NNS.getAsMicrosoftSuper();
144
145 case NestedNameSpecifier::Kind::Null:
146 llvm_unreachable("unexpected null nested name specifier");
147 }
148
149 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
150}
151
152bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
153 if (!SS.isSet() || SS.isInvalid())
154 return false;
155
156 return SS.getScopeRep().isDependent();
157}
158
159CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier NNS) {
160 assert(getLangOpts().CPlusPlus && "Only callable in C++");
161 assert(NNS.isDependent() && "Only dependent nested-name-specifier allowed");
162
163 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
164 return nullptr;
165
166 QualType T = QualType(NNS.getAsType(), 0);
167 return ::getCurrentInstantiationOf(T, CurContext);
168}
169
170/// Require that the context specified by SS be complete.
171///
172/// If SS refers to a type, this routine checks whether the type is
173/// complete enough (or can be made complete enough) for name lookup
174/// into the DeclContext. A type that is not yet completed can be
175/// considered "complete enough" if it is a class/struct/union/enum
176/// that is currently being defined. Or, if we have a type that names
177/// a class template specialization that is not a complete type, we
178/// will attempt to instantiate that class template.
179bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
180 DeclContext *DC) {
181 assert(DC && "given null context");
182
183 TagDecl *tag = dyn_cast<TagDecl>(Val: DC);
184
185 // If this is a dependent type, then we consider it complete.
186 // FIXME: This is wrong; we should require a (visible) definition to
187 // exist in this case too.
188 if (!tag || tag->isDependentContext())
189 return false;
190
191 // Grab the tag definition, if there is one.
192 tag = tag->getDefinitionOrSelf();
193
194 // If we're currently defining this type, then lookup into the
195 // type is okay: don't complain that it isn't complete yet.
196 if (tag->isBeingDefined())
197 return false;
198
199 SourceLocation loc = SS.getLastQualifierNameLoc();
200 if (loc.isInvalid()) loc = SS.getRange().getBegin();
201
202 // The type must be complete.
203 if (RequireCompleteType(Loc: loc, T: Context.getCanonicalTagType(TD: tag),
204 DiagID: diag::err_incomplete_nested_name_spec,
205 Args: SS.getRange())) {
206 SS.SetInvalid(SS.getRange());
207 return true;
208 }
209
210 if (auto *EnumD = dyn_cast<EnumDecl>(Val: tag))
211 // Fixed enum types and scoped enum instantiations are complete, but they
212 // aren't valid as scopes until we see or instantiate their definition.
213 return RequireCompleteEnumDecl(D: EnumD, L: loc, SS: &SS);
214
215 return false;
216}
217
218/// Require that the EnumDecl is completed with its enumerators defined or
219/// instantiated. SS, if provided, is the ScopeRef parsed.
220///
221bool Sema::RequireCompleteEnumDecl(EnumDecl *EnumD, SourceLocation L,
222 CXXScopeSpec *SS) {
223 if (EnumDecl *Def = EnumD->getDefinition();
224 Def && Def->isCompleteDefinition()) {
225 // If we know about the definition but it is not visible, complain.
226 NamedDecl *SuggestedDef = nullptr;
227 if (!hasReachableDefinition(D: Def, Suggested: &SuggestedDef,
228 /*OnlyNeedComplete*/ false)) {
229 // If the user is going to see an error here, recover by making the
230 // definition visible.
231 bool TreatAsComplete = !isSFINAEContext();
232 diagnoseMissingImport(Loc: L, Decl: SuggestedDef, MIK: MissingImportKind::Definition,
233 /*Recover*/ TreatAsComplete);
234 return !TreatAsComplete;
235 }
236 return false;
237 }
238
239 // Try to instantiate the definition, if this is a specialization of an
240 // enumeration temploid.
241 if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {
242 MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();
243 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
244 if (InstantiateEnum(PointOfInstantiation: L, Instantiation: EnumD, Pattern,
245 TemplateArgs: getTemplateInstantiationArgs(D: EnumD),
246 TSK: TSK_ImplicitInstantiation)) {
247 if (SS)
248 SS->SetInvalid(SS->getRange());
249 return true;
250 }
251 return false;
252 }
253 }
254
255 if (SS) {
256 Diag(Loc: L, DiagID: diag::err_incomplete_nested_name_spec)
257 << Context.getCanonicalTagType(TD: EnumD) << SS->getRange();
258 SS->SetInvalid(SS->getRange());
259 } else {
260 Diag(Loc: L, DiagID: diag::err_incomplete_enum) << Context.getCanonicalTagType(TD: EnumD);
261 Diag(Loc: EnumD->getLocation(), DiagID: diag::note_declared_at);
262 }
263
264 return true;
265}
266
267bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,
268 CXXScopeSpec &SS) {
269 SS.MakeGlobal(Context, ColonColonLoc: CCLoc);
270 return false;
271}
272
273bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
274 SourceLocation ColonColonLoc,
275 CXXScopeSpec &SS) {
276 if (getCurLambda()) {
277 Diag(Loc: SuperLoc, DiagID: diag::err_super_in_lambda_unsupported);
278 return true;
279 }
280
281 CXXRecordDecl *RD = nullptr;
282 for (Scope *S = getCurScope(); S; S = S->getParent()) {
283 if (S->isFunctionScope()) {
284 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: S->getEntity()))
285 RD = MD->getParent();
286 break;
287 }
288 if (S->isClassScope()) {
289 RD = cast<CXXRecordDecl>(Val: S->getEntity());
290 break;
291 }
292 }
293
294 if (!RD) {
295 Diag(Loc: SuperLoc, DiagID: diag::err_invalid_super_scope);
296 return true;
297 } else if (RD->getNumBases() == 0) {
298 Diag(Loc: SuperLoc, DiagID: diag::err_no_base_classes) << RD->getName();
299 return true;
300 }
301
302 SS.MakeMicrosoftSuper(Context, RD, SuperLoc, ColonColonLoc);
303 return false;
304}
305
306bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,
307 bool *IsExtension) {
308 if (!SD)
309 return false;
310
311 SD = SD->getUnderlyingDecl();
312
313 // Namespace and namespace aliases are fine.
314 if (isa<NamespaceDecl>(Val: SD))
315 return true;
316
317 if (!isa<TypeDecl>(Val: SD))
318 return false;
319
320 // Determine whether we have a class (or, in C++11, an enum) or
321 // a typedef thereof. If so, build the nested-name-specifier.
322 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: SD)) {
323 if (TD->getUnderlyingType()->isRecordType())
324 return true;
325 if (TD->getUnderlyingType()->isEnumeralType()) {
326 if (Context.getLangOpts().CPlusPlus11)
327 return true;
328 if (IsExtension)
329 *IsExtension = true;
330 }
331 } else if (isa<RecordDecl>(Val: SD)) {
332 return true;
333 } else if (isa<EnumDecl>(Val: SD)) {
334 if (Context.getLangOpts().CPlusPlus11)
335 return true;
336 if (IsExtension)
337 *IsExtension = true;
338 }
339 if (auto *TD = dyn_cast<TagDecl>(Val: SD)) {
340 if (TD->isDependentType())
341 return true;
342 } else if (Context.getCanonicalTypeDeclType(TD: cast<TypeDecl>(Val: SD))
343 ->isDependentType()) {
344 return true;
345 }
346
347 return false;
348}
349
350NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS) {
351 if (!S)
352 return nullptr;
353
354 while (NNS.getKind() == NestedNameSpecifier::Kind::Type) {
355 const Type *T = NNS.getAsType();
356 if ((NNS = T->getPrefix()))
357 continue;
358
359 const auto *DNT = dyn_cast<DependentNameType>(Val: T);
360 if (!DNT)
361 break;
362
363 LookupResult Found(*this, DNT->getIdentifier(), SourceLocation(),
364 LookupNestedNameSpecifierName);
365 LookupName(R&: Found, S);
366 assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
367
368 if (!Found.isSingleResult())
369 return nullptr;
370
371 NamedDecl *Result = Found.getFoundDecl();
372 if (isAcceptableNestedNameSpecifier(SD: Result))
373 return Result;
374 }
375 return nullptr;
376}
377
378namespace {
379
380// Callback to only accept typo corrections that can be a valid C++ member
381// initializer: either a non-static field member or a base class.
382class NestedNameSpecifierValidatorCCC final
383 : public QualifiedLookupValidatorCCC {
384public:
385 explicit NestedNameSpecifierValidatorCCC(Sema &SRef, bool HasQualifier)
386 : QualifiedLookupValidatorCCC(HasQualifier), SRef(SRef) {}
387
388 bool ValidateCandidate(const TypoCorrection &candidate) override {
389 if (!QualifiedLookupValidatorCCC::ValidateCandidate(Candidate: candidate))
390 return false;
391 const NamedDecl *ND = candidate.getCorrectionDecl();
392 if (!SRef.isAcceptableNestedNameSpecifier(SD: ND))
393 return false;
394 return true;
395 }
396
397 std::unique_ptr<CorrectionCandidateCallback> clone() override {
398 return std::make_unique<NestedNameSpecifierValidatorCCC>(args&: *this);
399 }
400
401 private:
402 Sema &SRef;
403};
404}
405
406[[nodiscard]] static bool ExtendNestedNameSpecifier(Sema &S, CXXScopeSpec &SS,
407 const NamedDecl *ND,
408 SourceLocation NameLoc,
409 SourceLocation CCLoc) {
410 TypeLocBuilder TLB;
411 QualType T;
412 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: ND)) {
413 T = S.Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
414 D: USD);
415 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
416 QualifierLoc: SS.getWithLocInContext(Context&: S.Context), NameLoc);
417 } else if (const auto *TD = dyn_cast<TypeDecl>(Val: ND)) {
418 T = S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
419 Decl: TD);
420 switch (T->getTypeClass()) {
421 case Type::Record:
422 case Type::InjectedClassName:
423 case Type::Enum: {
424 auto TTL = TLB.push<TagTypeLoc>(T);
425 TTL.setElaboratedKeywordLoc(SourceLocation());
426 TTL.setQualifierLoc(SS.getWithLocInContext(Context&: S.Context));
427 TTL.setNameLoc(NameLoc);
428 break;
429 }
430 case Type::Typedef:
431 TLB.push<TypedefTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
432 QualifierLoc: SS.getWithLocInContext(Context&: S.Context),
433 NameLoc);
434 break;
435 case Type::UnresolvedUsing:
436 TLB.push<UnresolvedUsingTypeLoc>(T).set(
437 /*ElaboratedKeywordLoc=*/SourceLocation(),
438 QualifierLoc: SS.getWithLocInContext(Context&: S.Context), NameLoc);
439 break;
440 default:
441 assert(SS.isEmpty());
442 T = S.Context.getTypeDeclType(Decl: TD);
443 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
444 break;
445 }
446 } else {
447 return false;
448 }
449 SS.clear();
450 SS.Make(Context&: S.Context, TL: TLB.getTypeLocInContext(Context&: S.Context, T), ColonColonLoc: CCLoc);
451 return true;
452}
453
454bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
455 bool EnteringContext, CXXScopeSpec &SS,
456 NamedDecl *ScopeLookupResult,
457 bool ErrorRecoveryLookup,
458 bool *IsCorrectedToColon,
459 bool OnlyNamespace) {
460 if (IdInfo.Identifier->isEditorPlaceholder())
461 return true;
462 LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
463 OnlyNamespace ? LookupNamespaceName
464 : LookupNestedNameSpecifierName);
465 QualType ObjectType = GetTypeFromParser(Ty: IdInfo.ObjectType);
466
467 // Determine where to perform name lookup
468 DeclContext *LookupCtx = nullptr;
469 bool isDependent = false;
470 if (IsCorrectedToColon)
471 *IsCorrectedToColon = false;
472 if (!ObjectType.isNull()) {
473 // This nested-name-specifier occurs in a member access expression, e.g.,
474 // x->B::f, and we are looking into the type of the object.
475 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
476 LookupCtx = computeDeclContext(T: ObjectType);
477 isDependent = ObjectType->isDependentType();
478 } else if (SS.isSet()) {
479 // This nested-name-specifier occurs after another nested-name-specifier,
480 // so look into the context associated with the prior nested-name-specifier.
481 LookupCtx = computeDeclContext(SS, EnteringContext);
482 isDependent = isDependentScopeSpecifier(SS);
483 Found.setContextRange(SS.getRange());
484 }
485
486 bool ObjectTypeSearchedInScope = false;
487 if (LookupCtx) {
488 // Perform "qualified" name lookup into the declaration context we
489 // computed, which is either the type of the base of a member access
490 // expression or the declaration context associated with a prior
491 // nested-name-specifier.
492
493 // The declaration context must be complete.
494 if (!LookupCtx->isDependentContext() &&
495 RequireCompleteDeclContext(SS, DC: LookupCtx))
496 return true;
497
498 LookupQualifiedName(R&: Found, LookupCtx);
499
500 if (!ObjectType.isNull() && Found.empty()) {
501 // C++ [basic.lookup.classref]p4:
502 // If the id-expression in a class member access is a qualified-id of
503 // the form
504 //
505 // class-name-or-namespace-name::...
506 //
507 // the class-name-or-namespace-name following the . or -> operator is
508 // looked up both in the context of the entire postfix-expression and in
509 // the scope of the class of the object expression. If the name is found
510 // only in the scope of the class of the object expression, the name
511 // shall refer to a class-name. If the name is found only in the
512 // context of the entire postfix-expression, the name shall refer to a
513 // class-name or namespace-name. [...]
514 //
515 // Qualified name lookup into a class will not find a namespace-name,
516 // so we do not need to diagnose that case specifically. However,
517 // this qualified name lookup may find nothing. In that case, perform
518 // unqualified name lookup in the given scope (if available) or
519 // reconstruct the result from when name lookup was performed at template
520 // definition time.
521 if (S)
522 LookupName(R&: Found, S);
523 else if (ScopeLookupResult)
524 Found.addDecl(D: ScopeLookupResult);
525
526 ObjectTypeSearchedInScope = true;
527 }
528 } else if (!isDependent) {
529 // Perform unqualified name lookup in the current scope.
530 LookupName(R&: Found, S);
531 }
532
533 if (Found.isAmbiguous())
534 return true;
535
536 // If we performed lookup into a dependent context and did not find anything,
537 // that's fine: just build a dependent nested-name-specifier.
538 if (Found.empty() && isDependent &&
539 !(LookupCtx && LookupCtx->isRecord() &&
540 (!cast<CXXRecordDecl>(Val: LookupCtx)->hasDefinition() ||
541 !cast<CXXRecordDecl>(Val: LookupCtx)->hasAnyDependentBases()))) {
542 // Don't speculate if we're just trying to improve error recovery.
543 if (ErrorRecoveryLookup)
544 return true;
545
546 // We were not able to compute the declaration context for a dependent
547 // base object type or prior nested-name-specifier, so this
548 // nested-name-specifier refers to an unknown specialization. Just build
549 // a dependent nested-name-specifier.
550
551 TypeLocBuilder TLB;
552
553 QualType DTN = Context.getDependentNameType(
554 Keyword: ElaboratedTypeKeyword::None, NNS: SS.getScopeRep(), Name: IdInfo.Identifier);
555 auto DTNL = TLB.push<DependentNameTypeLoc>(T: DTN);
556 DTNL.setElaboratedKeywordLoc(SourceLocation());
557 DTNL.setNameLoc(IdInfo.IdentifierLoc);
558 DTNL.setQualifierLoc(SS.getWithLocInContext(Context));
559
560 SS.clear();
561 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: DTN), ColonColonLoc: IdInfo.CCLoc);
562 return false;
563 }
564
565 if (Found.empty() && !ErrorRecoveryLookup) {
566 // If identifier is not found as class-name-or-namespace-name, but is found
567 // as other entity, don't look for typos.
568 LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
569 if (LookupCtx)
570 LookupQualifiedName(R, LookupCtx);
571 else if (S && !isDependent)
572 LookupName(R, S);
573 if (!R.empty()) {
574 // Don't diagnose problems with this speculative lookup.
575 R.suppressDiagnostics();
576 // The identifier is found in ordinary lookup. If correction to colon is
577 // allowed, suggest replacement to ':'.
578 if (IsCorrectedToColon) {
579 *IsCorrectedToColon = true;
580 Diag(Loc: IdInfo.CCLoc, DiagID: diag::err_nested_name_spec_is_not_class)
581 << IdInfo.Identifier << getLangOpts().CPlusPlus
582 << FixItHint::CreateReplacement(RemoveRange: IdInfo.CCLoc, Code: ":");
583 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
584 Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
585 return true;
586 }
587 // Replacement '::' -> ':' is not allowed, just issue respective error.
588 Diag(Loc: R.getNameLoc(), DiagID: OnlyNamespace
589 ? unsigned(diag::err_expected_namespace_name)
590 : unsigned(diag::err_expected_class_or_namespace))
591 << IdInfo.Identifier << getLangOpts().CPlusPlus;
592 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
593 Diag(Loc: ND->getLocation(), DiagID: diag::note_entity_declared_at)
594 << IdInfo.Identifier;
595 return true;
596 }
597 }
598
599 if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MSVCCompat) {
600 // We haven't found anything, and we're not recovering from a
601 // different kind of error, so look for typos.
602 DeclarationName Name = Found.getLookupName();
603 Found.clear();
604 NestedNameSpecifierValidatorCCC CCC(*this, /*HasQualifier=*/!SS.isEmpty());
605 if (TypoCorrection Corrected = CorrectTypo(
606 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC,
607 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx, EnteringContext)) {
608 if (LookupCtx) {
609 bool DroppedSpecifier =
610 Corrected.WillReplaceSpecifier() &&
611 Name.getAsString() == Corrected.getAsString(LO: getLangOpts());
612 if (DroppedSpecifier)
613 SS.clear();
614 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
615 << Name << LookupCtx << DroppedSpecifier
616 << SS.getRange());
617 } else
618 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_undeclared_var_use_suggest)
619 << Name);
620
621 if (Corrected.getCorrectionSpecifier())
622 SS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
623 R: SourceRange(Found.getNameLoc()));
624
625 if (NamedDecl *ND = Corrected.getFoundDecl())
626 Found.addDecl(D: ND);
627 Found.setLookupName(Corrected.getCorrection());
628 } else {
629 Found.setLookupName(IdInfo.Identifier);
630 }
631 }
632
633 NamedDecl *SD =
634 Found.isSingleResult() ? Found.getRepresentativeDecl() : nullptr;
635 bool IsExtension = false;
636 bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, IsExtension: &IsExtension);
637 if (!AcceptSpec && IsExtension) {
638 AcceptSpec = true;
639 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::ext_nested_name_spec_is_enum);
640 }
641 if (AcceptSpec) {
642 if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&
643 !getLangOpts().CPlusPlus11) {
644 // C++03 [basic.lookup.classref]p4:
645 // [...] If the name is found in both contexts, the
646 // class-name-or-namespace-name shall refer to the same entity.
647 //
648 // We already found the name in the scope of the object. Now, look
649 // into the current scope (the scope of the postfix-expression) to
650 // see if we can find the same name there. As above, if there is no
651 // scope, reconstruct the result from the template instantiation itself.
652 //
653 // Note that C++11 does *not* perform this redundant lookup.
654 NamedDecl *OuterDecl;
655 if (S) {
656 LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
657 LookupNestedNameSpecifierName);
658 LookupName(R&: FoundOuter, S);
659 OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
660 } else
661 OuterDecl = ScopeLookupResult;
662
663 if (isAcceptableNestedNameSpecifier(SD: OuterDecl) &&
664 OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
665 (!isa<TypeDecl>(Val: OuterDecl) || !isa<TypeDecl>(Val: SD) ||
666 !Context.hasSameType(
667 T1: Context.getCanonicalTypeDeclType(TD: cast<TypeDecl>(Val: OuterDecl)),
668 T2: Context.getCanonicalTypeDeclType(TD: cast<TypeDecl>(Val: SD))))) {
669 if (ErrorRecoveryLookup)
670 return true;
671
672 Diag(Loc: IdInfo.IdentifierLoc,
673 DiagID: diag::err_nested_name_member_ref_lookup_ambiguous)
674 << IdInfo.Identifier;
675 Diag(Loc: SD->getLocation(), DiagID: diag::note_ambig_member_ref_object_type)
676 << ObjectType;
677 Diag(Loc: OuterDecl->getLocation(), DiagID: diag::note_ambig_member_ref_scope);
678
679 // Fall through so that we'll pick the name we found in the object
680 // type, since that's probably what the user wanted anyway.
681 }
682 }
683
684 if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(Val: SD))
685 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
686
687 // If we're just performing this lookup for error-recovery purposes,
688 // don't extend the nested-name-specifier. Just return now.
689 if (ErrorRecoveryLookup)
690 return false;
691
692 // The use of a nested name specifier may trigger deprecation warnings.
693 DiagnoseUseOfDecl(D: SD, Locs: IdInfo.CCLoc);
694
695 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: SD)) {
696 SS.Extend(Context, Namespace, NamespaceLoc: IdInfo.IdentifierLoc, ColonColonLoc: IdInfo.CCLoc);
697 return false;
698 }
699
700 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(Val: SD)) {
701 SS.Extend(Context, Namespace: Alias, NamespaceLoc: IdInfo.IdentifierLoc, ColonColonLoc: IdInfo.CCLoc);
702 return false;
703 }
704
705 const auto *TD = cast<TypeDecl>(Val: SD->getUnderlyingDecl());
706 if (isa<EnumDecl>(Val: TD))
707 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::warn_cxx98_compat_enum_nested_name_spec);
708
709 [[maybe_unused]] bool IsType = ::ExtendNestedNameSpecifier(
710 S&: *this, SS, ND: SD, NameLoc: IdInfo.IdentifierLoc, CCLoc: IdInfo.CCLoc);
711 assert(IsType && "unhandled declaration kind");
712 return false;
713 }
714
715 // Otherwise, we have an error case. If we don't want diagnostics, just
716 // return an error now.
717 if (ErrorRecoveryLookup)
718 return true;
719
720 // If we didn't find anything during our lookup, try again with
721 // ordinary name lookup, which can help us produce better error
722 // messages.
723 if (Found.empty()) {
724 Found.clear(Kind: LookupOrdinaryName);
725 LookupName(R&: Found, S);
726 }
727
728 // In Microsoft mode, if we are within a templated function and we can't
729 // resolve Identifier, then extend the SS with Identifier. This will have
730 // the effect of resolving Identifier during template instantiation.
731 // The goal is to be able to resolve a function call whose
732 // nested-name-specifier is located inside a dependent base class.
733 // Example:
734 //
735 // class C {
736 // public:
737 // static void foo2() { }
738 // };
739 // template <class T> class A { public: typedef C D; };
740 //
741 // template <class T> class B : public A<T> {
742 // public:
743 // void foo() { D::foo2(); }
744 // };
745 if (getLangOpts().MSVCCompat) {
746 DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
747 if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
748 CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(Val: DC->getParent());
749 if (ContainingClass && ContainingClass->hasAnyDependentBases()) {
750 Diag(Loc: IdInfo.IdentifierLoc,
751 DiagID: diag::ext_undeclared_unqual_id_with_dependent_base)
752 << IdInfo.Identifier << ContainingClass;
753
754 TypeLocBuilder TLB;
755
756 // Fake up a nested-name-specifier that starts with the
757 // injected-class-name of the enclosing class.
758 // FIXME: This should be done as part of an adjustment, so that this
759 // doesn't get confused with something written in source.
760 QualType Result =
761 Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
762 TD: ContainingClass, /*OwnsTag=*/false);
763 auto TTL = TLB.push<TagTypeLoc>(T: Result);
764 TTL.setElaboratedKeywordLoc(SourceLocation());
765 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
766 TTL.setNameLoc(IdInfo.IdentifierLoc);
767 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: Result),
768 ColonColonLoc: SourceLocation());
769
770 TLB.clear();
771
772 // Form a DependentNameType.
773 QualType DTN = Context.getDependentNameType(
774 Keyword: ElaboratedTypeKeyword::None, NNS: SS.getScopeRep(), Name: IdInfo.Identifier);
775 auto DTNL = TLB.push<DependentNameTypeLoc>(T: DTN);
776 DTNL.setElaboratedKeywordLoc(SourceLocation());
777 DTNL.setNameLoc(IdInfo.IdentifierLoc);
778 DTNL.setQualifierLoc(SS.getWithLocInContext(Context));
779 SS.clear();
780 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: DTN), ColonColonLoc: IdInfo.CCLoc);
781 return false;
782 }
783 }
784 }
785
786 if (!Found.empty()) {
787 const auto *ND = Found.getAsSingle<NamedDecl>();
788 if (!ND) {
789 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_expected_class_or_namespace)
790 << IdInfo.Identifier << getLangOpts().CPlusPlus;
791 return true;
792 }
793 if (Found.getLookupKind() == LookupNestedNameSpecifierName &&
794 ::ExtendNestedNameSpecifier(S&: *this, SS, ND, NameLoc: IdInfo.IdentifierLoc,
795 CCLoc: IdInfo.CCLoc)) {
796 const Type *T = SS.getScopeRep().getAsType();
797 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_expected_class_or_namespace)
798 << QualType(T, 0) << getLangOpts().CPlusPlus;
799 // Recover with this type if it would be a valid nested name specifier.
800 return !T->getAsCanonical<TagType>();
801 }
802 if (isa<TemplateDecl>(Val: ND)) {
803 ParsedType SuggestedType;
804 DiagnoseUnknownTypeName(II&: IdInfo.Identifier, IILoc: IdInfo.IdentifierLoc, S, SS: &SS,
805 SuggestedType);
806 } else {
807 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_expected_class_or_namespace)
808 << IdInfo.Identifier << getLangOpts().CPlusPlus;
809 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
810 Diag(Loc: ND->getLocation(), DiagID: diag::note_entity_declared_at)
811 << IdInfo.Identifier;
812 }
813 } else if (SS.isSet())
814 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_no_member) << IdInfo.Identifier
815 << LookupCtx << SS.getRange();
816 else
817 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_undeclared_var_use)
818 << IdInfo.Identifier;
819
820 return true;
821}
822
823bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
824 bool EnteringContext, CXXScopeSpec &SS,
825 bool *IsCorrectedToColon,
826 bool OnlyNamespace) {
827 if (SS.isInvalid())
828 return true;
829
830 return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
831 /*ScopeLookupResult=*/nullptr, ErrorRecoveryLookup: false,
832 IsCorrectedToColon, OnlyNamespace);
833}
834
835bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
836 const DeclSpec &DS,
837 SourceLocation ColonColonLoc) {
838 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
839 return true;
840
841 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
842
843 QualType T = BuildDecltypeType(E: DS.getRepAsExpr());
844 if (T.isNull())
845 return true;
846
847 if (!T->isDependentType() && !isa<TagType>(Val: T.getCanonicalType())) {
848 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_expected_class_or_namespace)
849 << T << getLangOpts().CPlusPlus;
850 return true;
851 }
852
853 assert(SS.isEmpty());
854
855 TypeLocBuilder TLB;
856 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
857 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
858 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
859 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T), ColonColonLoc);
860 return false;
861}
862
863bool Sema::ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
864 const DeclSpec &DS,
865 SourceLocation ColonColonLoc,
866 QualType Type) {
867 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
868 return true;
869
870 assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing);
871
872 if (Type.isNull())
873 return true;
874
875 assert(SS.isEmpty());
876
877 TypeLocBuilder TLB;
878 TLB.pushTrivial(Context&: getASTContext(),
879 T: cast<PackIndexingType>(Val: Type.getTypePtr())->getPattern(),
880 Loc: DS.getBeginLoc());
881 PackIndexingTypeLoc PIT = TLB.push<PackIndexingTypeLoc>(T: Type);
882 PIT.setEllipsisLoc(DS.getEllipsisLoc());
883 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: Type), ColonColonLoc);
884 return false;
885}
886
887bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
888 NestedNameSpecInfo &IdInfo,
889 bool EnteringContext) {
890 if (SS.isInvalid())
891 return false;
892
893 return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
894 /*ScopeLookupResult=*/nullptr, ErrorRecoveryLookup: true);
895}
896
897bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
898 CXXScopeSpec &SS,
899 SourceLocation TemplateKWLoc,
900 TemplateTy OpaqueTemplate,
901 SourceLocation TemplateNameLoc,
902 SourceLocation LAngleLoc,
903 ASTTemplateArgsPtr TemplateArgsIn,
904 SourceLocation RAngleLoc,
905 SourceLocation CCLoc,
906 bool EnteringContext) {
907 if (SS.isInvalid())
908 return true;
909
910 // Translate the parser's template argument list in our AST format.
911 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
912 translateTemplateArguments(In: TemplateArgsIn, Out&: TemplateArgs);
913
914 // We were able to resolve the template name to an actual template.
915 // Build an appropriate nested-name-specifier.
916 QualType T = CheckTemplateIdType(
917 Keyword: ElaboratedTypeKeyword::None, Template: OpaqueTemplate.get(), TemplateLoc: TemplateNameLoc,
918 TemplateArgs, /*Scope=*/S, /*ForNestedNameSpecifier=*/true);
919 if (T.isNull())
920 return true;
921
922 // Alias template specializations can produce types which are not valid
923 // nested name specifiers.
924 if (!T->isDependentType() && !isa<TagType>(Val: T.getCanonicalType())) {
925 Diag(Loc: TemplateNameLoc, DiagID: diag::err_nested_name_spec_non_tag) << T;
926 NoteAllFoundTemplates(Name: OpaqueTemplate.get());
927 return true;
928 }
929
930 // Provide source-location information for the template specialization type.
931 TypeLocBuilder TLB;
932 TLB.push<TemplateSpecializationTypeLoc>(T).set(
933 /*ElaboratedKeywordLoc=*/SourceLocation(),
934 QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateNameLoc,
935 TAL: TemplateArgs);
936
937 SS.clear();
938 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T), ColonColonLoc: CCLoc);
939 return false;
940}
941
942namespace {
943 /// A structure that stores a nested-name-specifier annotation,
944 /// including both the nested-name-specifier
945 struct NestedNameSpecifierAnnotation {
946 NestedNameSpecifier NNS = std::nullopt;
947 };
948}
949
950void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
951 if (SS.isEmpty() || SS.isInvalid())
952 return nullptr;
953
954 void *Mem = Context.Allocate(
955 Size: (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
956 Align: alignof(NestedNameSpecifierAnnotation));
957 NestedNameSpecifierAnnotation *Annotation
958 = new (Mem) NestedNameSpecifierAnnotation;
959 Annotation->NNS = SS.getScopeRep();
960 memcpy(dest: Annotation + 1, src: SS.location_data(), n: SS.location_size());
961 return Annotation;
962}
963
964void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
965 SourceRange AnnotationRange,
966 CXXScopeSpec &SS) {
967 if (!AnnotationPtr) {
968 SS.SetInvalid(AnnotationRange);
969 return;
970 }
971
972 NestedNameSpecifierAnnotation *Annotation
973 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
974 SS.Adopt(Other: NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
975}
976
977bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
978 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
979
980 // Don't enter a declarator context when the current context is an Objective-C
981 // declaration.
982 if (isa<ObjCContainerDecl>(Val: CurContext) || isa<ObjCMethodDecl>(Val: CurContext))
983 return false;
984
985 // There are only two places a well-formed program may qualify a
986 // declarator: first, when defining a namespace or class member
987 // out-of-line, and second, when naming an explicitly-qualified
988 // friend function. The latter case is governed by
989 // C++03 [basic.lookup.unqual]p10:
990 // In a friend declaration naming a member function, a name used
991 // in the function declarator and not part of a template-argument
992 // in a template-id is first looked up in the scope of the member
993 // function's class. If it is not found, or if the name is part of
994 // a template-argument in a template-id, the look up is as
995 // described for unqualified names in the definition of the class
996 // granting friendship.
997 // i.e. we don't push a scope unless it's a class member.
998
999 switch (SS.getScopeRep().getKind()) {
1000 case NestedNameSpecifier::Kind::Global:
1001 case NestedNameSpecifier::Kind::Namespace:
1002 // These are always namespace scopes. We never want to enter a
1003 // namespace scope from anything but a file context.
1004 return CurContext->getRedeclContext()->isFileContext();
1005
1006 case NestedNameSpecifier::Kind::Type:
1007 case NestedNameSpecifier::Kind::MicrosoftSuper:
1008 // These are never namespace scopes.
1009 return true;
1010
1011 case NestedNameSpecifier::Kind::Null:
1012 llvm_unreachable("unexpected null nested name specifier");
1013 }
1014
1015 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1016}
1017
1018bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
1019 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1020
1021 if (SS.isInvalid()) return true;
1022
1023 DeclContext *DC = computeDeclContext(SS, EnteringContext: true);
1024 if (!DC) return true;
1025
1026 // Before we enter a declarator's context, we need to make sure that
1027 // it is a complete declaration context.
1028 if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
1029 return true;
1030
1031 EnterDeclaratorContext(S, DC);
1032
1033 // Rebuild the nested name specifier for the new scope.
1034 if (DC->isDependentContext())
1035 RebuildNestedNameSpecifierInCurrentInstantiation(SS);
1036
1037 return false;
1038}
1039
1040void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1041 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1042 if (SS.isInvalid())
1043 return;
1044 assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
1045 "exiting declarator scope we never really entered");
1046 ExitDeclaratorContext(S);
1047}
1048