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