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