blob: 38a777efb17fb534d26544c672237eef83868167 [file] [log] [blame]
Douglas Gregorb55fdf82010-12-15 17:38:57 +00001//===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
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// This file implements semantic analysis for C++0x variadic templates.
10//===----------------------------------------------------------------------===/
11
12#include "clang/Sema/Sema.h"
Douglas Gregor820ba7b2011-01-04 17:33:58 +000013#include "clang/Sema/Lookup.h"
Douglas Gregord2fa7662010-12-20 02:24:11 +000014#include "clang/Sema/ParsedTemplate.h"
Douglas Gregorb55fdf82010-12-15 17:38:57 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregor840bd6c2010-12-20 22:05:00 +000016#include "clang/Sema/Template.h"
Douglas Gregorb55fdf82010-12-15 17:38:57 +000017#include "clang/AST/Expr.h"
Douglas Gregor1da294a2010-12-15 19:43:21 +000018#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb55fdf82010-12-15 17:38:57 +000019#include "clang/AST/TypeLoc.h"
20
21using namespace clang;
22
Douglas Gregor1da294a2010-12-15 19:43:21 +000023//----------------------------------------------------------------------------
24// Visitor that collects unexpanded parameter packs
25//----------------------------------------------------------------------------
26
Douglas Gregor1da294a2010-12-15 19:43:21 +000027namespace {
28 /// \brief A class that collects unexpanded parameter packs.
29 class CollectUnexpandedParameterPacksVisitor :
30 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
31 {
32 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
33 inherited;
34
35 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
36
37 public:
38 explicit CollectUnexpandedParameterPacksVisitor(
39 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
40 : Unexpanded(Unexpanded) { }
41
Douglas Gregor15b4ec22010-12-20 23:07:20 +000042 bool shouldWalkTypesOfTypeLocs() const { return false; }
43
Douglas Gregor1da294a2010-12-15 19:43:21 +000044 //------------------------------------------------------------------------
45 // Recording occurrences of (unexpanded) parameter packs.
46 //------------------------------------------------------------------------
47
48 /// \brief Record occurrences of template type parameter packs.
49 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
50 if (TL.getTypePtr()->isParameterPack())
51 Unexpanded.push_back(std::make_pair(TL.getTypePtr(), TL.getNameLoc()));
52 return true;
53 }
54
55 /// \brief Record occurrences of template type parameter packs
56 /// when we don't have proper source-location information for
57 /// them.
58 ///
59 /// Ideally, this routine would never be used.
60 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
61 if (T->isParameterPack())
62 Unexpanded.push_back(std::make_pair(T, SourceLocation()));
63
64 return true;
65 }
66
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000067 /// \brief Record occurrences of (FIXME: function and) non-type template
68 /// parameter packs in an expression.
69 bool VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf3010112011-01-07 16:43:16 +000070 if (E->getDecl()->isParameterPack())
71 Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000072
73 return true;
74 }
75
Douglas Gregorf5500772011-01-05 15:48:55 +000076 /// \brief Record occurrences of template template parameter packs.
77 bool TraverseTemplateName(TemplateName Template) {
78 if (TemplateTemplateParmDecl *TTP
79 = dyn_cast_or_null<TemplateTemplateParmDecl>(
80 Template.getAsTemplateDecl()))
81 if (TTP->isParameterPack())
82 Unexpanded.push_back(std::make_pair(TTP, SourceLocation()));
83
84 return inherited::TraverseTemplateName(Template);
85 }
Douglas Gregor1da294a2010-12-15 19:43:21 +000086
Douglas Gregor1da294a2010-12-15 19:43:21 +000087 //------------------------------------------------------------------------
88 // Pruning the search for unexpanded parameter packs.
89 //------------------------------------------------------------------------
90
91 /// \brief Suppress traversal into statements and expressions that
92 /// do not contain unexpanded parameter packs.
93 bool TraverseStmt(Stmt *S) {
94 if (Expr *E = dyn_cast_or_null<Expr>(S))
95 if (E->containsUnexpandedParameterPack())
96 return inherited::TraverseStmt(E);
97
98 return true;
99 }
100
101 /// \brief Suppress traversal into types that do not contain
102 /// unexpanded parameter packs.
103 bool TraverseType(QualType T) {
104 if (!T.isNull() && T->containsUnexpandedParameterPack())
105 return inherited::TraverseType(T);
106
107 return true;
108 }
109
110 /// \brief Suppress traversel into types with location information
111 /// that do not contain unexpanded parameter packs.
112 bool TraverseTypeLoc(TypeLoc TL) {
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000113 if (!TL.getType().isNull() &&
114 TL.getType()->containsUnexpandedParameterPack())
Douglas Gregor1da294a2010-12-15 19:43:21 +0000115 return inherited::TraverseTypeLoc(TL);
116
117 return true;
118 }
119
Douglas Gregora8461bb2010-12-15 21:57:59 +0000120 /// \brief Suppress traversal of non-parameter declarations, since
121 /// they cannot contain unexpanded parameter packs.
122 bool TraverseDecl(Decl *D) {
123 if (D && isa<ParmVarDecl>(D))
124 return inherited::TraverseDecl(D);
125
126 return true;
127 }
Douglas Gregoreb29d182011-01-05 17:40:24 +0000128
129 /// \brief Suppress traversal of template argument pack expansions.
130 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
131 if (Arg.isPackExpansion())
132 return true;
133
134 return inherited::TraverseTemplateArgument(Arg);
135 }
136
137 /// \brief Suppress traversal of template argument pack expansions.
138 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
139 if (ArgLoc.getArgument().isPackExpansion())
140 return true;
141
142 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
143 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000144 };
145}
146
147/// \brief Diagnose all of the unexpanded parameter packs in the given
148/// vector.
149static void
150DiagnoseUnexpandedParameterPacks(Sema &S, SourceLocation Loc,
151 Sema::UnexpandedParameterPackContext UPPC,
152 const llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
153 llvm::SmallVector<SourceLocation, 4> Locations;
154 llvm::SmallVector<IdentifierInfo *, 4> Names;
155 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
156
157 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
158 IdentifierInfo *Name = 0;
159 if (const TemplateTypeParmType *TTP
160 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
161 Name = TTP->getName();
162 else
163 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
164
165 if (Name && NamesKnown.insert(Name))
166 Names.push_back(Name);
167
168 if (Unexpanded[I].second.isValid())
169 Locations.push_back(Unexpanded[I].second);
170 }
171
172 DiagnosticBuilder DB
173 = Names.size() == 0? S.Diag(Loc, diag::err_unexpanded_parameter_pack_0)
174 << (int)UPPC
175 : Names.size() == 1? S.Diag(Loc, diag::err_unexpanded_parameter_pack_1)
176 << (int)UPPC << Names[0]
177 : Names.size() == 2? S.Diag(Loc, diag::err_unexpanded_parameter_pack_2)
178 << (int)UPPC << Names[0] << Names[1]
179 : S.Diag(Loc, diag::err_unexpanded_parameter_pack_3_or_more)
180 << (int)UPPC << Names[0] << Names[1];
181
182 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
183 DB << SourceRange(Locations[I]);
184}
185
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000186bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
187 TypeSourceInfo *T,
188 UnexpandedParameterPackContext UPPC) {
189 // C++0x [temp.variadic]p5:
190 // An appearance of a name of a parameter pack that is not expanded is
191 // ill-formed.
192 if (!T->getType()->containsUnexpandedParameterPack())
193 return false;
194
Douglas Gregor1da294a2010-12-15 19:43:21 +0000195 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
196 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
197 T->getTypeLoc());
198 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
199 DiagnoseUnexpandedParameterPacks(*this, Loc, UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000200 return true;
201}
202
203bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
Douglas Gregorc4356532010-12-16 00:46:58 +0000204 UnexpandedParameterPackContext UPPC) {
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000205 // C++0x [temp.variadic]p5:
206 // An appearance of a name of a parameter pack that is not expanded is
207 // ill-formed.
208 if (!E->containsUnexpandedParameterPack())
209 return false;
210
Douglas Gregor1da294a2010-12-15 19:43:21 +0000211 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
212 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
213 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
214 DiagnoseUnexpandedParameterPacks(*this, E->getLocStart(), UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000215 return true;
216}
Douglas Gregorc4356532010-12-16 00:46:58 +0000217
218bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
219 UnexpandedParameterPackContext UPPC) {
220 // C++0x [temp.variadic]p5:
221 // An appearance of a name of a parameter pack that is not expanded is
222 // ill-formed.
223 if (!SS.getScopeRep() ||
224 !SS.getScopeRep()->containsUnexpandedParameterPack())
225 return false;
226
227 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
228 CollectUnexpandedParameterPacksVisitor(Unexpanded)
229 .TraverseNestedNameSpecifier(SS.getScopeRep());
230 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
231 DiagnoseUnexpandedParameterPacks(*this, SS.getRange().getBegin(),
232 UPPC, Unexpanded);
233 return true;
234}
235
236bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
237 UnexpandedParameterPackContext UPPC) {
238 // C++0x [temp.variadic]p5:
239 // An appearance of a name of a parameter pack that is not expanded is
240 // ill-formed.
241 switch (NameInfo.getName().getNameKind()) {
242 case DeclarationName::Identifier:
243 case DeclarationName::ObjCZeroArgSelector:
244 case DeclarationName::ObjCOneArgSelector:
245 case DeclarationName::ObjCMultiArgSelector:
246 case DeclarationName::CXXOperatorName:
247 case DeclarationName::CXXLiteralOperatorName:
248 case DeclarationName::CXXUsingDirective:
249 return false;
250
251 case DeclarationName::CXXConstructorName:
252 case DeclarationName::CXXDestructorName:
253 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor062ecac2010-12-16 17:19:19 +0000254 // FIXME: We shouldn't need this null check!
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000255 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
256 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
257
258 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
Douglas Gregorc4356532010-12-16 00:46:58 +0000259 return false;
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000260
Douglas Gregorc4356532010-12-16 00:46:58 +0000261 break;
262 }
263
264 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
265 CollectUnexpandedParameterPacksVisitor(Unexpanded)
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000266 .TraverseType(NameInfo.getName().getCXXNameType());
Douglas Gregorc4356532010-12-16 00:46:58 +0000267 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
268 DiagnoseUnexpandedParameterPacks(*this, NameInfo.getLoc(), UPPC, Unexpanded);
269 return true;
270}
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000271
272bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
273 TemplateName Template,
274 UnexpandedParameterPackContext UPPC) {
275
276 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
277 return false;
278
279 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
280 CollectUnexpandedParameterPacksVisitor(Unexpanded)
281 .TraverseTemplateName(Template);
282 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
283 DiagnoseUnexpandedParameterPacks(*this, Loc, UPPC, Unexpanded);
284 return true;
285}
286
Douglas Gregor14406932011-01-03 20:35:03 +0000287bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
288 UnexpandedParameterPackContext UPPC) {
289 if (Arg.getArgument().isNull() ||
290 !Arg.getArgument().containsUnexpandedParameterPack())
291 return false;
292
293 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
294 CollectUnexpandedParameterPacksVisitor(Unexpanded)
295 .TraverseTemplateArgumentLoc(Arg);
296 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
297 DiagnoseUnexpandedParameterPacks(*this, Arg.getLocation(), UPPC, Unexpanded);
298 return true;
299}
300
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000301void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
302 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
303 CollectUnexpandedParameterPacksVisitor(Unexpanded)
304 .TraverseTemplateArgument(Arg);
305}
306
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000307void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
308 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
309 CollectUnexpandedParameterPacksVisitor(Unexpanded)
310 .TraverseTemplateArgumentLoc(Arg);
311}
312
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000313void Sema::collectUnexpandedParameterPacks(QualType T,
314 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
315 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
316}
317
Douglas Gregor752a5952011-01-03 22:36:02 +0000318void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
319 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
320 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
321}
322
Douglas Gregord2fa7662010-12-20 02:24:11 +0000323ParsedTemplateArgument
324Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
325 SourceLocation EllipsisLoc) {
326 if (Arg.isInvalid())
327 return Arg;
328
329 switch (Arg.getKind()) {
330 case ParsedTemplateArgument::Type: {
331 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
332 if (Result.isInvalid())
333 return ParsedTemplateArgument();
334
335 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
336 Arg.getLocation());
337 }
338
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000339 case ParsedTemplateArgument::NonType: {
340 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
341 if (Result.isInvalid())
342 return ParsedTemplateArgument();
343
344 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
345 Arg.getLocation());
346 }
347
Douglas Gregord2fa7662010-12-20 02:24:11 +0000348 case ParsedTemplateArgument::Template:
Douglas Gregoreb29d182011-01-05 17:40:24 +0000349 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
350 SourceRange R(Arg.getLocation());
351 if (Arg.getScopeSpec().isValid())
352 R.setBegin(Arg.getScopeSpec().getBeginLoc());
353 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
354 << R;
355 return ParsedTemplateArgument();
356 }
357
358 return Arg.getTemplatePackExpansion(EllipsisLoc);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000359 }
360 llvm_unreachable("Unhandled template argument kind?");
361 return ParsedTemplateArgument();
362}
363
364TypeResult Sema::ActOnPackExpansion(ParsedType Type,
365 SourceLocation EllipsisLoc) {
366 TypeSourceInfo *TSInfo;
367 GetTypeFromParser(Type, &TSInfo);
368 if (!TSInfo)
369 return true;
370
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000371 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc,
372 llvm::Optional<unsigned>());
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000373 if (!TSResult)
374 return true;
375
376 return CreateParsedType(TSResult->getType(), TSResult);
377}
378
379TypeSourceInfo *Sema::CheckPackExpansion(TypeSourceInfo *Pattern,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000380 SourceLocation EllipsisLoc,
381 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +0000382 // Create the pack expansion type and source-location information.
Douglas Gregor822d0302011-01-12 17:07:58 +0000383 QualType Result = CheckPackExpansion(Pattern->getType(),
384 Pattern->getTypeLoc().getSourceRange(),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000385 EllipsisLoc, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000386 if (Result.isNull())
387 return 0;
388
Douglas Gregord2fa7662010-12-20 02:24:11 +0000389 TypeSourceInfo *TSResult = Context.CreateTypeSourceInfo(Result);
390 PackExpansionTypeLoc TL = cast<PackExpansionTypeLoc>(TSResult->getTypeLoc());
391 TL.setEllipsisLoc(EllipsisLoc);
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000392
Douglas Gregord2fa7662010-12-20 02:24:11 +0000393 // Copy over the source-location information from the type.
394 memcpy(TL.getNextTypeLoc().getOpaqueData(),
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000395 Pattern->getTypeLoc().getOpaqueData(),
396 Pattern->getTypeLoc().getFullDataSize());
397 return TSResult;
Douglas Gregord2fa7662010-12-20 02:24:11 +0000398}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000399
Douglas Gregor822d0302011-01-12 17:07:58 +0000400QualType Sema::CheckPackExpansion(QualType Pattern,
401 SourceRange PatternRange,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000402 SourceLocation EllipsisLoc,
403 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor822d0302011-01-12 17:07:58 +0000404 // C++0x [temp.variadic]p5:
405 // The pattern of a pack expansion shall name one or more
406 // parameter packs that are not expanded by a nested pack
407 // expansion.
408 if (!Pattern->containsUnexpandedParameterPack()) {
409 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
410 << PatternRange;
411 return QualType();
412 }
413
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000414 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000415}
416
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000417ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
Douglas Gregorb8840002011-01-14 21:20:45 +0000418 return CheckPackExpansion(Pattern, EllipsisLoc, llvm::Optional<unsigned>());
419}
420
421ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
422 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000423 if (!Pattern)
424 return ExprError();
425
426 // C++0x [temp.variadic]p5:
427 // The pattern of a pack expansion shall name one or more
428 // parameter packs that are not expanded by a nested pack
429 // expansion.
430 if (!Pattern->containsUnexpandedParameterPack()) {
431 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
432 << Pattern->getSourceRange();
433 return ExprError();
434 }
435
436 // Create the pack expansion expression and source-location information.
437 return Owned(new (Context) PackExpansionExpr(Context.DependentTy, Pattern,
Douglas Gregorb8840002011-01-14 21:20:45 +0000438 EllipsisLoc, NumExpansions));
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000439}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000440
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000441/// \brief Retrieve the depth and index of a parameter pack.
442static std::pair<unsigned, unsigned>
443getDepthAndIndex(NamedDecl *ND) {
444 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
445 return std::make_pair(TTP->getDepth(), TTP->getIndex());
446
447 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
448 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
449
450 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
451 return std::make_pair(TTP->getDepth(), TTP->getIndex());
452}
453
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000454bool Sema::CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
455 SourceRange PatternRange,
456 const UnexpandedParameterPack *Unexpanded,
457 unsigned NumUnexpanded,
458 const MultiLevelTemplateArgumentList &TemplateArgs,
459 bool &ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000460 bool &RetainExpansion,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000461 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000462 ShouldExpand = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000463 RetainExpansion = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000464 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
465 bool HaveFirstPack = false;
466
467 for (unsigned I = 0; I != NumUnexpanded; ++I) {
468 // Compute the depth and index for this parameter pack.
469 unsigned Depth;
470 unsigned Index;
471 IdentifierInfo *Name;
Douglas Gregorf3010112011-01-07 16:43:16 +0000472 bool IsFunctionParameterPack = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000473
474 if (const TemplateTypeParmType *TTP
475 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
476 Depth = TTP->getDepth();
477 Index = TTP->getIndex();
478 Name = TTP->getName();
479 } else {
480 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000481 if (isa<ParmVarDecl>(ND))
Douglas Gregorf3010112011-01-07 16:43:16 +0000482 IsFunctionParameterPack = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000483 else
484 llvm::tie(Depth, Index) = getDepthAndIndex(ND);
485
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000486 Name = ND->getIdentifier();
487 }
488
Douglas Gregorf3010112011-01-07 16:43:16 +0000489 // Determine the size of this argument pack.
490 unsigned NewPackSize;
491 if (IsFunctionParameterPack) {
492 // Figure out whether we're instantiating to an argument pack or not.
493 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
494
495 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
496 = CurrentInstantiationScope->findInstantiationOf(
497 Unexpanded[I].first.get<NamedDecl *>());
498 if (Instantiation &&
499 Instantiation->is<DeclArgumentPack *>()) {
500 // We could expand this function parameter pack.
501 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
502 } else {
503 // We can't expand this function parameter pack, so we can't expand
504 // the pack expansion.
505 ShouldExpand = false;
506 continue;
507 }
508 } else {
509 // If we don't have a template argument at this depth/index, then we
510 // cannot expand the pack expansion. Make a note of this, but we still
511 // want to check any parameter packs we *do* have arguments for.
512 if (Depth >= TemplateArgs.getNumLevels() ||
513 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
514 ShouldExpand = false;
515 continue;
516 }
517
518 // Determine the size of the argument pack.
519 NewPackSize = TemplateArgs(Depth, Index).pack_size();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000520 }
521
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000522 // C++0x [temp.arg.explicit]p9:
523 // Template argument deduction can extend the sequence of template
524 // arguments corresponding to a template parameter pack, even when the
525 // sequence contains explicitly specified template arguments.
526 if (NamedDecl *PartialPack
527 = CurrentInstantiationScope->getPartiallySubstitutedPack()) {
528 unsigned PartialDepth, PartialIndex;
529 llvm::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
530 if (PartialDepth == Depth && PartialIndex == Index)
531 RetainExpansion = true;
532 }
533
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000534 if (!NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000535 // The is the first pack we've seen for which we have an argument.
536 // Record it.
537 NumExpansions = NewPackSize;
538 FirstPack.first = Name;
539 FirstPack.second = Unexpanded[I].second;
540 HaveFirstPack = true;
541 continue;
542 }
543
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000544 if (NewPackSize != *NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000545 // C++0x [temp.variadic]p5:
546 // All of the parameter packs expanded by a pack expansion shall have
547 // the same number of arguments specified.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000548 if (HaveFirstPack)
549 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
550 << FirstPack.first << Name << *NumExpansions << NewPackSize
551 << SourceRange(FirstPack.second) << SourceRange(Unexpanded[I].second);
552 else
553 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
554 << Name << *NumExpansions << NewPackSize
555 << SourceRange(Unexpanded[I].second);
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000556 return true;
557 }
558 }
559
560 return false;
561}
Douglas Gregor27b4c162010-12-23 22:44:42 +0000562
Douglas Gregor5cde3862011-01-11 03:14:20 +0000563unsigned Sema::getNumArgumentsInExpansion(QualType T,
564 const MultiLevelTemplateArgumentList &TemplateArgs) {
565 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
566 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
567 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
568
569 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
570 // Compute the depth and index for this parameter pack.
571 unsigned Depth;
572 unsigned Index;
573
574 if (const TemplateTypeParmType *TTP
575 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
576 Depth = TTP->getDepth();
577 Index = TTP->getIndex();
578 } else {
579 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
580 if (isa<ParmVarDecl>(ND)) {
581 // Function parameter pack.
582 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
583
584 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
585 = CurrentInstantiationScope->findInstantiationOf(
586 Unexpanded[I].first.get<NamedDecl *>());
587 if (Instantiation && Instantiation->is<DeclArgumentPack *>())
588 return Instantiation->get<DeclArgumentPack *>()->size();
589
590 continue;
591 }
592
593 llvm::tie(Depth, Index) = getDepthAndIndex(ND);
594 }
595 if (Depth >= TemplateArgs.getNumLevels() ||
596 !TemplateArgs.hasTemplateArgument(Depth, Index))
597 continue;
598
599 // Determine the size of the argument pack.
600 return TemplateArgs(Depth, Index).pack_size();
601 }
602
603 llvm_unreachable("No unexpanded parameter packs in type expansion.");
604 return 0;
605}
606
Douglas Gregor27b4c162010-12-23 22:44:42 +0000607bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
608 const DeclSpec &DS = D.getDeclSpec();
609 switch (DS.getTypeSpecType()) {
610 case TST_typename:
611 case TST_typeofType: {
612 QualType T = DS.getRepAsType().get();
613 if (!T.isNull() && T->containsUnexpandedParameterPack())
614 return true;
615 break;
616 }
617
618 case TST_typeofExpr:
619 case TST_decltype:
620 if (DS.getRepAsExpr() &&
621 DS.getRepAsExpr()->containsUnexpandedParameterPack())
622 return true;
623 break;
624
625 case TST_unspecified:
626 case TST_void:
627 case TST_char:
628 case TST_wchar:
629 case TST_char16:
630 case TST_char32:
631 case TST_int:
632 case TST_float:
633 case TST_double:
634 case TST_bool:
635 case TST_decimal32:
636 case TST_decimal64:
637 case TST_decimal128:
638 case TST_enum:
639 case TST_union:
640 case TST_struct:
641 case TST_class:
642 case TST_auto:
643 case TST_error:
644 break;
645 }
646
647 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
648 const DeclaratorChunk &Chunk = D.getTypeObject(I);
649 switch (Chunk.Kind) {
650 case DeclaratorChunk::Pointer:
651 case DeclaratorChunk::Reference:
652 case DeclaratorChunk::Paren:
653 // These declarator chunks cannot contain any parameter packs.
654 break;
655
656 case DeclaratorChunk::Array:
657 case DeclaratorChunk::Function:
658 case DeclaratorChunk::BlockPointer:
659 // Syntactically, these kinds of declarator chunks all come after the
660 // declarator-id (conceptually), so the parser should not invoke this
661 // routine at this time.
662 llvm_unreachable("Could not have seen this kind of declarator chunk");
663 break;
664
665 case DeclaratorChunk::MemberPointer:
666 if (Chunk.Mem.Scope().getScopeRep() &&
667 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
668 return true;
669 break;
670 }
671 }
672
673 return false;
674}
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000675
676/// \brief Called when an expression computing the size of a parameter pack
677/// is parsed.
678///
679/// \code
680/// template<typename ...Types> struct count {
681/// static const unsigned value = sizeof...(Types);
682/// };
683/// \endcode
684///
685//
686/// \param OpLoc The location of the "sizeof" keyword.
687/// \param Name The name of the parameter pack whose size will be determined.
688/// \param NameLoc The source location of the name of the parameter pack.
689/// \param RParenLoc The location of the closing parentheses.
690ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
691 SourceLocation OpLoc,
692 IdentifierInfo &Name,
693 SourceLocation NameLoc,
694 SourceLocation RParenLoc) {
695 // C++0x [expr.sizeof]p5:
696 // The identifier in a sizeof... expression shall name a parameter pack.
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000697 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
698 LookupName(R, S);
699
700 NamedDecl *ParameterPack = 0;
701 switch (R.getResultKind()) {
702 case LookupResult::Found:
703 ParameterPack = R.getFoundDecl();
704 break;
705
706 case LookupResult::NotFound:
707 case LookupResult::NotFoundInCurrentInstantiation:
708 if (DeclarationName CorrectedName = CorrectTypo(R, S, 0, 0, false,
709 CTC_NoKeywords)) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000710 if (NamedDecl *CorrectedResult = R.getAsSingle<NamedDecl>())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000711 if (CorrectedResult->isParameterPack()) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000712 ParameterPack = CorrectedResult;
713 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name_suggest)
714 << &Name << CorrectedName
715 << FixItHint::CreateReplacement(NameLoc,
716 CorrectedName.getAsString());
717 Diag(ParameterPack->getLocation(), diag::note_parameter_pack_here)
718 << CorrectedName;
719 }
720 }
721
722 case LookupResult::FoundOverloaded:
723 case LookupResult::FoundUnresolvedValue:
724 break;
725
726 case LookupResult::Ambiguous:
727 DiagnoseAmbiguousLookup(R);
728 return ExprError();
729 }
730
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000731 if (!ParameterPack || !ParameterPack->isParameterPack()) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000732 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
733 << &Name;
734 return ExprError();
735 }
736
737 return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc,
738 ParameterPack, NameLoc, RParenLoc);
739}