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 SourceLocation IdLoc, 384 IdentifierInfo &II, 385 ParsedType ObjectTypePtr) { 386 QualType ObjectType = GetTypeFromParser(ObjectTypePtr); 387 LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName); 388 389 // Determine where to perform name lookup 390 DeclContext *LookupCtx = nullptr; 391 bool isDependent = false; 392 if (!ObjectType.isNull()) { 393 // This nested-name-specifier occurs in a member access expression, e.g., 394 // x->B::f, and we are looking into the type of the object. 395 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 396 LookupCtx = computeDeclContext(ObjectType); 397 isDependent = ObjectType->isDependentType(); 398 } else if (SS.isSet()) { 399 // This nested-name-specifier occurs after another nested-name-specifier, 400 // so long into the context associated with the prior nested-name-specifier. 401 LookupCtx = computeDeclContext(SS, false); 402 isDependent = isDependentScopeSpecifier(SS); 403 Found.setContextRange(SS.getRange()); 404 } 405 406 if (LookupCtx) { 407 // Perform "qualified" name lookup into the declaration context we 408 // computed, which is either the type of the base of a member access 409 // expression or the declaration context associated with a prior 410 // nested-name-specifier. 411 412 // The declaration context must be complete. 413 if (!LookupCtx->isDependentContext() && 414 RequireCompleteDeclContext(SS, LookupCtx)) 415 return false; 416 417 LookupQualifiedName(Found, LookupCtx); 418 } else if (isDependent) { 419 return false; 420 } else { 421 LookupName(Found, S); 422 } 423 Found.suppressDiagnostics(); 424 425 return Found.getAsSingle<NamespaceDecl>(); 426 } 427 428 namespace { 429 430 // Callback to only accept typo corrections that can be a valid C++ member 431 // intializer: either a non-static field member or a base class. 432 class NestedNameSpecifierValidatorCCC : public CorrectionCandidateCallback { 433 public: 434 explicit NestedNameSpecifierValidatorCCC(Sema &SRef) 435 : SRef(SRef) {} 436 437 bool ValidateCandidate(const TypoCorrection &candidate) override { 438 return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl()); 439 } 440 441 private: 442 Sema &SRef; 443 }; 444 445 } 446 447 /// \brief Build a new nested-name-specifier for "identifier::", as described 448 /// by ActOnCXXNestedNameSpecifier. 449 /// 450 /// \param S Scope in which the nested-name-specifier occurs. 451 /// \param Identifier Identifier in the sequence "identifier" "::". 452 /// \param IdentifierLoc Location of the \p Identifier. 453 /// \param CCLoc Location of "::" following Identifier. 454 /// \param ObjectType Type of postfix expression if the nested-name-specifier 455 /// occurs in construct like: <tt>ptr->nns::f</tt>. 456 /// \param EnteringContext If true, enter the context specified by the 457 /// nested-name-specifier. 458 /// \param SS Optional nested name specifier preceding the identifier. 459 /// \param ScopeLookupResult Provides the result of name lookup within the 460 /// scope of the nested-name-specifier that was computed at template 461 /// definition time. 462 /// \param ErrorRecoveryLookup Specifies if the method is called to improve 463 /// error recovery and what kind of recovery is performed. 464 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':' 465 /// are allowed. The bool value pointed by this parameter is set to 466 /// 'true' if the identifier is treated as if it was followed by ':', 467 /// not '::'. 468 /// 469 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in 470 /// that it contains an extra parameter \p ScopeLookupResult, which provides 471 /// the result of name lookup within the scope of the nested-name-specifier 472 /// that was computed at template definition time. 473 /// 474 /// If ErrorRecoveryLookup is true, then this call is used to improve error 475 /// recovery. This means that it should not emit diagnostics, it should 476 /// just return true on failure. It also means it should only return a valid 477 /// scope if it *knows* that the result is correct. It should not return in a 478 /// dependent context, for example. Nor will it extend \p SS with the scope 479 /// specifier. 480 bool Sema::BuildCXXNestedNameSpecifier(Scope *S, 481 IdentifierInfo &Identifier, 482 SourceLocation IdentifierLoc, 483 SourceLocation CCLoc, 484 QualType ObjectType, 485 bool EnteringContext, 486 CXXScopeSpec &SS, 487 NamedDecl *ScopeLookupResult, 488 bool ErrorRecoveryLookup, 489 bool *IsCorrectedToColon) { 490 LookupResult Found(*this, &Identifier, IdentifierLoc, 491 LookupNestedNameSpecifierName); 492 493 // Determine where to perform name lookup 494 DeclContext *LookupCtx = nullptr; 495 bool isDependent = false; 496 if (IsCorrectedToColon) 497 *IsCorrectedToColon = false; 498 if (!ObjectType.isNull()) { 499 // This nested-name-specifier occurs in a member access expression, e.g., 500 // x->B::f, and we are looking into the type of the object. 501 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 502 LookupCtx = computeDeclContext(ObjectType); 503 isDependent = ObjectType->isDependentType(); 504 } else if (SS.isSet()) { 505 // This nested-name-specifier occurs after another nested-name-specifier, 506 // so look into the context associated with the prior nested-name-specifier. 507 LookupCtx = computeDeclContext(SS, EnteringContext); 508 isDependent = isDependentScopeSpecifier(SS); 509 Found.setContextRange(SS.getRange()); 510 } 511 512 bool ObjectTypeSearchedInScope = false; 513 if (LookupCtx) { 514 // Perform "qualified" name lookup into the declaration context we 515 // computed, which is either the type of the base of a member access 516 // expression or the declaration context associated with a prior 517 // nested-name-specifier. 518 519 // The declaration context must be complete. 520 if (!LookupCtx->isDependentContext() && 521 RequireCompleteDeclContext(SS, LookupCtx)) 522 return true; 523 524 LookupQualifiedName(Found, LookupCtx); 525 526 if (!ObjectType.isNull() && Found.empty()) { 527 // C++ [basic.lookup.classref]p4: 528 // If the id-expression in a class member access is a qualified-id of 529 // the form 530 // 531 // class-name-or-namespace-name::... 532 // 533 // the class-name-or-namespace-name following the . or -> operator is 534 // looked up both in the context of the entire postfix-expression and in 535 // the scope of the class of the object expression. If the name is found 536 // only in the scope of the class of the object expression, the name 537 // shall refer to a class-name. If the name is found only in the 538 // context of the entire postfix-expression, the name shall refer to a 539 // class-name or namespace-name. [...] 540 // 541 // Qualified name lookup into a class will not find a namespace-name, 542 // so we do not need to diagnose that case specifically. However, 543 // this qualified name lookup may find nothing. In that case, perform 544 // unqualified name lookup in the given scope (if available) or 545 // reconstruct the result from when name lookup was performed at template 546 // definition time. 547 if (S) 548 LookupName(Found, S); 549 else if (ScopeLookupResult) 550 Found.addDecl(ScopeLookupResult); 551 552 ObjectTypeSearchedInScope = true; 553 } 554 } else if (!isDependent) { 555 // Perform unqualified name lookup in the current scope. 556 LookupName(Found, S); 557 } 558 559 if (Found.isAmbiguous()) 560 return true; 561 562 // If we performed lookup into a dependent context and did not find anything, 563 // that's fine: just build a dependent nested-name-specifier. 564 if (Found.empty() && isDependent && 565 !(LookupCtx && LookupCtx->isRecord() && 566 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() || 567 !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) { 568 // Don't speculate if we're just trying to improve error recovery. 569 if (ErrorRecoveryLookup) 570 return true; 571 572 // We were not able to compute the declaration context for a dependent 573 // base object type or prior nested-name-specifier, so this 574 // nested-name-specifier refers to an unknown specialization. Just build 575 // a dependent nested-name-specifier. 576 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc); 577 return false; 578 } 579 580 if (Found.empty() && !ErrorRecoveryLookup) { 581 // If identifier is not found as class-name-or-namespace-name, but is found 582 // as other entity, don't look for typos. 583 LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName); 584 if (LookupCtx) 585 LookupQualifiedName(R, LookupCtx); 586 else if (S && !isDependent) 587 LookupName(R, S); 588 if (!R.empty()) { 589 // Don't diagnose problems with this speculative lookup. 590 R.suppressDiagnostics(); 591 // The identifier is found in ordinary lookup. If correction to colon is 592 // allowed, suggest replacement to ':'. 593 if (IsCorrectedToColon) { 594 *IsCorrectedToColon = true; 595 Diag(CCLoc, diag::err_nested_name_spec_is_not_class) 596 << &Identifier << getLangOpts().CPlusPlus 597 << FixItHint::CreateReplacement(CCLoc, ":"); 598 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 599 Diag(ND->getLocation(), diag::note_declared_at); 600 return true; 601 } 602 // Replacement '::' -> ':' is not allowed, just issue respective error. 603 Diag(R.getNameLoc(), diag::err_expected_class_or_namespace) 604 << &Identifier << getLangOpts().CPlusPlus; 605 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 606 Diag(ND->getLocation(), diag::note_entity_declared_at) << &Identifier; 607 return true; 608 } 609 } 610 611 if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MSVCCompat) { 612 // We haven't found anything, and we're not recovering from a 613 // different kind of error, so look for typos. 614 DeclarationName Name = Found.getLookupName(); 615 Found.clear(); 616 if (TypoCorrection Corrected = CorrectTypo( 617 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, 618 llvm::make_unique<NestedNameSpecifierValidatorCCC>(*this), 619 CTK_ErrorRecovery, LookupCtx, EnteringContext)) { 620 if (LookupCtx) { 621 bool DroppedSpecifier = 622 Corrected.WillReplaceSpecifier() && 623 Name.getAsString() == Corrected.getAsString(getLangOpts()); 624 if (DroppedSpecifier) 625 SS.clear(); 626 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 627 << Name << LookupCtx << DroppedSpecifier 628 << SS.getRange()); 629 } else 630 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 631 << Name); 632 633 if (Corrected.getCorrectionSpecifier()) 634 SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 635 SourceRange(Found.getNameLoc())); 636 637 if (NamedDecl *ND = Corrected.getFoundDecl()) 638 Found.addDecl(ND); 639 Found.setLookupName(Corrected.getCorrection()); 640 } else { 641 Found.setLookupName(&Identifier); 642 } 643 } 644 645 NamedDecl *SD = 646 Found.isSingleResult() ? Found.getRepresentativeDecl() : nullptr; 647 bool IsExtension = false; 648 bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension); 649 if (!AcceptSpec && IsExtension) { 650 AcceptSpec = true; 651 Diag(IdentifierLoc, diag::ext_nested_name_spec_is_enum); 652 } 653 if (AcceptSpec) { 654 if (!ObjectType.isNull() && !ObjectTypeSearchedInScope && 655 !getLangOpts().CPlusPlus11) { 656 // C++03 [basic.lookup.classref]p4: 657 // [...] If the name is found in both contexts, the 658 // class-name-or-namespace-name shall refer to the same entity. 659 // 660 // We already found the name in the scope of the object. Now, look 661 // into the current scope (the scope of the postfix-expression) to 662 // see if we can find the same name there. As above, if there is no 663 // scope, reconstruct the result from the template instantiation itself. 664 // 665 // Note that C++11 does *not* perform this redundant lookup. 666 NamedDecl *OuterDecl; 667 if (S) { 668 LookupResult FoundOuter(*this, &Identifier, IdentifierLoc, 669 LookupNestedNameSpecifierName); 670 LookupName(FoundOuter, S); 671 OuterDecl = FoundOuter.getAsSingle<NamedDecl>(); 672 } else 673 OuterDecl = ScopeLookupResult; 674 675 if (isAcceptableNestedNameSpecifier(OuterDecl) && 676 OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() && 677 (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) || 678 !Context.hasSameType( 679 Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)), 680 Context.getTypeDeclType(cast<TypeDecl>(SD))))) { 681 if (ErrorRecoveryLookup) 682 return true; 683 684 Diag(IdentifierLoc, 685 diag::err_nested_name_member_ref_lookup_ambiguous) 686 << &Identifier; 687 Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type) 688 << ObjectType; 689 Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope); 690 691 // Fall through so that we'll pick the name we found in the object 692 // type, since that's probably what the user wanted anyway. 693 } 694 } 695 696 if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD)) 697 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 698 699 // If we're just performing this lookup for error-recovery purposes, 700 // don't extend the nested-name-specifier. Just return now. 701 if (ErrorRecoveryLookup) 702 return false; 703 704 // The use of a nested name specifier may trigger deprecation warnings. 705 DiagnoseUseOfDecl(SD, CCLoc); 706 707 708 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) { 709 SS.Extend(Context, Namespace, IdentifierLoc, CCLoc); 710 return false; 711 } 712 713 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) { 714 SS.Extend(Context, Alias, IdentifierLoc, CCLoc); 715 return false; 716 } 717 718 QualType T = 719 Context.getTypeDeclType(cast<TypeDecl>(SD->getUnderlyingDecl())); 720 TypeLocBuilder TLB; 721 if (isa<InjectedClassNameType>(T)) { 722 InjectedClassNameTypeLoc InjectedTL 723 = TLB.push<InjectedClassNameTypeLoc>(T); 724 InjectedTL.setNameLoc(IdentifierLoc); 725 } else if (isa<RecordType>(T)) { 726 RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T); 727 RecordTL.setNameLoc(IdentifierLoc); 728 } else if (isa<TypedefType>(T)) { 729 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T); 730 TypedefTL.setNameLoc(IdentifierLoc); 731 } else if (isa<EnumType>(T)) { 732 EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T); 733 EnumTL.setNameLoc(IdentifierLoc); 734 } else if (isa<TemplateTypeParmType>(T)) { 735 TemplateTypeParmTypeLoc TemplateTypeTL 736 = TLB.push<TemplateTypeParmTypeLoc>(T); 737 TemplateTypeTL.setNameLoc(IdentifierLoc); 738 } else if (isa<UnresolvedUsingType>(T)) { 739 UnresolvedUsingTypeLoc UnresolvedTL 740 = TLB.push<UnresolvedUsingTypeLoc>(T); 741 UnresolvedTL.setNameLoc(IdentifierLoc); 742 } else if (isa<SubstTemplateTypeParmType>(T)) { 743 SubstTemplateTypeParmTypeLoc TL 744 = TLB.push<SubstTemplateTypeParmTypeLoc>(T); 745 TL.setNameLoc(IdentifierLoc); 746 } else if (isa<SubstTemplateTypeParmPackType>(T)) { 747 SubstTemplateTypeParmPackTypeLoc TL 748 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T); 749 TL.setNameLoc(IdentifierLoc); 750 } else { 751 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier"); 752 } 753 754 if (T->isEnumeralType()) 755 Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec); 756 757 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T), 758 CCLoc); 759 return false; 760 } 761 762 // Otherwise, we have an error case. If we don't want diagnostics, just 763 // return an error now. 764 if (ErrorRecoveryLookup) 765 return true; 766 767 // If we didn't find anything during our lookup, try again with 768 // ordinary name lookup, which can help us produce better error 769 // messages. 770 if (Found.empty()) { 771 Found.clear(LookupOrdinaryName); 772 LookupName(Found, S); 773 } 774 775 // In Microsoft mode, if we are within a templated function and we can't 776 // resolve Identifier, then extend the SS with Identifier. This will have 777 // the effect of resolving Identifier during template instantiation. 778 // The goal is to be able to resolve a function call whose 779 // nested-name-specifier is located inside a dependent base class. 780 // Example: 781 // 782 // class C { 783 // public: 784 // static void foo2() { } 785 // }; 786 // template <class T> class A { public: typedef C D; }; 787 // 788 // template <class T> class B : public A<T> { 789 // public: 790 // void foo() { D::foo2(); } 791 // }; 792 if (getLangOpts().MSVCCompat) { 793 DeclContext *DC = LookupCtx ? LookupCtx : CurContext; 794 if (DC->isDependentContext() && DC->isFunctionOrMethod()) { 795 CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent()); 796 if (ContainingClass && ContainingClass->hasAnyDependentBases()) { 797 Diag(IdentifierLoc, diag::ext_undeclared_unqual_id_with_dependent_base) 798 << &Identifier << ContainingClass; 799 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc); 800 return false; 801 } 802 } 803 } 804 805 if (!Found.empty()) { 806 if (TypeDecl *TD = Found.getAsSingle<TypeDecl>()) 807 Diag(IdentifierLoc, diag::err_expected_class_or_namespace) 808 << QualType(TD->getTypeForDecl(), 0) << getLangOpts().CPlusPlus; 809 else { 810 Diag(IdentifierLoc, diag::err_expected_class_or_namespace) 811 << &Identifier << getLangOpts().CPlusPlus; 812 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>()) 813 Diag(ND->getLocation(), diag::note_entity_declared_at) << &Identifier; 814 } 815 } else if (SS.isSet()) 816 Diag(IdentifierLoc, diag::err_no_member) << &Identifier << LookupCtx 817 << SS.getRange(); 818 else 819 Diag(IdentifierLoc, diag::err_undeclared_var_use) << &Identifier; 820 821 return true; 822 } 823 824 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, 825 IdentifierInfo &Identifier, 826 SourceLocation IdentifierLoc, 827 SourceLocation CCLoc, 828 ParsedType ObjectType, 829 bool EnteringContext, 830 CXXScopeSpec &SS, 831 bool ErrorRecoveryLookup, 832 bool *IsCorrectedToColon) { 833 if (SS.isInvalid()) 834 return true; 835 836 return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc, 837 GetTypeFromParser(ObjectType), 838 EnteringContext, SS, 839 /*ScopeLookupResult=*/nullptr, false, 840 IsCorrectedToColon); 841 } 842 843 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 844 const DeclSpec &DS, 845 SourceLocation ColonColonLoc) { 846 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error) 847 return true; 848 849 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype); 850 851 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 852 if (!T->isDependentType() && !T->getAs<TagType>()) { 853 Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) 854 << T << getLangOpts().CPlusPlus; 855 return true; 856 } 857 858 TypeLocBuilder TLB; 859 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 860 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 861 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T), 862 ColonColonLoc); 863 return false; 864 } 865 866 /// IsInvalidUnlessNestedName - This method is used for error recovery 867 /// purposes to determine whether the specified identifier is only valid as 868 /// a nested name specifier, for example a namespace name. It is 869 /// conservatively correct to always return false from this method. 870 /// 871 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier. 872 bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 873 IdentifierInfo &Identifier, 874 SourceLocation IdentifierLoc, 875 SourceLocation ColonLoc, 876 ParsedType ObjectType, 877 bool EnteringContext) { 878 if (SS.isInvalid()) 879 return false; 880 881 return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc, 882 GetTypeFromParser(ObjectType), 883 EnteringContext, SS, 884 /*ScopeLookupResult=*/nullptr, true); 885 } 886 887 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, 888 CXXScopeSpec &SS, 889 SourceLocation TemplateKWLoc, 890 TemplateTy Template, 891 SourceLocation TemplateNameLoc, 892 SourceLocation LAngleLoc, 893 ASTTemplateArgsPtr TemplateArgsIn, 894 SourceLocation RAngleLoc, 895 SourceLocation CCLoc, 896 bool EnteringContext) { 897 if (SS.isInvalid()) 898 return true; 899 900 // Translate the parser's template argument list in our AST format. 901 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 902 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 903 904 DependentTemplateName *DTN = Template.get().getAsDependentTemplateName(); 905 if (DTN && DTN->isIdentifier()) { 906 // Handle a dependent template specialization for which we cannot resolve 907 // the template name. 908 assert(DTN->getQualifier() == SS.getScopeRep()); 909 QualType T = Context.getDependentTemplateSpecializationType(ETK_None, 910 DTN->getQualifier(), 911 DTN->getIdentifier(), 912 TemplateArgs); 913 914 // Create source-location information for this type. 915 TypeLocBuilder Builder; 916 DependentTemplateSpecializationTypeLoc SpecTL 917 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 918 SpecTL.setElaboratedKeywordLoc(SourceLocation()); 919 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 920 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 921 SpecTL.setTemplateNameLoc(TemplateNameLoc); 922 SpecTL.setLAngleLoc(LAngleLoc); 923 SpecTL.setRAngleLoc(RAngleLoc); 924 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 925 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 926 927 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T), 928 CCLoc); 929 return false; 930 } 931 932 TemplateDecl *TD = Template.get().getAsTemplateDecl(); 933 if (Template.get().getAsOverloadedTemplate() || DTN || 934 isa<FunctionTemplateDecl>(TD) || isa<VarTemplateDecl>(TD)) { 935 SourceRange R(TemplateNameLoc, RAngleLoc); 936 if (SS.getRange().isValid()) 937 R.setBegin(SS.getRange().getBegin()); 938 939 Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier) 940 << (TD && isa<VarTemplateDecl>(TD)) << Template.get() << R; 941 NoteAllFoundTemplates(Template.get()); 942 return true; 943 } 944 945 // We were able to resolve the template name to an actual template. 946 // Build an appropriate nested-name-specifier. 947 QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc, 948 TemplateArgs); 949 if (T.isNull()) 950 return true; 951 952 // Alias template specializations can produce types which are not valid 953 // nested name specifiers. 954 if (!T->isDependentType() && !T->getAs<TagType>()) { 955 Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T; 956 NoteAllFoundTemplates(Template.get()); 957 return true; 958 } 959 960 // Provide source-location information for the template specialization type. 961 TypeLocBuilder Builder; 962 TemplateSpecializationTypeLoc SpecTL 963 = Builder.push<TemplateSpecializationTypeLoc>(T); 964 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 965 SpecTL.setTemplateNameLoc(TemplateNameLoc); 966 SpecTL.setLAngleLoc(LAngleLoc); 967 SpecTL.setRAngleLoc(RAngleLoc); 968 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 969 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 970 971 972 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T), 973 CCLoc); 974 return false; 975 } 976 977 namespace { 978 /// \brief A structure that stores a nested-name-specifier annotation, 979 /// including both the nested-name-specifier 980 struct NestedNameSpecifierAnnotation { 981 NestedNameSpecifier *NNS; 982 }; 983 } 984 985 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) { 986 if (SS.isEmpty() || SS.isInvalid()) 987 return nullptr; 988 989 void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) + 990 SS.location_size()), 991 llvm::alignOf<NestedNameSpecifierAnnotation>()); 992 NestedNameSpecifierAnnotation *Annotation 993 = new (Mem) NestedNameSpecifierAnnotation; 994 Annotation->NNS = SS.getScopeRep(); 995 memcpy(Annotation + 1, SS.location_data(), SS.location_size()); 996 return Annotation; 997 } 998 999 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr, 1000 SourceRange AnnotationRange, 1001 CXXScopeSpec &SS) { 1002 if (!AnnotationPtr) { 1003 SS.SetInvalid(AnnotationRange); 1004 return; 1005 } 1006 1007 NestedNameSpecifierAnnotation *Annotation 1008 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr); 1009 SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1)); 1010 } 1011 1012 bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { 1013 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); 1014 1015 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 1016 1017 // There are only two places a well-formed program may qualify a 1018 // declarator: first, when defining a namespace or class member 1019 // out-of-line, and second, when naming an explicitly-qualified 1020 // friend function. The latter case is governed by 1021 // C++03 [basic.lookup.unqual]p10: 1022 // In a friend declaration naming a member function, a name used 1023 // in the function declarator and not part of a template-argument 1024 // in a template-id is first looked up in the scope of the member 1025 // function's class. If it is not found, or if the name is part of 1026 // a template-argument in a template-id, the look up is as 1027 // described for unqualified names in the definition of the class 1028 // granting friendship. 1029 // i.e. we don't push a scope unless it's a class member. 1030 1031 switch (Qualifier->getKind()) { 1032 case NestedNameSpecifier::Global: 1033 case NestedNameSpecifier::Namespace: 1034 case NestedNameSpecifier::NamespaceAlias: 1035 // These are always namespace scopes. We never want to enter a 1036 // namespace scope from anything but a file context. 1037 return CurContext->getRedeclContext()->isFileContext(); 1038 1039 case NestedNameSpecifier::Identifier: 1040 case NestedNameSpecifier::TypeSpec: 1041 case NestedNameSpecifier::TypeSpecWithTemplate: 1042 case NestedNameSpecifier::Super: 1043 // These are never namespace scopes. 1044 return true; 1045 } 1046 1047 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 1048 } 1049 1050 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 1051 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 1052 /// After this method is called, according to [C++ 3.4.3p3], names should be 1053 /// looked up in the declarator-id's scope, until the declarator is parsed and 1054 /// ActOnCXXExitDeclaratorScope is called. 1055 /// The 'SS' should be a non-empty valid CXXScopeSpec. 1056 bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) { 1057 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); 1058 1059 if (SS.isInvalid()) return true; 1060 1061 DeclContext *DC = computeDeclContext(SS, true); 1062 if (!DC) return true; 1063 1064 // Before we enter a declarator's context, we need to make sure that 1065 // it is a complete declaration context. 1066 if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC)) 1067 return true; 1068 1069 EnterDeclaratorContext(S, DC); 1070 1071 // Rebuild the nested name specifier for the new scope. 1072 if (DC->isDependentContext()) 1073 RebuildNestedNameSpecifierInCurrentInstantiation(SS); 1074 1075 return false; 1076 } 1077 1078 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 1079 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 1080 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 1081 /// Used to indicate that names should revert to being looked up in the 1082 /// defining scope. 1083 void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { 1084 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); 1085 if (SS.isInvalid()) 1086 return; 1087 assert(!SS.isInvalid() && computeDeclContext(SS, true) && 1088 "exiting declarator scope we never really entered"); 1089 ExitDeclaratorContext(S); 1090 } 1091