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)
385 : SRef(SRef) {}
386
387 bool ValidateCandidate(const TypoCorrection &candidate) override {
388 return SRef.isAcceptableNestedNameSpecifier(SD: candidate.getCorrectionDecl());
389 }
390
391 std::unique_ptr<CorrectionCandidateCallback> clone() override {
392 return std::make_unique<NestedNameSpecifierValidatorCCC>(args&: *this);
393 }
394
395 private:
396 Sema &SRef;
397};
398
399}
400
401[[nodiscard]] static bool ExtendNestedNameSpecifier(Sema &S, CXXScopeSpec &SS,
402 const NamedDecl *ND,
403 SourceLocation NameLoc,
404 SourceLocation CCLoc) {
405 TypeLocBuilder TLB;
406 QualType T;
407 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: ND)) {
408 T = S.Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
409 D: USD);
410 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
411 QualifierLoc: SS.getWithLocInContext(Context&: S.Context), NameLoc);
412 } else if (const auto *TD = dyn_cast<TypeDecl>(Val: ND)) {
413 T = S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
414 Decl: TD);
415 switch (T->getTypeClass()) {
416 case Type::Record:
417 case Type::InjectedClassName:
418 case Type::Enum: {
419 auto TTL = TLB.push<TagTypeLoc>(T);
420 TTL.setElaboratedKeywordLoc(SourceLocation());
421 TTL.setQualifierLoc(SS.getWithLocInContext(Context&: S.Context));
422 TTL.setNameLoc(NameLoc);
423 break;
424 }
425 case Type::Typedef:
426 TLB.push<TypedefTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
427 QualifierLoc: SS.getWithLocInContext(Context&: S.Context),
428 NameLoc);
429 break;
430 case Type::UnresolvedUsing:
431 TLB.push<UnresolvedUsingTypeLoc>(T).set(
432 /*ElaboratedKeywordLoc=*/SourceLocation(),
433 QualifierLoc: SS.getWithLocInContext(Context&: S.Context), NameLoc);
434 break;
435 default:
436 assert(SS.isEmpty());
437 T = S.Context.getTypeDeclType(Decl: TD);
438 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
439 break;
440 }
441 } else {
442 return false;
443 }
444 SS.clear();
445 SS.Make(Context&: S.Context, TL: TLB.getTypeLocInContext(Context&: S.Context, T), ColonColonLoc: CCLoc);
446 return true;
447}
448
449bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
450 bool EnteringContext, CXXScopeSpec &SS,
451 NamedDecl *ScopeLookupResult,
452 bool ErrorRecoveryLookup,
453 bool *IsCorrectedToColon,
454 bool OnlyNamespace) {
455 if (IdInfo.Identifier->isEditorPlaceholder())
456 return true;
457 LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
458 OnlyNamespace ? LookupNamespaceName
459 : LookupNestedNameSpecifierName);
460 QualType ObjectType = GetTypeFromParser(Ty: IdInfo.ObjectType);
461
462 // Determine where to perform name lookup
463 DeclContext *LookupCtx = nullptr;
464 bool isDependent = false;
465 if (IsCorrectedToColon)
466 *IsCorrectedToColon = false;
467 if (!ObjectType.isNull()) {
468 // This nested-name-specifier occurs in a member access expression, e.g.,
469 // x->B::f, and we are looking into the type of the object.
470 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
471 LookupCtx = computeDeclContext(T: ObjectType);
472 isDependent = ObjectType->isDependentType();
473 } else if (SS.isSet()) {
474 // This nested-name-specifier occurs after another nested-name-specifier,
475 // so look into the context associated with the prior nested-name-specifier.
476 LookupCtx = computeDeclContext(SS, EnteringContext);
477 isDependent = isDependentScopeSpecifier(SS);
478 Found.setContextRange(SS.getRange());
479 }
480
481 bool ObjectTypeSearchedInScope = false;
482 if (LookupCtx) {
483 // Perform "qualified" name lookup into the declaration context we
484 // computed, which is either the type of the base of a member access
485 // expression or the declaration context associated with a prior
486 // nested-name-specifier.
487
488 // The declaration context must be complete.
489 if (!LookupCtx->isDependentContext() &&
490 RequireCompleteDeclContext(SS, DC: LookupCtx))
491 return true;
492
493 LookupQualifiedName(R&: Found, LookupCtx);
494
495 if (!ObjectType.isNull() && Found.empty()) {
496 // C++ [basic.lookup.classref]p4:
497 // If the id-expression in a class member access is a qualified-id of
498 // the form
499 //
500 // class-name-or-namespace-name::...
501 //
502 // the class-name-or-namespace-name following the . or -> operator is
503 // looked up both in the context of the entire postfix-expression and in
504 // the scope of the class of the object expression. If the name is found
505 // only in the scope of the class of the object expression, the name
506 // shall refer to a class-name. If the name is found only in the
507 // context of the entire postfix-expression, the name shall refer to a
508 // class-name or namespace-name. [...]
509 //
510 // Qualified name lookup into a class will not find a namespace-name,
511 // so we do not need to diagnose that case specifically. However,
512 // this qualified name lookup may find nothing. In that case, perform
513 // unqualified name lookup in the given scope (if available) or
514 // reconstruct the result from when name lookup was performed at template
515 // definition time.
516 if (S)
517 LookupName(R&: Found, S);
518 else if (ScopeLookupResult)
519 Found.addDecl(D: ScopeLookupResult);
520
521 ObjectTypeSearchedInScope = true;
522 }
523 } else if (!isDependent) {
524 // Perform unqualified name lookup in the current scope.
525 LookupName(R&: Found, S);
526 }
527
528 if (Found.isAmbiguous())
529 return true;
530
531 // If we performed lookup into a dependent context and did not find anything,
532 // that's fine: just build a dependent nested-name-specifier.
533 if (Found.empty() && isDependent &&
534 !(LookupCtx && LookupCtx->isRecord() &&
535 (!cast<CXXRecordDecl>(Val: LookupCtx)->hasDefinition() ||
536 !cast<CXXRecordDecl>(Val: LookupCtx)->hasAnyDependentBases()))) {
537 // Don't speculate if we're just trying to improve error recovery.
538 if (ErrorRecoveryLookup)
539 return true;
540
541 // We were not able to compute the declaration context for a dependent
542 // base object type or prior nested-name-specifier, so this
543 // nested-name-specifier refers to an unknown specialization. Just build
544 // a dependent nested-name-specifier.
545
546 TypeLocBuilder TLB;
547
548 QualType DTN = Context.getDependentNameType(
549 Keyword: ElaboratedTypeKeyword::None, NNS: SS.getScopeRep(), Name: IdInfo.Identifier);
550 auto DTNL = TLB.push<DependentNameTypeLoc>(T: DTN);
551 DTNL.setElaboratedKeywordLoc(SourceLocation());
552 DTNL.setNameLoc(IdInfo.IdentifierLoc);
553 DTNL.setQualifierLoc(SS.getWithLocInContext(Context));
554
555 SS.clear();
556 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: DTN), ColonColonLoc: IdInfo.CCLoc);
557 return false;
558 }
559
560 if (Found.empty() && !ErrorRecoveryLookup) {
561 // If identifier is not found as class-name-or-namespace-name, but is found
562 // as other entity, don't look for typos.
563 LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
564 if (LookupCtx)
565 LookupQualifiedName(R, LookupCtx);
566 else if (S && !isDependent)
567 LookupName(R, S);
568 if (!R.empty()) {
569 // Don't diagnose problems with this speculative lookup.
570 R.suppressDiagnostics();
571 // The identifier is found in ordinary lookup. If correction to colon is
572 // allowed, suggest replacement to ':'.
573 if (IsCorrectedToColon) {
574 *IsCorrectedToColon = true;
575 Diag(Loc: IdInfo.CCLoc, DiagID: diag::err_nested_name_spec_is_not_class)
576 << IdInfo.Identifier << getLangOpts().CPlusPlus
577 << FixItHint::CreateReplacement(RemoveRange: IdInfo.CCLoc, Code: ":");
578 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
579 Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
580 return true;
581 }
582 // Replacement '::' -> ':' is not allowed, just issue respective error.
583 Diag(Loc: R.getNameLoc(), DiagID: OnlyNamespace
584 ? unsigned(diag::err_expected_namespace_name)
585 : unsigned(diag::err_expected_class_or_namespace))
586 << IdInfo.Identifier << getLangOpts().CPlusPlus;
587 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
588 Diag(Loc: ND->getLocation(), DiagID: diag::note_entity_declared_at)
589 << IdInfo.Identifier;
590 return true;
591 }
592 }
593
594 if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MSVCCompat) {
595 // We haven't found anything, and we're not recovering from a
596 // different kind of error, so look for typos.
597 DeclarationName Name = Found.getLookupName();
598 Found.clear();
599 NestedNameSpecifierValidatorCCC CCC(*this);
600 if (TypoCorrection Corrected = CorrectTypo(
601 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC,
602 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx, EnteringContext)) {
603 if (LookupCtx) {
604 bool DroppedSpecifier =
605 Corrected.WillReplaceSpecifier() &&
606 Name.getAsString() == Corrected.getAsString(LO: getLangOpts());
607 if (DroppedSpecifier)
608 SS.clear();
609 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
610 << Name << LookupCtx << DroppedSpecifier
611 << SS.getRange());
612 } else
613 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_undeclared_var_use_suggest)
614 << Name);
615
616 if (Corrected.getCorrectionSpecifier())
617 SS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
618 R: SourceRange(Found.getNameLoc()));
619
620 if (NamedDecl *ND = Corrected.getFoundDecl())
621 Found.addDecl(D: ND);
622 Found.setLookupName(Corrected.getCorrection());
623 } else {
624 Found.setLookupName(IdInfo.Identifier);
625 }
626 }
627
628 NamedDecl *SD =
629 Found.isSingleResult() ? Found.getRepresentativeDecl() : nullptr;
630 bool IsExtension = false;
631 bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, IsExtension: &IsExtension);
632 if (!AcceptSpec && IsExtension) {
633 AcceptSpec = true;
634 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::ext_nested_name_spec_is_enum);
635 }
636 if (AcceptSpec) {
637 if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&
638 !getLangOpts().CPlusPlus11) {
639 // C++03 [basic.lookup.classref]p4:
640 // [...] If the name is found in both contexts, the
641 // class-name-or-namespace-name shall refer to the same entity.
642 //
643 // We already found the name in the scope of the object. Now, look
644 // into the current scope (the scope of the postfix-expression) to
645 // see if we can find the same name there. As above, if there is no
646 // scope, reconstruct the result from the template instantiation itself.
647 //
648 // Note that C++11 does *not* perform this redundant lookup.
649 NamedDecl *OuterDecl;
650 if (S) {
651 LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
652 LookupNestedNameSpecifierName);
653 LookupName(R&: FoundOuter, S);
654 OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
655 } else
656 OuterDecl = ScopeLookupResult;
657
658 if (isAcceptableNestedNameSpecifier(SD: OuterDecl) &&
659 OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
660 (!isa<TypeDecl>(Val: OuterDecl) || !isa<TypeDecl>(Val: SD) ||
661 !Context.hasSameType(
662 T1: Context.getCanonicalTypeDeclType(TD: cast<TypeDecl>(Val: OuterDecl)),
663 T2: Context.getCanonicalTypeDeclType(TD: cast<TypeDecl>(Val: SD))))) {
664 if (ErrorRecoveryLookup)
665 return true;
666
667 Diag(Loc: IdInfo.IdentifierLoc,
668 DiagID: diag::err_nested_name_member_ref_lookup_ambiguous)
669 << IdInfo.Identifier;
670 Diag(Loc: SD->getLocation(), DiagID: diag::note_ambig_member_ref_object_type)
671 << ObjectType;
672 Diag(Loc: OuterDecl->getLocation(), DiagID: diag::note_ambig_member_ref_scope);
673
674 // Fall through so that we'll pick the name we found in the object
675 // type, since that's probably what the user wanted anyway.
676 }
677 }
678
679 if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(Val: SD))
680 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
681
682 // If we're just performing this lookup for error-recovery purposes,
683 // don't extend the nested-name-specifier. Just return now.
684 if (ErrorRecoveryLookup)
685 return false;
686
687 // The use of a nested name specifier may trigger deprecation warnings.
688 DiagnoseUseOfDecl(D: SD, Locs: IdInfo.CCLoc);
689
690 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: SD)) {
691 SS.Extend(Context, Namespace, NamespaceLoc: IdInfo.IdentifierLoc, ColonColonLoc: IdInfo.CCLoc);
692 return false;
693 }
694
695 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(Val: SD)) {
696 SS.Extend(Context, Namespace: Alias, NamespaceLoc: IdInfo.IdentifierLoc, ColonColonLoc: IdInfo.CCLoc);
697 return false;
698 }
699
700 const auto *TD = cast<TypeDecl>(Val: SD->getUnderlyingDecl());
701 if (isa<EnumDecl>(Val: TD))
702 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::warn_cxx98_compat_enum_nested_name_spec);
703
704 [[maybe_unused]] bool IsType = ::ExtendNestedNameSpecifier(
705 S&: *this, SS, ND: SD, NameLoc: IdInfo.IdentifierLoc, CCLoc: IdInfo.CCLoc);
706 assert(IsType && "unhandled declaration kind");
707 return false;
708 }
709
710 // Otherwise, we have an error case. If we don't want diagnostics, just
711 // return an error now.
712 if (ErrorRecoveryLookup)
713 return true;
714
715 // If we didn't find anything during our lookup, try again with
716 // ordinary name lookup, which can help us produce better error
717 // messages.
718 if (Found.empty()) {
719 Found.clear(Kind: LookupOrdinaryName);
720 LookupName(R&: Found, S);
721 }
722
723 // In Microsoft mode, if we are within a templated function and we can't
724 // resolve Identifier, then extend the SS with Identifier. This will have
725 // the effect of resolving Identifier during template instantiation.
726 // The goal is to be able to resolve a function call whose
727 // nested-name-specifier is located inside a dependent base class.
728 // Example:
729 //
730 // class C {
731 // public:
732 // static void foo2() { }
733 // };
734 // template <class T> class A { public: typedef C D; };
735 //
736 // template <class T> class B : public A<T> {
737 // public:
738 // void foo() { D::foo2(); }
739 // };
740 if (getLangOpts().MSVCCompat) {
741 DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
742 if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
743 CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(Val: DC->getParent());
744 if (ContainingClass && ContainingClass->hasAnyDependentBases()) {
745 Diag(Loc: IdInfo.IdentifierLoc,
746 DiagID: diag::ext_undeclared_unqual_id_with_dependent_base)
747 << IdInfo.Identifier << ContainingClass;
748
749 TypeLocBuilder TLB;
750
751 // Fake up a nested-name-specifier that starts with the
752 // injected-class-name of the enclosing class.
753 // FIXME: This should be done as part of an adjustment, so that this
754 // doesn't get confused with something written in source.
755 QualType Result =
756 Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
757 TD: ContainingClass, /*OwnsTag=*/false);
758 auto TTL = TLB.push<TagTypeLoc>(T: Result);
759 TTL.setElaboratedKeywordLoc(SourceLocation());
760 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
761 TTL.setNameLoc(IdInfo.IdentifierLoc);
762 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: Result),
763 ColonColonLoc: SourceLocation());
764
765 TLB.clear();
766
767 // Form a DependentNameType.
768 QualType DTN = Context.getDependentNameType(
769 Keyword: ElaboratedTypeKeyword::None, NNS: SS.getScopeRep(), Name: IdInfo.Identifier);
770 auto DTNL = TLB.push<DependentNameTypeLoc>(T: DTN);
771 DTNL.setElaboratedKeywordLoc(SourceLocation());
772 DTNL.setNameLoc(IdInfo.IdentifierLoc);
773 DTNL.setQualifierLoc(SS.getWithLocInContext(Context));
774 SS.clear();
775 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: DTN), ColonColonLoc: IdInfo.CCLoc);
776 return false;
777 }
778 }
779 }
780
781 if (!Found.empty()) {
782 const auto *ND = Found.getAsSingle<NamedDecl>();
783 if (!ND) {
784 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_expected_class_or_namespace)
785 << IdInfo.Identifier << getLangOpts().CPlusPlus;
786 return true;
787 }
788 if (::ExtendNestedNameSpecifier(S&: *this, SS, ND, NameLoc: IdInfo.IdentifierLoc,
789 CCLoc: IdInfo.CCLoc)) {
790 const Type *T = SS.getScopeRep().getAsType();
791 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_expected_class_or_namespace)
792 << QualType(T, 0) << getLangOpts().CPlusPlus;
793 // Recover with this type if it would be a valid nested name specifier.
794 return !T->getAsCanonical<TagType>();
795 }
796 if (isa<TemplateDecl>(Val: ND)) {
797 ParsedType SuggestedType;
798 DiagnoseUnknownTypeName(II&: IdInfo.Identifier, IILoc: IdInfo.IdentifierLoc, S, SS: &SS,
799 SuggestedType);
800 } else {
801 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_expected_class_or_namespace)
802 << IdInfo.Identifier << getLangOpts().CPlusPlus;
803 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
804 Diag(Loc: ND->getLocation(), DiagID: diag::note_entity_declared_at)
805 << IdInfo.Identifier;
806 }
807 } else if (SS.isSet())
808 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_no_member) << IdInfo.Identifier
809 << LookupCtx << SS.getRange();
810 else
811 Diag(Loc: IdInfo.IdentifierLoc, DiagID: diag::err_undeclared_var_use)
812 << IdInfo.Identifier;
813
814 return true;
815}
816
817bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
818 bool EnteringContext, CXXScopeSpec &SS,
819 bool *IsCorrectedToColon,
820 bool OnlyNamespace) {
821 if (SS.isInvalid())
822 return true;
823
824 return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
825 /*ScopeLookupResult=*/nullptr, ErrorRecoveryLookup: false,
826 IsCorrectedToColon, OnlyNamespace);
827}
828
829bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
830 const DeclSpec &DS,
831 SourceLocation ColonColonLoc) {
832 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
833 return true;
834
835 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
836
837 QualType T = BuildDecltypeType(E: DS.getRepAsExpr());
838 if (T.isNull())
839 return true;
840
841 if (!T->isDependentType() && !isa<TagType>(Val: T.getCanonicalType())) {
842 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_expected_class_or_namespace)
843 << T << getLangOpts().CPlusPlus;
844 return true;
845 }
846
847 assert(SS.isEmpty());
848
849 TypeLocBuilder TLB;
850 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
851 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
852 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
853 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T), ColonColonLoc);
854 return false;
855}
856
857bool Sema::ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
858 const DeclSpec &DS,
859 SourceLocation ColonColonLoc,
860 QualType Type) {
861 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
862 return true;
863
864 assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing);
865
866 if (Type.isNull())
867 return true;
868
869 assert(SS.isEmpty());
870
871 TypeLocBuilder TLB;
872 TLB.pushTrivial(Context&: getASTContext(),
873 T: cast<PackIndexingType>(Val: Type.getTypePtr())->getPattern(),
874 Loc: DS.getBeginLoc());
875 PackIndexingTypeLoc PIT = TLB.push<PackIndexingTypeLoc>(T: Type);
876 PIT.setEllipsisLoc(DS.getEllipsisLoc());
877 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T: Type), ColonColonLoc);
878 return false;
879}
880
881bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
882 NestedNameSpecInfo &IdInfo,
883 bool EnteringContext) {
884 if (SS.isInvalid())
885 return false;
886
887 return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
888 /*ScopeLookupResult=*/nullptr, ErrorRecoveryLookup: true);
889}
890
891bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
892 CXXScopeSpec &SS,
893 SourceLocation TemplateKWLoc,
894 TemplateTy OpaqueTemplate,
895 SourceLocation TemplateNameLoc,
896 SourceLocation LAngleLoc,
897 ASTTemplateArgsPtr TemplateArgsIn,
898 SourceLocation RAngleLoc,
899 SourceLocation CCLoc,
900 bool EnteringContext) {
901 if (SS.isInvalid())
902 return true;
903
904 // Translate the parser's template argument list in our AST format.
905 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
906 translateTemplateArguments(In: TemplateArgsIn, Out&: TemplateArgs);
907
908 // We were able to resolve the template name to an actual template.
909 // Build an appropriate nested-name-specifier.
910 QualType T = CheckTemplateIdType(
911 Keyword: ElaboratedTypeKeyword::None, Template: OpaqueTemplate.get(), TemplateLoc: TemplateNameLoc,
912 TemplateArgs, /*Scope=*/S, /*ForNestedNameSpecifier=*/true);
913 if (T.isNull())
914 return true;
915
916 // Alias template specializations can produce types which are not valid
917 // nested name specifiers.
918 if (!T->isDependentType() && !isa<TagType>(Val: T.getCanonicalType())) {
919 Diag(Loc: TemplateNameLoc, DiagID: diag::err_nested_name_spec_non_tag) << T;
920 NoteAllFoundTemplates(Name: OpaqueTemplate.get());
921 return true;
922 }
923
924 // Provide source-location information for the template specialization type.
925 TypeLocBuilder TLB;
926 TLB.push<TemplateSpecializationTypeLoc>(T).set(
927 /*ElaboratedKeywordLoc=*/SourceLocation(),
928 QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateNameLoc,
929 TAL: TemplateArgs);
930
931 SS.clear();
932 SS.Make(Context, TL: TLB.getTypeLocInContext(Context, T), ColonColonLoc: CCLoc);
933 return false;
934}
935
936namespace {
937 /// A structure that stores a nested-name-specifier annotation,
938 /// including both the nested-name-specifier
939 struct NestedNameSpecifierAnnotation {
940 NestedNameSpecifier NNS = std::nullopt;
941 };
942}
943
944void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
945 if (SS.isEmpty() || SS.isInvalid())
946 return nullptr;
947
948 void *Mem = Context.Allocate(
949 Size: (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
950 Align: alignof(NestedNameSpecifierAnnotation));
951 NestedNameSpecifierAnnotation *Annotation
952 = new (Mem) NestedNameSpecifierAnnotation;
953 Annotation->NNS = SS.getScopeRep();
954 memcpy(dest: Annotation + 1, src: SS.location_data(), n: SS.location_size());
955 return Annotation;
956}
957
958void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
959 SourceRange AnnotationRange,
960 CXXScopeSpec &SS) {
961 if (!AnnotationPtr) {
962 SS.SetInvalid(AnnotationRange);
963 return;
964 }
965
966 NestedNameSpecifierAnnotation *Annotation
967 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
968 SS.Adopt(Other: NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
969}
970
971bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
972 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
973
974 // Don't enter a declarator context when the current context is an Objective-C
975 // declaration.
976 if (isa<ObjCContainerDecl>(Val: CurContext) || isa<ObjCMethodDecl>(Val: CurContext))
977 return false;
978
979 // There are only two places a well-formed program may qualify a
980 // declarator: first, when defining a namespace or class member
981 // out-of-line, and second, when naming an explicitly-qualified
982 // friend function. The latter case is governed by
983 // C++03 [basic.lookup.unqual]p10:
984 // In a friend declaration naming a member function, a name used
985 // in the function declarator and not part of a template-argument
986 // in a template-id is first looked up in the scope of the member
987 // function's class. If it is not found, or if the name is part of
988 // a template-argument in a template-id, the look up is as
989 // described for unqualified names in the definition of the class
990 // granting friendship.
991 // i.e. we don't push a scope unless it's a class member.
992
993 switch (SS.getScopeRep().getKind()) {
994 case NestedNameSpecifier::Kind::Global:
995 case NestedNameSpecifier::Kind::Namespace:
996 // These are always namespace scopes. We never want to enter a
997 // namespace scope from anything but a file context.
998 return CurContext->getRedeclContext()->isFileContext();
999
1000 case NestedNameSpecifier::Kind::Type:
1001 case NestedNameSpecifier::Kind::MicrosoftSuper:
1002 // These are never namespace scopes.
1003 return true;
1004
1005 case NestedNameSpecifier::Kind::Null:
1006 llvm_unreachable("unexpected null nested name specifier");
1007 }
1008
1009 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1010}
1011
1012bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
1013 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1014
1015 if (SS.isInvalid()) return true;
1016
1017 DeclContext *DC = computeDeclContext(SS, EnteringContext: true);
1018 if (!DC) return true;
1019
1020 // Before we enter a declarator's context, we need to make sure that
1021 // it is a complete declaration context.
1022 if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
1023 return true;
1024
1025 EnterDeclaratorContext(S, DC);
1026
1027 // Rebuild the nested name specifier for the new scope.
1028 if (DC->isDependentContext())
1029 RebuildNestedNameSpecifierInCurrentInstantiation(SS);
1030
1031 return false;
1032}
1033
1034void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1035 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1036 if (SS.isInvalid())
1037 return;
1038 assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
1039 "exiting declarator scope we never really entered");
1040 ExitDeclaratorContext(S);
1041}
1042