clang API Documentation

SemaTemplateVariadic.cpp
Go to the documentation of this file.
00001 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===/
00008 //
00009 //  This file implements semantic analysis for C++0x variadic templates.
00010 //===----------------------------------------------------------------------===/
00011 
00012 #include "clang/Sema/Sema.h"
00013 #include "clang/Sema/Lookup.h"
00014 #include "clang/Sema/ParsedTemplate.h"
00015 #include "clang/Sema/SemaInternal.h"
00016 #include "clang/Sema/Template.h"
00017 #include "clang/AST/Expr.h"
00018 #include "clang/AST/RecursiveASTVisitor.h"
00019 #include "clang/AST/TypeLoc.h"
00020 
00021 using namespace clang;
00022 
00023 //----------------------------------------------------------------------------
00024 // Visitor that collects unexpanded parameter packs
00025 //----------------------------------------------------------------------------
00026 
00027 namespace {
00028   /// \brief A class that collects unexpanded parameter packs.
00029   class CollectUnexpandedParameterPacksVisitor :
00030     public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> 
00031   {
00032     typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
00033       inherited;
00034 
00035     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
00036 
00037   public:
00038     explicit CollectUnexpandedParameterPacksVisitor(
00039                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
00040       : Unexpanded(Unexpanded) { }
00041 
00042     bool shouldWalkTypesOfTypeLocs() const { return false; }
00043     
00044     //------------------------------------------------------------------------
00045     // Recording occurrences of (unexpanded) parameter packs.
00046     //------------------------------------------------------------------------
00047 
00048     /// \brief Record occurrences of template type parameter packs.
00049     bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
00050       if (TL.getTypePtr()->isParameterPack())
00051         Unexpanded.push_back(std::make_pair(TL.getTypePtr(), TL.getNameLoc()));
00052       return true;
00053     }
00054 
00055     /// \brief Record occurrences of template type parameter packs
00056     /// when we don't have proper source-location information for
00057     /// them.
00058     ///
00059     /// Ideally, this routine would never be used.
00060     bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
00061       if (T->isParameterPack())
00062         Unexpanded.push_back(std::make_pair(T, SourceLocation()));
00063 
00064       return true;
00065     }
00066 
00067     /// \brief Record occurrences of function and non-type template
00068     /// parameter packs in an expression.
00069     bool VisitDeclRefExpr(DeclRefExpr *E) {
00070       if (E->getDecl()->isParameterPack())
00071         Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
00072       
00073       return true;
00074     }
00075     
00076     /// \brief Record occurrences of template template parameter packs.
00077     bool TraverseTemplateName(TemplateName Template) {
00078       if (TemplateTemplateParmDecl *TTP 
00079             = dyn_cast_or_null<TemplateTemplateParmDecl>(
00080                                                   Template.getAsTemplateDecl()))
00081         if (TTP->isParameterPack())
00082           Unexpanded.push_back(std::make_pair(TTP, SourceLocation()));
00083       
00084       return inherited::TraverseTemplateName(Template);
00085     }
00086 
00087     /// \brief Suppress traversal into Objective-C container literal
00088     /// elements that are pack expansions.
00089     bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
00090       if (!E->containsUnexpandedParameterPack())
00091         return true;
00092 
00093       for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
00094         ObjCDictionaryElement Element = E->getKeyValueElement(I);
00095         if (Element.isPackExpansion())
00096           continue;
00097 
00098         TraverseStmt(Element.Key);
00099         TraverseStmt(Element.Value);
00100       }
00101       return true;
00102     }
00103     //------------------------------------------------------------------------
00104     // Pruning the search for unexpanded parameter packs.
00105     //------------------------------------------------------------------------
00106 
00107     /// \brief Suppress traversal into statements and expressions that
00108     /// do not contain unexpanded parameter packs.
00109     bool TraverseStmt(Stmt *S) { 
00110       if (Expr *E = dyn_cast_or_null<Expr>(S))
00111         if (E->containsUnexpandedParameterPack())
00112           return inherited::TraverseStmt(E);
00113 
00114       return true; 
00115     }
00116 
00117     /// \brief Suppress traversal into types that do not contain
00118     /// unexpanded parameter packs.
00119     bool TraverseType(QualType T) {
00120       if (!T.isNull() && T->containsUnexpandedParameterPack())
00121         return inherited::TraverseType(T);
00122 
00123       return true;
00124     }
00125 
00126     /// \brief Suppress traversel into types with location information
00127     /// that do not contain unexpanded parameter packs.
00128     bool TraverseTypeLoc(TypeLoc TL) {
00129       if (!TL.getType().isNull() && 
00130           TL.getType()->containsUnexpandedParameterPack())
00131         return inherited::TraverseTypeLoc(TL);
00132 
00133       return true;
00134     }
00135 
00136     /// \brief Suppress traversal of non-parameter declarations, since
00137     /// they cannot contain unexpanded parameter packs.
00138     bool TraverseDecl(Decl *D) { 
00139       if (D && isa<ParmVarDecl>(D))
00140         return inherited::TraverseDecl(D);
00141 
00142       return true; 
00143     }
00144 
00145     /// \brief Suppress traversal of template argument pack expansions.
00146     bool TraverseTemplateArgument(const TemplateArgument &Arg) {
00147       if (Arg.isPackExpansion())
00148         return true;
00149 
00150       return inherited::TraverseTemplateArgument(Arg);
00151     }
00152 
00153     /// \brief Suppress traversal of template argument pack expansions.
00154     bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
00155       if (ArgLoc.getArgument().isPackExpansion())
00156         return true;
00157       
00158       return inherited::TraverseTemplateArgumentLoc(ArgLoc);
00159     }
00160   };
00161 }
00162 
00163 /// \brief Diagnose all of the unexpanded parameter packs in the given
00164 /// vector.
00165 void
00166 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
00167                                        UnexpandedParameterPackContext UPPC,
00168                                  ArrayRef<UnexpandedParameterPack> Unexpanded) {
00169   if (Unexpanded.empty())
00170     return;
00171   
00172   SmallVector<SourceLocation, 4> Locations;
00173   SmallVector<IdentifierInfo *, 4> Names;
00174   llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
00175 
00176   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
00177     IdentifierInfo *Name = 0;
00178     if (const TemplateTypeParmType *TTP
00179           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
00180       Name = TTP->getIdentifier();
00181     else
00182       Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
00183 
00184     if (Name && NamesKnown.insert(Name))
00185       Names.push_back(Name);
00186 
00187     if (Unexpanded[I].second.isValid())
00188       Locations.push_back(Unexpanded[I].second);
00189   }
00190 
00191   DiagnosticBuilder DB
00192     = Names.size() == 0? Diag(Loc, diag::err_unexpanded_parameter_pack_0)
00193                            << (int)UPPC
00194     : Names.size() == 1? Diag(Loc, diag::err_unexpanded_parameter_pack_1)
00195                            << (int)UPPC << Names[0]
00196     : Names.size() == 2? Diag(Loc, diag::err_unexpanded_parameter_pack_2)
00197                            << (int)UPPC << Names[0] << Names[1]
00198     : Diag(Loc, diag::err_unexpanded_parameter_pack_3_or_more)
00199         << (int)UPPC << Names[0] << Names[1];
00200 
00201   for (unsigned I = 0, N = Locations.size(); I != N; ++I)
00202     DB << SourceRange(Locations[I]);
00203 }
00204 
00205 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, 
00206                                            TypeSourceInfo *T,
00207                                          UnexpandedParameterPackContext UPPC) {
00208   // C++0x [temp.variadic]p5:
00209   //   An appearance of a name of a parameter pack that is not expanded is 
00210   //   ill-formed.
00211   if (!T->getType()->containsUnexpandedParameterPack())
00212     return false;
00213 
00214   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00215   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
00216                                                               T->getTypeLoc());
00217   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00218   DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
00219   return true;
00220 }
00221 
00222 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
00223                                         UnexpandedParameterPackContext UPPC) {
00224   // C++0x [temp.variadic]p5:
00225   //   An appearance of a name of a parameter pack that is not expanded is 
00226   //   ill-formed.
00227   if (!E->containsUnexpandedParameterPack())
00228     return false;
00229 
00230   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00231   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
00232   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00233   DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
00234   return true;
00235 }
00236 
00237 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
00238                                         UnexpandedParameterPackContext UPPC) {
00239   // C++0x [temp.variadic]p5:
00240   //   An appearance of a name of a parameter pack that is not expanded is 
00241   //   ill-formed.
00242   if (!SS.getScopeRep() || 
00243       !SS.getScopeRep()->containsUnexpandedParameterPack())
00244     return false;
00245 
00246   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00247   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00248     .TraverseNestedNameSpecifier(SS.getScopeRep());
00249   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00250   DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(), 
00251                                    UPPC, Unexpanded);
00252   return true;
00253 }
00254 
00255 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
00256                                          UnexpandedParameterPackContext UPPC) {
00257   // C++0x [temp.variadic]p5:
00258   //   An appearance of a name of a parameter pack that is not expanded is 
00259   //   ill-formed.
00260   switch (NameInfo.getName().getNameKind()) {
00261   case DeclarationName::Identifier:
00262   case DeclarationName::ObjCZeroArgSelector:
00263   case DeclarationName::ObjCOneArgSelector:
00264   case DeclarationName::ObjCMultiArgSelector:
00265   case DeclarationName::CXXOperatorName:
00266   case DeclarationName::CXXLiteralOperatorName:
00267   case DeclarationName::CXXUsingDirective:
00268     return false;
00269 
00270   case DeclarationName::CXXConstructorName:
00271   case DeclarationName::CXXDestructorName:
00272   case DeclarationName::CXXConversionFunctionName:
00273     // FIXME: We shouldn't need this null check!
00274     if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
00275       return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
00276 
00277     if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
00278       return false;
00279 
00280     break;
00281   }
00282 
00283   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00284   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00285     .TraverseType(NameInfo.getName().getCXXNameType());
00286   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00287   DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
00288   return true;
00289 }
00290 
00291 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
00292                                            TemplateName Template,
00293                                        UnexpandedParameterPackContext UPPC) {
00294   
00295   if (Template.isNull() || !Template.containsUnexpandedParameterPack())
00296     return false;
00297 
00298   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00299   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00300     .TraverseTemplateName(Template);
00301   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00302   DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
00303   return true;
00304 }
00305 
00306 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
00307                                          UnexpandedParameterPackContext UPPC) {
00308   if (Arg.getArgument().isNull() || 
00309       !Arg.getArgument().containsUnexpandedParameterPack())
00310     return false;
00311   
00312   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00313   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00314     .TraverseTemplateArgumentLoc(Arg);
00315   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00316   DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
00317   return true;  
00318 }
00319 
00320 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
00321                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00322   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00323     .TraverseTemplateArgument(Arg);
00324 }
00325 
00326 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
00327                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00328   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00329     .TraverseTemplateArgumentLoc(Arg);
00330 }
00331 
00332 void Sema::collectUnexpandedParameterPacks(QualType T,
00333                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00334   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);  
00335 }  
00336 
00337 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
00338                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00339   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);  
00340 }  
00341 
00342 void Sema::collectUnexpandedParameterPacks(CXXScopeSpec &SS,
00343                                            SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00344   NestedNameSpecifier *Qualifier = SS.getScopeRep();
00345   if (!Qualifier)
00346     return;
00347   
00348   NestedNameSpecifierLoc QualifierLoc(Qualifier, SS.location_data());
00349   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00350     .TraverseNestedNameSpecifierLoc(QualifierLoc);
00351 }
00352 
00353 void Sema::collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
00354                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00355   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00356     .TraverseDeclarationNameInfo(NameInfo);
00357 }
00358 
00359 
00360 ParsedTemplateArgument 
00361 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
00362                          SourceLocation EllipsisLoc) {
00363   if (Arg.isInvalid())
00364     return Arg;
00365 
00366   switch (Arg.getKind()) {
00367   case ParsedTemplateArgument::Type: {
00368     TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
00369     if (Result.isInvalid())
00370       return ParsedTemplateArgument();
00371 
00372     return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), 
00373                                   Arg.getLocation());
00374   }
00375 
00376   case ParsedTemplateArgument::NonType: {
00377     ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
00378     if (Result.isInvalid())
00379       return ParsedTemplateArgument();
00380     
00381     return ParsedTemplateArgument(Arg.getKind(), Result.get(), 
00382                                   Arg.getLocation());
00383   }
00384     
00385   case ParsedTemplateArgument::Template:
00386     if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
00387       SourceRange R(Arg.getLocation());
00388       if (Arg.getScopeSpec().isValid())
00389         R.setBegin(Arg.getScopeSpec().getBeginLoc());
00390       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
00391         << R;
00392       return ParsedTemplateArgument();
00393     }
00394       
00395     return Arg.getTemplatePackExpansion(EllipsisLoc);
00396   }
00397   llvm_unreachable("Unhandled template argument kind?");
00398 }
00399 
00400 TypeResult Sema::ActOnPackExpansion(ParsedType Type, 
00401                                     SourceLocation EllipsisLoc) {
00402   TypeSourceInfo *TSInfo;
00403   GetTypeFromParser(Type, &TSInfo);
00404   if (!TSInfo)
00405     return true;
00406 
00407   TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc,
00408                                                 llvm::Optional<unsigned>());
00409   if (!TSResult)
00410     return true;
00411   
00412   return CreateParsedType(TSResult->getType(), TSResult);
00413 }
00414 
00415 TypeSourceInfo *Sema::CheckPackExpansion(TypeSourceInfo *Pattern,
00416                                          SourceLocation EllipsisLoc,
00417                                        llvm::Optional<unsigned> NumExpansions) {
00418   // Create the pack expansion type and source-location information.
00419   QualType Result = CheckPackExpansion(Pattern->getType(), 
00420                                        Pattern->getTypeLoc().getSourceRange(),
00421                                        EllipsisLoc, NumExpansions);
00422   if (Result.isNull())
00423     return 0;
00424   
00425   TypeSourceInfo *TSResult = Context.CreateTypeSourceInfo(Result);
00426   PackExpansionTypeLoc TL = cast<PackExpansionTypeLoc>(TSResult->getTypeLoc());
00427   TL.setEllipsisLoc(EllipsisLoc);
00428   
00429   // Copy over the source-location information from the type.
00430   memcpy(TL.getNextTypeLoc().getOpaqueData(),
00431          Pattern->getTypeLoc().getOpaqueData(),
00432          Pattern->getTypeLoc().getFullDataSize());
00433   return TSResult;
00434 }
00435 
00436 QualType Sema::CheckPackExpansion(QualType Pattern,
00437                                   SourceRange PatternRange,
00438                                   SourceLocation EllipsisLoc,
00439                                   llvm::Optional<unsigned> NumExpansions) {
00440   // C++0x [temp.variadic]p5:
00441   //   The pattern of a pack expansion shall name one or more
00442   //   parameter packs that are not expanded by a nested pack
00443   //   expansion.
00444   if (!Pattern->containsUnexpandedParameterPack()) {
00445     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
00446       << PatternRange;
00447     return QualType();
00448   }
00449 
00450   return Context.getPackExpansionType(Pattern, NumExpansions);
00451 }
00452 
00453 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
00454   return CheckPackExpansion(Pattern, EllipsisLoc, llvm::Optional<unsigned>());
00455 }
00456 
00457 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
00458                                     llvm::Optional<unsigned> NumExpansions) {
00459   if (!Pattern)
00460     return ExprError();
00461   
00462   // C++0x [temp.variadic]p5:
00463   //   The pattern of a pack expansion shall name one or more
00464   //   parameter packs that are not expanded by a nested pack
00465   //   expansion.
00466   if (!Pattern->containsUnexpandedParameterPack()) {
00467     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
00468     << Pattern->getSourceRange();
00469     return ExprError();
00470   }
00471   
00472   // Create the pack expansion expression and source-location information.
00473   return Owned(new (Context) PackExpansionExpr(Context.DependentTy, Pattern,
00474                                                EllipsisLoc, NumExpansions));
00475 }
00476 
00477 /// \brief Retrieve the depth and index of a parameter pack.
00478 static std::pair<unsigned, unsigned> 
00479 getDepthAndIndex(NamedDecl *ND) {
00480   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
00481     return std::make_pair(TTP->getDepth(), TTP->getIndex());
00482   
00483   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
00484     return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
00485   
00486   TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
00487   return std::make_pair(TTP->getDepth(), TTP->getIndex());
00488 }
00489 
00490 bool Sema::CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
00491                                            SourceRange PatternRange,
00492                                    ArrayRef<UnexpandedParameterPack> Unexpanded,
00493                              const MultiLevelTemplateArgumentList &TemplateArgs,
00494                                            bool &ShouldExpand,
00495                                            bool &RetainExpansion,
00496                                      llvm::Optional<unsigned> &NumExpansions) {                                        
00497   ShouldExpand = true;
00498   RetainExpansion = false;
00499   std::pair<IdentifierInfo *, SourceLocation> FirstPack;
00500   bool HaveFirstPack = false;
00501   
00502   for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
00503                                                  end = Unexpanded.end();
00504                                                   i != end; ++i) {
00505     // Compute the depth and index for this parameter pack.
00506     unsigned Depth = 0, Index = 0;
00507     IdentifierInfo *Name;
00508     bool IsFunctionParameterPack = false;
00509     
00510     if (const TemplateTypeParmType *TTP
00511         = i->first.dyn_cast<const TemplateTypeParmType *>()) {
00512       Depth = TTP->getDepth();
00513       Index = TTP->getIndex();
00514       Name = TTP->getIdentifier();
00515     } else {
00516       NamedDecl *ND = i->first.get<NamedDecl *>();
00517       if (isa<ParmVarDecl>(ND))
00518         IsFunctionParameterPack = true;
00519       else
00520         llvm::tie(Depth, Index) = getDepthAndIndex(ND);        
00521       
00522       Name = ND->getIdentifier();
00523     }
00524     
00525     // Determine the size of this argument pack.
00526     unsigned NewPackSize;    
00527     if (IsFunctionParameterPack) {
00528       // Figure out whether we're instantiating to an argument pack or not.
00529       typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
00530       
00531       llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
00532         = CurrentInstantiationScope->findInstantiationOf(
00533                                         i->first.get<NamedDecl *>());
00534       if (Instantiation->is<DeclArgumentPack *>()) {
00535         // We could expand this function parameter pack.
00536         NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
00537       } else {
00538         // We can't expand this function parameter pack, so we can't expand
00539         // the pack expansion.
00540         ShouldExpand = false;
00541         continue;
00542       }
00543     } else {
00544       // If we don't have a template argument at this depth/index, then we 
00545       // cannot expand the pack expansion. Make a note of this, but we still 
00546       // want to check any parameter packs we *do* have arguments for.
00547       if (Depth >= TemplateArgs.getNumLevels() ||
00548           !TemplateArgs.hasTemplateArgument(Depth, Index)) {
00549         ShouldExpand = false;
00550         continue;
00551       }
00552       
00553       // Determine the size of the argument pack.
00554       NewPackSize = TemplateArgs(Depth, Index).pack_size();
00555     }
00556     
00557     // C++0x [temp.arg.explicit]p9:
00558     //   Template argument deduction can extend the sequence of template 
00559     //   arguments corresponding to a template parameter pack, even when the
00560     //   sequence contains explicitly specified template arguments.
00561     if (!IsFunctionParameterPack) {
00562       if (NamedDecl *PartialPack 
00563                     = CurrentInstantiationScope->getPartiallySubstitutedPack()){
00564         unsigned PartialDepth, PartialIndex;
00565         llvm::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
00566         if (PartialDepth == Depth && PartialIndex == Index)
00567           RetainExpansion = true;
00568       }
00569     }
00570     
00571     if (!NumExpansions) {
00572       // The is the first pack we've seen for which we have an argument. 
00573       // Record it.
00574       NumExpansions = NewPackSize;
00575       FirstPack.first = Name;
00576       FirstPack.second = i->second;
00577       HaveFirstPack = true;
00578       continue;
00579     }
00580     
00581     if (NewPackSize != *NumExpansions) {
00582       // C++0x [temp.variadic]p5:
00583       //   All of the parameter packs expanded by a pack expansion shall have 
00584       //   the same number of arguments specified.
00585       if (HaveFirstPack)
00586         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
00587           << FirstPack.first << Name << *NumExpansions << NewPackSize
00588           << SourceRange(FirstPack.second) << SourceRange(i->second);
00589       else
00590         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
00591           << Name << *NumExpansions << NewPackSize
00592           << SourceRange(i->second);
00593       return true;
00594     }
00595   }
00596   
00597   return false;
00598 }
00599 
00600 unsigned Sema::getNumArgumentsInExpansion(QualType T, 
00601                           const MultiLevelTemplateArgumentList &TemplateArgs) {
00602   QualType Pattern = cast<PackExpansionType>(T)->getPattern();
00603   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00604   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
00605 
00606   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
00607     // Compute the depth and index for this parameter pack.
00608     unsigned Depth;
00609     unsigned Index;
00610     
00611     if (const TemplateTypeParmType *TTP
00612           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
00613       Depth = TTP->getDepth();
00614       Index = TTP->getIndex();
00615     } else {      
00616       NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
00617       if (isa<ParmVarDecl>(ND)) {
00618         // Function parameter pack.
00619         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
00620         
00621         llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
00622           = CurrentInstantiationScope->findInstantiationOf(
00623                                         Unexpanded[I].first.get<NamedDecl *>());
00624         if (Instantiation->is<DeclArgumentPack *>())
00625           return Instantiation->get<DeclArgumentPack *>()->size();
00626         
00627         continue;
00628       }
00629       
00630       llvm::tie(Depth, Index) = getDepthAndIndex(ND);        
00631     }
00632     if (Depth >= TemplateArgs.getNumLevels() ||
00633         !TemplateArgs.hasTemplateArgument(Depth, Index))
00634       continue;
00635     
00636     // Determine the size of the argument pack.
00637     return TemplateArgs(Depth, Index).pack_size();
00638   }
00639   
00640   llvm_unreachable("No unexpanded parameter packs in type expansion.");
00641 }
00642 
00643 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
00644   const DeclSpec &DS = D.getDeclSpec();
00645   switch (DS.getTypeSpecType()) {
00646   case TST_typename:
00647   case TST_typeofType:
00648   case TST_underlyingType:
00649   case TST_atomic: {
00650     QualType T = DS.getRepAsType().get();
00651     if (!T.isNull() && T->containsUnexpandedParameterPack())
00652       return true;
00653     break;
00654   }
00655       
00656   case TST_typeofExpr:
00657   case TST_decltype:
00658     if (DS.getRepAsExpr() && 
00659         DS.getRepAsExpr()->containsUnexpandedParameterPack())
00660       return true;
00661     break;
00662       
00663   case TST_unspecified:
00664   case TST_void:
00665   case TST_char:
00666   case TST_wchar:
00667   case TST_char16:
00668   case TST_char32:
00669   case TST_int:
00670   case TST_int128:
00671   case TST_half:
00672   case TST_float:
00673   case TST_double:
00674   case TST_bool:
00675   case TST_decimal32:
00676   case TST_decimal64:
00677   case TST_decimal128:
00678   case TST_enum:
00679   case TST_union:
00680   case TST_struct:
00681   case TST_class:
00682   case TST_auto:
00683   case TST_unknown_anytype:
00684   case TST_error:
00685     break;
00686   }
00687   
00688   for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
00689     const DeclaratorChunk &Chunk = D.getTypeObject(I);
00690     switch (Chunk.Kind) {
00691     case DeclaratorChunk::Pointer:
00692     case DeclaratorChunk::Reference:
00693     case DeclaratorChunk::Paren:
00694       // These declarator chunks cannot contain any parameter packs.
00695       break;
00696         
00697     case DeclaratorChunk::Array:
00698     case DeclaratorChunk::Function:
00699     case DeclaratorChunk::BlockPointer:
00700       // Syntactically, these kinds of declarator chunks all come after the
00701       // declarator-id (conceptually), so the parser should not invoke this
00702       // routine at this time.
00703       llvm_unreachable("Could not have seen this kind of declarator chunk");
00704         
00705     case DeclaratorChunk::MemberPointer:
00706       if (Chunk.Mem.Scope().getScopeRep() &&
00707           Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
00708         return true;
00709       break;
00710     }
00711   }
00712   
00713   return false;
00714 }
00715 
00716 namespace {
00717 
00718 // Callback to only accept typo corrections that refer to parameter packs.
00719 class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
00720  public:
00721   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
00722     NamedDecl *ND = candidate.getCorrectionDecl();
00723     return ND && ND->isParameterPack();
00724   }
00725 };
00726 
00727 }
00728 
00729 /// \brief Called when an expression computing the size of a parameter pack
00730 /// is parsed.
00731 ///
00732 /// \code
00733 /// template<typename ...Types> struct count {
00734 ///   static const unsigned value = sizeof...(Types);
00735 /// };
00736 /// \endcode
00737 ///
00738 //
00739 /// \param OpLoc The location of the "sizeof" keyword.
00740 /// \param Name The name of the parameter pack whose size will be determined.
00741 /// \param NameLoc The source location of the name of the parameter pack.
00742 /// \param RParenLoc The location of the closing parentheses.
00743 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
00744                                               SourceLocation OpLoc,
00745                                               IdentifierInfo &Name,
00746                                               SourceLocation NameLoc,
00747                                               SourceLocation RParenLoc) {
00748   // C++0x [expr.sizeof]p5:
00749   //   The identifier in a sizeof... expression shall name a parameter pack.
00750   LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
00751   LookupName(R, S);
00752   
00753   NamedDecl *ParameterPack = 0;
00754   ParameterPackValidatorCCC Validator;
00755   switch (R.getResultKind()) {
00756   case LookupResult::Found:
00757     ParameterPack = R.getFoundDecl();
00758     break;
00759     
00760   case LookupResult::NotFound:
00761   case LookupResult::NotFoundInCurrentInstantiation:
00762     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
00763                                                R.getLookupKind(), S, 0,
00764                                                Validator)) {
00765       std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
00766       ParameterPack = Corrected.getCorrectionDecl();
00767       Diag(NameLoc, diag::err_sizeof_pack_no_pack_name_suggest)
00768         << &Name << CorrectedQuotedStr
00769         << FixItHint::CreateReplacement(
00770             NameLoc, Corrected.getAsString(getLangOpts()));
00771       Diag(ParameterPack->getLocation(), diag::note_parameter_pack_here)
00772         << CorrectedQuotedStr;
00773     }
00774       
00775   case LookupResult::FoundOverloaded:
00776   case LookupResult::FoundUnresolvedValue:
00777     break;
00778     
00779   case LookupResult::Ambiguous:
00780     DiagnoseAmbiguousLookup(R);
00781     return ExprError();
00782   }
00783   
00784   if (!ParameterPack || !ParameterPack->isParameterPack()) {
00785     Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
00786       << &Name;
00787     return ExprError();
00788   }
00789 
00790   MarkAnyDeclReferenced(OpLoc, ParameterPack);
00791 
00792   return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc, 
00793                                       ParameterPack, NameLoc, RParenLoc);
00794 }