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