1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
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 parsing of C++ templates.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 using namespace clang;
23
24 /// \brief Parse a template declaration, explicit instantiation, or
25 /// explicit specialization.
26 Decl *
ParseDeclarationStartingWithTemplate(unsigned Context,SourceLocation & DeclEnd,AccessSpecifier AS,AttributeList * AccessAttrs)27 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
29 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
31 ObjCDeclContextSwitch ObjCDC(*this);
32
33 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
34 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
37 }
38 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
40 }
41
42 /// \brief RAII class that manages the template parameter depth.
43 namespace {
44 class TemplateParameterDepthCounter {
45 unsigned &Depth;
46 unsigned AddedLevels;
47
48 public:
TemplateParameterDepthCounter(unsigned & Depth)49 explicit TemplateParameterDepthCounter(unsigned &Depth)
50 : Depth(Depth), AddedLevels(0) { }
51
~TemplateParameterDepthCounter()52 ~TemplateParameterDepthCounter() {
53 Depth -= AddedLevels;
54 }
55
operator ++()56 void operator++() {
57 ++Depth;
58 ++AddedLevels;
59 }
60
operator unsigned() const61 operator unsigned() const { return Depth; }
62 };
63 }
64
65 /// \brief Parse a template declaration or an explicit specialization.
66 ///
67 /// Template declarations include one or more template parameter lists
68 /// and either the function or class template declaration. Explicit
69 /// specializations contain one or more 'template < >' prefixes
70 /// followed by a (possibly templated) declaration. Since the
71 /// syntactic form of both features is nearly identical, we parse all
72 /// of the template headers together and let semantic analysis sort
73 /// the declarations from the explicit specializations.
74 ///
75 /// template-declaration: [C++ temp]
76 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
77 ///
78 /// explicit-specialization: [ C++ temp.expl.spec]
79 /// 'template' '<' '>' declaration
80 Decl *
ParseTemplateDeclarationOrSpecialization(unsigned Context,SourceLocation & DeclEnd,AccessSpecifier AS,AttributeList * AccessAttrs)81 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
82 SourceLocation &DeclEnd,
83 AccessSpecifier AS,
84 AttributeList *AccessAttrs) {
85 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
86 "Token does not start a template declaration.");
87
88 // Enter template-parameter scope.
89 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
90
91 // Tell the action that names should be checked in the context of
92 // the declaration to come.
93 ParsingDeclRAIIObject
94 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
95
96 // Parse multiple levels of template headers within this template
97 // parameter scope, e.g.,
98 //
99 // template<typename T>
100 // template<typename U>
101 // class A<T>::B { ... };
102 //
103 // We parse multiple levels non-recursively so that we can build a
104 // single data structure containing all of the template parameter
105 // lists to easily differentiate between the case above and:
106 //
107 // template<typename T>
108 // class A {
109 // template<typename U> class B;
110 // };
111 //
112 // In the first case, the action for declaring A<T>::B receives
113 // both template parameter lists. In the second case, the action for
114 // defining A<T>::B receives just the inner template parameter list
115 // (and retrieves the outer template parameter list from its
116 // context).
117 bool isSpecialization = true;
118 bool LastParamListWasEmpty = false;
119 TemplateParameterLists ParamLists;
120 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
121 do {
122 // Consume the 'export', if any.
123 SourceLocation ExportLoc;
124 if (Tok.is(tok::kw_export)) {
125 ExportLoc = ConsumeToken();
126 }
127
128 // Consume the 'template', which should be here.
129 SourceLocation TemplateLoc;
130 if (Tok.is(tok::kw_template)) {
131 TemplateLoc = ConsumeToken();
132 } else {
133 Diag(Tok.getLocation(), diag::err_expected_template);
134 return 0;
135 }
136
137 // Parse the '<' template-parameter-list '>'
138 SourceLocation LAngleLoc, RAngleLoc;
139 SmallVector<Decl*, 4> TemplateParams;
140 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
141 RAngleLoc)) {
142 // Skip until the semi-colon or a }.
143 SkipUntil(tok::r_brace, true, true);
144 if (Tok.is(tok::semi))
145 ConsumeToken();
146 return 0;
147 }
148
149 ParamLists.push_back(
150 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
151 TemplateLoc, LAngleLoc,
152 TemplateParams.data(),
153 TemplateParams.size(), RAngleLoc));
154
155 if (!TemplateParams.empty()) {
156 isSpecialization = false;
157 ++Depth;
158 } else {
159 LastParamListWasEmpty = true;
160 }
161 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
162
163 // Parse the actual template declaration.
164 return ParseSingleDeclarationAfterTemplate(Context,
165 ParsedTemplateInfo(&ParamLists,
166 isSpecialization,
167 LastParamListWasEmpty),
168 ParsingTemplateParams,
169 DeclEnd, AS, AccessAttrs);
170 }
171
172 /// \brief Parse a single declaration that declares a template,
173 /// template specialization, or explicit instantiation of a template.
174 ///
175 /// \param DeclEnd will receive the source location of the last token
176 /// within this declaration.
177 ///
178 /// \param AS the access specifier associated with this
179 /// declaration. Will be AS_none for namespace-scope declarations.
180 ///
181 /// \returns the new declaration.
182 Decl *
ParseSingleDeclarationAfterTemplate(unsigned Context,const ParsedTemplateInfo & TemplateInfo,ParsingDeclRAIIObject & DiagsFromTParams,SourceLocation & DeclEnd,AccessSpecifier AS,AttributeList * AccessAttrs)183 Parser::ParseSingleDeclarationAfterTemplate(
184 unsigned Context,
185 const ParsedTemplateInfo &TemplateInfo,
186 ParsingDeclRAIIObject &DiagsFromTParams,
187 SourceLocation &DeclEnd,
188 AccessSpecifier AS,
189 AttributeList *AccessAttrs) {
190 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
191 "Template information required");
192
193 if (Context == Declarator::MemberContext) {
194 // We are parsing a member template.
195 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
196 &DiagsFromTParams);
197 return 0;
198 }
199
200 ParsedAttributesWithRange prefixAttrs(AttrFactory);
201 MaybeParseCXX11Attributes(prefixAttrs);
202
203 if (Tok.is(tok::kw_using))
204 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
205 prefixAttrs);
206
207 // Parse the declaration specifiers, stealing any diagnostics from
208 // the template parameters.
209 ParsingDeclSpec DS(*this, &DiagsFromTParams);
210
211 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
212 getDeclSpecContextFromDeclaratorContext(Context));
213
214 if (Tok.is(tok::semi)) {
215 ProhibitAttributes(prefixAttrs);
216 DeclEnd = ConsumeToken();
217 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
218 getCurScope(), AS, DS,
219 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
220 : MultiTemplateParamsArg(),
221 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
222 DS.complete(Decl);
223 return Decl;
224 }
225
226 // Move the attributes from the prefix into the DS.
227 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
228 ProhibitAttributes(prefixAttrs);
229 else
230 DS.takeAttributesFrom(prefixAttrs);
231
232 // Parse the declarator.
233 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
234 ParseDeclarator(DeclaratorInfo);
235 // Error parsing the declarator?
236 if (!DeclaratorInfo.hasName()) {
237 // If so, skip until the semi-colon or a }.
238 SkipUntil(tok::r_brace, true, true);
239 if (Tok.is(tok::semi))
240 ConsumeToken();
241 return 0;
242 }
243
244 LateParsedAttrList LateParsedAttrs(true);
245 if (DeclaratorInfo.isFunctionDeclarator())
246 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
247
248 if (DeclaratorInfo.isFunctionDeclarator() &&
249 isStartOfFunctionDefinition(DeclaratorInfo)) {
250 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
251 // Recover by ignoring the 'typedef'. This was probably supposed to be
252 // the 'typename' keyword, which we should have already suggested adding
253 // if it's appropriate.
254 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
255 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
256 DS.ClearStorageClassSpecs();
257 }
258 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
259 &LateParsedAttrs);
260 }
261
262 // Parse this declaration.
263 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
264 TemplateInfo);
265
266 if (Tok.is(tok::comma)) {
267 Diag(Tok, diag::err_multiple_template_declarators)
268 << (int)TemplateInfo.Kind;
269 SkipUntil(tok::semi, true, false);
270 return ThisDecl;
271 }
272
273 // Eat the semi colon after the declaration.
274 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
275 if (LateParsedAttrs.size() > 0)
276 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
277 DeclaratorInfo.complete(ThisDecl);
278 return ThisDecl;
279 }
280
281 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
282 /// angle brackets. Depth is the depth of this template-parameter-list, which
283 /// is the number of template headers directly enclosing this template header.
284 /// TemplateParams is the current list of template parameters we're building.
285 /// The template parameter we parse will be added to this list. LAngleLoc and
286 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
287 /// that enclose this template parameter list.
288 ///
289 /// \returns true if an error occurred, false otherwise.
ParseTemplateParameters(unsigned Depth,SmallVectorImpl<Decl * > & TemplateParams,SourceLocation & LAngleLoc,SourceLocation & RAngleLoc)290 bool Parser::ParseTemplateParameters(unsigned Depth,
291 SmallVectorImpl<Decl*> &TemplateParams,
292 SourceLocation &LAngleLoc,
293 SourceLocation &RAngleLoc) {
294 // Get the template parameter list.
295 if (!Tok.is(tok::less)) {
296 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
297 return true;
298 }
299 LAngleLoc = ConsumeToken();
300
301 // Try to parse the template parameter list.
302 bool Failed = false;
303 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
304 Failed = ParseTemplateParameterList(Depth, TemplateParams);
305
306 if (Tok.is(tok::greatergreater)) {
307 // No diagnostic required here: a template-parameter-list can only be
308 // followed by a declaration or, for a template template parameter, the
309 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
310 // This matters for elegant diagnosis of:
311 // template<template<typename>> struct S;
312 Tok.setKind(tok::greater);
313 RAngleLoc = Tok.getLocation();
314 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
315 } else if (Tok.is(tok::greater))
316 RAngleLoc = ConsumeToken();
317 else if (Failed) {
318 Diag(Tok.getLocation(), diag::err_expected_greater);
319 return true;
320 }
321 return false;
322 }
323
324 /// ParseTemplateParameterList - Parse a template parameter list. If
325 /// the parsing fails badly (i.e., closing bracket was left out), this
326 /// will try to put the token stream in a reasonable position (closing
327 /// a statement, etc.) and return false.
328 ///
329 /// template-parameter-list: [C++ temp]
330 /// template-parameter
331 /// template-parameter-list ',' template-parameter
332 bool
ParseTemplateParameterList(unsigned Depth,SmallVectorImpl<Decl * > & TemplateParams)333 Parser::ParseTemplateParameterList(unsigned Depth,
334 SmallVectorImpl<Decl*> &TemplateParams) {
335 while (1) {
336 if (Decl *TmpParam
337 = ParseTemplateParameter(Depth, TemplateParams.size())) {
338 TemplateParams.push_back(TmpParam);
339 } else {
340 // If we failed to parse a template parameter, skip until we find
341 // a comma or closing brace.
342 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
343 }
344
345 // Did we find a comma or the end of the template parameter list?
346 if (Tok.is(tok::comma)) {
347 ConsumeToken();
348 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
349 // Don't consume this... that's done by template parser.
350 break;
351 } else {
352 // Somebody probably forgot to close the template. Skip ahead and
353 // try to get out of the expression. This error is currently
354 // subsumed by whatever goes on in ParseTemplateParameter.
355 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
356 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
357 return false;
358 }
359 }
360 return true;
361 }
362
363 /// \brief Determine whether the parser is at the start of a template
364 /// type parameter.
isStartOfTemplateTypeParameter()365 bool Parser::isStartOfTemplateTypeParameter() {
366 if (Tok.is(tok::kw_class)) {
367 // "class" may be the start of an elaborated-type-specifier or a
368 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
369 switch (NextToken().getKind()) {
370 case tok::equal:
371 case tok::comma:
372 case tok::greater:
373 case tok::greatergreater:
374 case tok::ellipsis:
375 return true;
376
377 case tok::identifier:
378 // This may be either a type-parameter or an elaborated-type-specifier.
379 // We have to look further.
380 break;
381
382 default:
383 return false;
384 }
385
386 switch (GetLookAheadToken(2).getKind()) {
387 case tok::equal:
388 case tok::comma:
389 case tok::greater:
390 case tok::greatergreater:
391 return true;
392
393 default:
394 return false;
395 }
396 }
397
398 if (Tok.isNot(tok::kw_typename))
399 return false;
400
401 // C++ [temp.param]p2:
402 // There is no semantic difference between class and typename in a
403 // template-parameter. typename followed by an unqualified-id
404 // names a template type parameter. typename followed by a
405 // qualified-id denotes the type in a non-type
406 // parameter-declaration.
407 Token Next = NextToken();
408
409 // If we have an identifier, skip over it.
410 if (Next.getKind() == tok::identifier)
411 Next = GetLookAheadToken(2);
412
413 switch (Next.getKind()) {
414 case tok::equal:
415 case tok::comma:
416 case tok::greater:
417 case tok::greatergreater:
418 case tok::ellipsis:
419 return true;
420
421 default:
422 return false;
423 }
424 }
425
426 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
427 ///
428 /// template-parameter: [C++ temp.param]
429 /// type-parameter
430 /// parameter-declaration
431 ///
432 /// type-parameter: (see below)
433 /// 'class' ...[opt] identifier[opt]
434 /// 'class' identifier[opt] '=' type-id
435 /// 'typename' ...[opt] identifier[opt]
436 /// 'typename' identifier[opt] '=' type-id
437 /// 'template' '<' template-parameter-list '>'
438 /// 'class' ...[opt] identifier[opt]
439 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
440 /// = id-expression
ParseTemplateParameter(unsigned Depth,unsigned Position)441 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
442 if (isStartOfTemplateTypeParameter())
443 return ParseTypeParameter(Depth, Position);
444
445 if (Tok.is(tok::kw_template))
446 return ParseTemplateTemplateParameter(Depth, Position);
447
448 // If it's none of the above, then it must be a parameter declaration.
449 // NOTE: This will pick up errors in the closure of the template parameter
450 // list (e.g., template < ; Check here to implement >> style closures.
451 return ParseNonTypeTemplateParameter(Depth, Position);
452 }
453
454 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
455 /// Other kinds of template parameters are parsed in
456 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
457 ///
458 /// type-parameter: [C++ temp.param]
459 /// 'class' ...[opt][C++0x] identifier[opt]
460 /// 'class' identifier[opt] '=' type-id
461 /// 'typename' ...[opt][C++0x] identifier[opt]
462 /// 'typename' identifier[opt] '=' type-id
ParseTypeParameter(unsigned Depth,unsigned Position)463 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
464 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
465 "A type-parameter starts with 'class' or 'typename'");
466
467 // Consume the 'class' or 'typename' keyword.
468 bool TypenameKeyword = Tok.is(tok::kw_typename);
469 SourceLocation KeyLoc = ConsumeToken();
470
471 // Grab the ellipsis (if given).
472 bool Ellipsis = false;
473 SourceLocation EllipsisLoc;
474 if (Tok.is(tok::ellipsis)) {
475 Ellipsis = true;
476 EllipsisLoc = ConsumeToken();
477
478 Diag(EllipsisLoc,
479 getLangOpts().CPlusPlus11
480 ? diag::warn_cxx98_compat_variadic_templates
481 : diag::ext_variadic_templates);
482 }
483
484 // Grab the template parameter name (if given)
485 SourceLocation NameLoc;
486 IdentifierInfo* ParamName = 0;
487 if (Tok.is(tok::identifier)) {
488 ParamName = Tok.getIdentifierInfo();
489 NameLoc = ConsumeToken();
490 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
491 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
492 // Unnamed template parameter. Don't have to do anything here, just
493 // don't consume this token.
494 } else {
495 Diag(Tok.getLocation(), diag::err_expected_ident);
496 return 0;
497 }
498
499 // Grab a default argument (if available).
500 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
501 // we introduce the type parameter into the local scope.
502 SourceLocation EqualLoc;
503 ParsedType DefaultArg;
504 if (Tok.is(tok::equal)) {
505 EqualLoc = ConsumeToken();
506 DefaultArg = ParseTypeName(/*Range=*/0,
507 Declarator::TemplateTypeArgContext).get();
508 }
509
510 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
511 EllipsisLoc, KeyLoc, ParamName, NameLoc,
512 Depth, Position, EqualLoc, DefaultArg);
513 }
514
515 /// ParseTemplateTemplateParameter - Handle the parsing of template
516 /// template parameters.
517 ///
518 /// type-parameter: [C++ temp.param]
519 /// 'template' '<' template-parameter-list '>' 'class'
520 /// ...[opt] identifier[opt]
521 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
522 /// = id-expression
523 Decl *
ParseTemplateTemplateParameter(unsigned Depth,unsigned Position)524 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
525 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
526
527 // Handle the template <...> part.
528 SourceLocation TemplateLoc = ConsumeToken();
529 SmallVector<Decl*,8> TemplateParams;
530 SourceLocation LAngleLoc, RAngleLoc;
531 {
532 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
533 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
534 RAngleLoc)) {
535 return 0;
536 }
537 }
538
539 // Generate a meaningful error if the user forgot to put class before the
540 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
541 // or greater appear immediately or after 'typename' or 'struct'. In the
542 // latter case, replace the keyword with 'class'.
543 if (!Tok.is(tok::kw_class)) {
544 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
545 const Token& Next = Replace ? NextToken() : Tok;
546 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
547 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
548 Next.is(tok::ellipsis))
549 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
550 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
551 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
552 else
553 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
554
555 if (Replace)
556 ConsumeToken();
557 } else
558 ConsumeToken();
559
560 // Parse the ellipsis, if given.
561 SourceLocation EllipsisLoc;
562 if (Tok.is(tok::ellipsis)) {
563 EllipsisLoc = ConsumeToken();
564
565 Diag(EllipsisLoc,
566 getLangOpts().CPlusPlus11
567 ? diag::warn_cxx98_compat_variadic_templates
568 : diag::ext_variadic_templates);
569 }
570
571 // Get the identifier, if given.
572 SourceLocation NameLoc;
573 IdentifierInfo* ParamName = 0;
574 if (Tok.is(tok::identifier)) {
575 ParamName = Tok.getIdentifierInfo();
576 NameLoc = ConsumeToken();
577 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
578 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
579 // Unnamed template parameter. Don't have to do anything here, just
580 // don't consume this token.
581 } else {
582 Diag(Tok.getLocation(), diag::err_expected_ident);
583 return 0;
584 }
585
586 TemplateParameterList *ParamList =
587 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
588 TemplateLoc, LAngleLoc,
589 TemplateParams.data(),
590 TemplateParams.size(),
591 RAngleLoc);
592
593 // Grab a default argument (if available).
594 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
595 // we introduce the template parameter into the local scope.
596 SourceLocation EqualLoc;
597 ParsedTemplateArgument DefaultArg;
598 if (Tok.is(tok::equal)) {
599 EqualLoc = ConsumeToken();
600 DefaultArg = ParseTemplateTemplateArgument();
601 if (DefaultArg.isInvalid()) {
602 Diag(Tok.getLocation(),
603 diag::err_default_template_template_parameter_not_template);
604 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
605 }
606 }
607
608 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
609 ParamList, EllipsisLoc,
610 ParamName, NameLoc, Depth,
611 Position, EqualLoc, DefaultArg);
612 }
613
614 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
615 /// template parameters (e.g., in "template<int Size> class array;").
616 ///
617 /// template-parameter:
618 /// ...
619 /// parameter-declaration
620 Decl *
ParseNonTypeTemplateParameter(unsigned Depth,unsigned Position)621 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
622 // Parse the declaration-specifiers (i.e., the type).
623 // FIXME: The type should probably be restricted in some way... Not all
624 // declarators (parts of declarators?) are accepted for parameters.
625 DeclSpec DS(AttrFactory);
626 ParseDeclarationSpecifiers(DS);
627
628 // Parse this as a typename.
629 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
630 ParseDeclarator(ParamDecl);
631 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
632 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
633 return 0;
634 }
635
636 // If there is a default value, parse it.
637 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
638 // we introduce the template parameter into the local scope.
639 SourceLocation EqualLoc;
640 ExprResult DefaultArg;
641 if (Tok.is(tok::equal)) {
642 EqualLoc = ConsumeToken();
643
644 // C++ [temp.param]p15:
645 // When parsing a default template-argument for a non-type
646 // template-parameter, the first non-nested > is taken as the
647 // end of the template-parameter-list rather than a greater-than
648 // operator.
649 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
650 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
651
652 DefaultArg = ParseAssignmentExpression();
653 if (DefaultArg.isInvalid())
654 SkipUntil(tok::comma, tok::greater, true, true);
655 }
656
657 // Create the parameter.
658 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
659 Depth, Position, EqualLoc,
660 DefaultArg.take());
661 }
662
663 /// \brief Parses a '>' at the end of a template list.
664 ///
665 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
666 /// to determine if these tokens were supposed to be a '>' followed by
667 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
668 ///
669 /// \param RAngleLoc the location of the consumed '>'.
670 ///
671 /// \param ConsumeLastToken if true, the '>' is not consumed.
ParseGreaterThanInTemplateList(SourceLocation & RAngleLoc,bool ConsumeLastToken)672 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
673 bool ConsumeLastToken) {
674 // What will be left once we've consumed the '>'.
675 tok::TokenKind RemainingToken;
676 const char *ReplacementStr = "> >";
677
678 switch (Tok.getKind()) {
679 default:
680 Diag(Tok.getLocation(), diag::err_expected_greater);
681 return true;
682
683 case tok::greater:
684 // Determine the location of the '>' token. Only consume this token
685 // if the caller asked us to.
686 RAngleLoc = Tok.getLocation();
687 if (ConsumeLastToken)
688 ConsumeToken();
689 return false;
690
691 case tok::greatergreater:
692 RemainingToken = tok::greater;
693 break;
694
695 case tok::greatergreatergreater:
696 RemainingToken = tok::greatergreater;
697 break;
698
699 case tok::greaterequal:
700 RemainingToken = tok::equal;
701 ReplacementStr = "> =";
702 break;
703
704 case tok::greatergreaterequal:
705 RemainingToken = tok::greaterequal;
706 break;
707 }
708
709 // This template-id is terminated by a token which starts with a '>'. Outside
710 // C++11, this is now error recovery, and in C++11, this is error recovery if
711 // the token isn't '>>'.
712
713 RAngleLoc = Tok.getLocation();
714
715 // The source range of the '>>' or '>=' at the start of the token.
716 CharSourceRange ReplacementRange =
717 CharSourceRange::getCharRange(RAngleLoc,
718 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
719 getLangOpts()));
720
721 // A hint to put a space between the '>>'s. In order to make the hint as
722 // clear as possible, we include the characters either side of the space in
723 // the replacement, rather than just inserting a space at SecondCharLoc.
724 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
725 ReplacementStr);
726
727 // A hint to put another space after the token, if it would otherwise be
728 // lexed differently.
729 FixItHint Hint2;
730 Token Next = NextToken();
731 if ((RemainingToken == tok::greater ||
732 RemainingToken == tok::greatergreater) &&
733 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
734 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
735 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
736 Next.is(tok::equalequal)) &&
737 areTokensAdjacent(Tok, Next))
738 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
739
740 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
741 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
742 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
743 else if (Tok.is(tok::greaterequal))
744 DiagId = diag::err_right_angle_bracket_equal_needs_space;
745 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
746
747 // Strip the initial '>' from the token.
748 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
749 areTokensAdjacent(Tok, Next)) {
750 // Join two adjacent '=' tokens into one, for cases like:
751 // void (*p)() = f<int>;
752 // return f<int>==p;
753 ConsumeToken();
754 Tok.setKind(tok::equalequal);
755 Tok.setLength(Tok.getLength() + 1);
756 } else {
757 Tok.setKind(RemainingToken);
758 Tok.setLength(Tok.getLength() - 1);
759 }
760 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
761 PP.getSourceManager(),
762 getLangOpts()));
763
764 if (!ConsumeLastToken) {
765 // Since we're not supposed to consume the '>' token, we need to push
766 // this token and revert the current token back to the '>'.
767 PP.EnterToken(Tok);
768 Tok.setKind(tok::greater);
769 Tok.setLength(1);
770 Tok.setLocation(RAngleLoc);
771 }
772 return false;
773 }
774
775
776 /// \brief Parses a template-id that after the template name has
777 /// already been parsed.
778 ///
779 /// This routine takes care of parsing the enclosed template argument
780 /// list ('<' template-parameter-list [opt] '>') and placing the
781 /// results into a form that can be transferred to semantic analysis.
782 ///
783 /// \param Template the template declaration produced by isTemplateName
784 ///
785 /// \param TemplateNameLoc the source location of the template name
786 ///
787 /// \param SS if non-NULL, the nested-name-specifier preceding the
788 /// template name.
789 ///
790 /// \param ConsumeLastToken if true, then we will consume the last
791 /// token that forms the template-id. Otherwise, we will leave the
792 /// last token in the stream (e.g., so that it can be replaced with an
793 /// annotation token).
794 bool
ParseTemplateIdAfterTemplateName(TemplateTy Template,SourceLocation TemplateNameLoc,const CXXScopeSpec & SS,bool ConsumeLastToken,SourceLocation & LAngleLoc,TemplateArgList & TemplateArgs,SourceLocation & RAngleLoc)795 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
796 SourceLocation TemplateNameLoc,
797 const CXXScopeSpec &SS,
798 bool ConsumeLastToken,
799 SourceLocation &LAngleLoc,
800 TemplateArgList &TemplateArgs,
801 SourceLocation &RAngleLoc) {
802 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
803
804 // Consume the '<'.
805 LAngleLoc = ConsumeToken();
806
807 // Parse the optional template-argument-list.
808 bool Invalid = false;
809 {
810 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
811 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
812 Invalid = ParseTemplateArgumentList(TemplateArgs);
813
814 if (Invalid) {
815 // Try to find the closing '>'.
816 SkipUntil(tok::greater, true, !ConsumeLastToken);
817
818 return true;
819 }
820 }
821
822 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
823 }
824
825 /// \brief Replace the tokens that form a simple-template-id with an
826 /// annotation token containing the complete template-id.
827 ///
828 /// The first token in the stream must be the name of a template that
829 /// is followed by a '<'. This routine will parse the complete
830 /// simple-template-id and replace the tokens with a single annotation
831 /// token with one of two different kinds: if the template-id names a
832 /// type (and \p AllowTypeAnnotation is true), the annotation token is
833 /// a type annotation that includes the optional nested-name-specifier
834 /// (\p SS). Otherwise, the annotation token is a template-id
835 /// annotation that does not include the optional
836 /// nested-name-specifier.
837 ///
838 /// \param Template the declaration of the template named by the first
839 /// token (an identifier), as returned from \c Action::isTemplateName().
840 ///
841 /// \param TNK the kind of template that \p Template
842 /// refers to, as returned from \c Action::isTemplateName().
843 ///
844 /// \param SS if non-NULL, the nested-name-specifier that precedes
845 /// this template name.
846 ///
847 /// \param TemplateKWLoc if valid, specifies that this template-id
848 /// annotation was preceded by the 'template' keyword and gives the
849 /// location of that keyword. If invalid (the default), then this
850 /// template-id was not preceded by a 'template' keyword.
851 ///
852 /// \param AllowTypeAnnotation if true (the default), then a
853 /// simple-template-id that refers to a class template, template
854 /// template parameter, or other template that produces a type will be
855 /// replaced with a type annotation token. Otherwise, the
856 /// simple-template-id is always replaced with a template-id
857 /// annotation token.
858 ///
859 /// If an unrecoverable parse error occurs and no annotation token can be
860 /// formed, this function returns true.
861 ///
AnnotateTemplateIdToken(TemplateTy Template,TemplateNameKind TNK,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & TemplateName,bool AllowTypeAnnotation)862 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
863 CXXScopeSpec &SS,
864 SourceLocation TemplateKWLoc,
865 UnqualifiedId &TemplateName,
866 bool AllowTypeAnnotation) {
867 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
868 assert(Template && Tok.is(tok::less) &&
869 "Parser isn't at the beginning of a template-id");
870
871 // Consume the template-name.
872 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
873
874 // Parse the enclosed template argument list.
875 SourceLocation LAngleLoc, RAngleLoc;
876 TemplateArgList TemplateArgs;
877 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
878 TemplateNameLoc,
879 SS, false, LAngleLoc,
880 TemplateArgs,
881 RAngleLoc);
882
883 if (Invalid) {
884 // If we failed to parse the template ID but skipped ahead to a >, we're not
885 // going to be able to form a token annotation. Eat the '>' if present.
886 if (Tok.is(tok::greater))
887 ConsumeToken();
888 return true;
889 }
890
891 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
892
893 // Build the annotation token.
894 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
895 TypeResult Type
896 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
897 Template, TemplateNameLoc,
898 LAngleLoc, TemplateArgsPtr, RAngleLoc);
899 if (Type.isInvalid()) {
900 // If we failed to parse the template ID but skipped ahead to a >, we're not
901 // going to be able to form a token annotation. Eat the '>' if present.
902 if (Tok.is(tok::greater))
903 ConsumeToken();
904 return true;
905 }
906
907 Tok.setKind(tok::annot_typename);
908 setTypeAnnotation(Tok, Type.get());
909 if (SS.isNotEmpty())
910 Tok.setLocation(SS.getBeginLoc());
911 else if (TemplateKWLoc.isValid())
912 Tok.setLocation(TemplateKWLoc);
913 else
914 Tok.setLocation(TemplateNameLoc);
915 } else {
916 // Build a template-id annotation token that can be processed
917 // later.
918 Tok.setKind(tok::annot_template_id);
919 TemplateIdAnnotation *TemplateId
920 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
921 TemplateId->TemplateNameLoc = TemplateNameLoc;
922 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
923 TemplateId->Name = TemplateName.Identifier;
924 TemplateId->Operator = OO_None;
925 } else {
926 TemplateId->Name = 0;
927 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
928 }
929 TemplateId->SS = SS;
930 TemplateId->TemplateKWLoc = TemplateKWLoc;
931 TemplateId->Template = Template;
932 TemplateId->Kind = TNK;
933 TemplateId->LAngleLoc = LAngleLoc;
934 TemplateId->RAngleLoc = RAngleLoc;
935 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
936 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
937 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
938 Tok.setAnnotationValue(TemplateId);
939 if (TemplateKWLoc.isValid())
940 Tok.setLocation(TemplateKWLoc);
941 else
942 Tok.setLocation(TemplateNameLoc);
943 }
944
945 // Common fields for the annotation token
946 Tok.setAnnotationEndLoc(RAngleLoc);
947
948 // In case the tokens were cached, have Preprocessor replace them with the
949 // annotation token.
950 PP.AnnotateCachedTokens(Tok);
951 return false;
952 }
953
954 /// \brief Replaces a template-id annotation token with a type
955 /// annotation token.
956 ///
957 /// If there was a failure when forming the type from the template-id,
958 /// a type annotation token will still be created, but will have a
959 /// NULL type pointer to signify an error.
AnnotateTemplateIdTokenAsType()960 void Parser::AnnotateTemplateIdTokenAsType() {
961 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
962
963 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
964 assert((TemplateId->Kind == TNK_Type_template ||
965 TemplateId->Kind == TNK_Dependent_template_name) &&
966 "Only works for type and dependent templates");
967
968 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
969 TemplateId->NumArgs);
970
971 TypeResult Type
972 = Actions.ActOnTemplateIdType(TemplateId->SS,
973 TemplateId->TemplateKWLoc,
974 TemplateId->Template,
975 TemplateId->TemplateNameLoc,
976 TemplateId->LAngleLoc,
977 TemplateArgsPtr,
978 TemplateId->RAngleLoc);
979 // Create the new "type" annotation token.
980 Tok.setKind(tok::annot_typename);
981 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
982 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
983 Tok.setLocation(TemplateId->SS.getBeginLoc());
984 // End location stays the same
985
986 // Replace the template-id annotation token, and possible the scope-specifier
987 // that precedes it, with the typename annotation token.
988 PP.AnnotateCachedTokens(Tok);
989 }
990
991 /// \brief Determine whether the given token can end a template argument.
isEndOfTemplateArgument(Token Tok)992 static bool isEndOfTemplateArgument(Token Tok) {
993 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
994 Tok.is(tok::greatergreater);
995 }
996
997 /// \brief Parse a C++ template template argument.
ParseTemplateTemplateArgument()998 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
999 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1000 !Tok.is(tok::annot_cxxscope))
1001 return ParsedTemplateArgument();
1002
1003 // C++0x [temp.arg.template]p1:
1004 // A template-argument for a template template-parameter shall be the name
1005 // of a class template or an alias template, expressed as id-expression.
1006 //
1007 // We parse an id-expression that refers to a class template or alias
1008 // template. The grammar we parse is:
1009 //
1010 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1011 //
1012 // followed by a token that terminates a template argument, such as ',',
1013 // '>', or (in some cases) '>>'.
1014 CXXScopeSpec SS; // nested-name-specifier, if present
1015 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1016 /*EnteringContext=*/false);
1017
1018 ParsedTemplateArgument Result;
1019 SourceLocation EllipsisLoc;
1020 if (SS.isSet() && Tok.is(tok::kw_template)) {
1021 // Parse the optional 'template' keyword following the
1022 // nested-name-specifier.
1023 SourceLocation TemplateKWLoc = ConsumeToken();
1024
1025 if (Tok.is(tok::identifier)) {
1026 // We appear to have a dependent template name.
1027 UnqualifiedId Name;
1028 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1029 ConsumeToken(); // the identifier
1030
1031 // Parse the ellipsis.
1032 if (Tok.is(tok::ellipsis))
1033 EllipsisLoc = ConsumeToken();
1034
1035 // If the next token signals the end of a template argument,
1036 // then we have a dependent template name that could be a template
1037 // template argument.
1038 TemplateTy Template;
1039 if (isEndOfTemplateArgument(Tok) &&
1040 Actions.ActOnDependentTemplateName(getCurScope(),
1041 SS, TemplateKWLoc, Name,
1042 /*ObjectType=*/ ParsedType(),
1043 /*EnteringContext=*/false,
1044 Template))
1045 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1046 }
1047 } else if (Tok.is(tok::identifier)) {
1048 // We may have a (non-dependent) template name.
1049 TemplateTy Template;
1050 UnqualifiedId Name;
1051 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1052 ConsumeToken(); // the identifier
1053
1054 // Parse the ellipsis.
1055 if (Tok.is(tok::ellipsis))
1056 EllipsisLoc = ConsumeToken();
1057
1058 if (isEndOfTemplateArgument(Tok)) {
1059 bool MemberOfUnknownSpecialization;
1060 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1061 /*hasTemplateKeyword=*/false,
1062 Name,
1063 /*ObjectType=*/ ParsedType(),
1064 /*EnteringContext=*/false,
1065 Template,
1066 MemberOfUnknownSpecialization);
1067 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1068 // We have an id-expression that refers to a class template or
1069 // (C++0x) alias template.
1070 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1071 }
1072 }
1073 }
1074
1075 // If this is a pack expansion, build it as such.
1076 if (EllipsisLoc.isValid() && !Result.isInvalid())
1077 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1078
1079 return Result;
1080 }
1081
1082 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1083 ///
1084 /// template-argument: [C++ 14.2]
1085 /// constant-expression
1086 /// type-id
1087 /// id-expression
ParseTemplateArgument()1088 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1089 // C++ [temp.arg]p2:
1090 // In a template-argument, an ambiguity between a type-id and an
1091 // expression is resolved to a type-id, regardless of the form of
1092 // the corresponding template-parameter.
1093 //
1094 // Therefore, we initially try to parse a type-id.
1095 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1096 SourceLocation Loc = Tok.getLocation();
1097 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1098 Declarator::TemplateTypeArgContext);
1099 if (TypeArg.isInvalid())
1100 return ParsedTemplateArgument();
1101
1102 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1103 TypeArg.get().getAsOpaquePtr(),
1104 Loc);
1105 }
1106
1107 // Try to parse a template template argument.
1108 {
1109 TentativeParsingAction TPA(*this);
1110
1111 ParsedTemplateArgument TemplateTemplateArgument
1112 = ParseTemplateTemplateArgument();
1113 if (!TemplateTemplateArgument.isInvalid()) {
1114 TPA.Commit();
1115 return TemplateTemplateArgument;
1116 }
1117
1118 // Revert this tentative parse to parse a non-type template argument.
1119 TPA.Revert();
1120 }
1121
1122 // Parse a non-type template argument.
1123 SourceLocation Loc = Tok.getLocation();
1124 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1125 if (ExprArg.isInvalid() || !ExprArg.get())
1126 return ParsedTemplateArgument();
1127
1128 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1129 ExprArg.release(), Loc);
1130 }
1131
1132 /// \brief Determine whether the current tokens can only be parsed as a
1133 /// template argument list (starting with the '<') and never as a '<'
1134 /// expression.
IsTemplateArgumentList(unsigned Skip)1135 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1136 struct AlwaysRevertAction : TentativeParsingAction {
1137 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1138 ~AlwaysRevertAction() { Revert(); }
1139 } Tentative(*this);
1140
1141 while (Skip) {
1142 ConsumeToken();
1143 --Skip;
1144 }
1145
1146 // '<'
1147 if (!Tok.is(tok::less))
1148 return false;
1149 ConsumeToken();
1150
1151 // An empty template argument list.
1152 if (Tok.is(tok::greater))
1153 return true;
1154
1155 // See whether we have declaration specifiers, which indicate a type.
1156 while (isCXXDeclarationSpecifier() == TPResult::True())
1157 ConsumeToken();
1158
1159 // If we have a '>' or a ',' then this is a template argument list.
1160 return Tok.is(tok::greater) || Tok.is(tok::comma);
1161 }
1162
1163 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1164 /// (C++ [temp.names]). Returns true if there was an error.
1165 ///
1166 /// template-argument-list: [C++ 14.2]
1167 /// template-argument
1168 /// template-argument-list ',' template-argument
1169 bool
ParseTemplateArgumentList(TemplateArgList & TemplateArgs)1170 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1171 while (true) {
1172 ParsedTemplateArgument Arg = ParseTemplateArgument();
1173 if (Tok.is(tok::ellipsis)) {
1174 SourceLocation EllipsisLoc = ConsumeToken();
1175 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1176 }
1177
1178 if (Arg.isInvalid()) {
1179 SkipUntil(tok::comma, tok::greater, true, true);
1180 return true;
1181 }
1182
1183 // Save this template argument.
1184 TemplateArgs.push_back(Arg);
1185
1186 // If the next token is a comma, consume it and keep reading
1187 // arguments.
1188 if (Tok.isNot(tok::comma)) break;
1189
1190 // Consume the comma.
1191 ConsumeToken();
1192 }
1193
1194 return false;
1195 }
1196
1197 /// \brief Parse a C++ explicit template instantiation
1198 /// (C++ [temp.explicit]).
1199 ///
1200 /// explicit-instantiation:
1201 /// 'extern' [opt] 'template' declaration
1202 ///
1203 /// Note that the 'extern' is a GNU extension and C++11 feature.
ParseExplicitInstantiation(unsigned Context,SourceLocation ExternLoc,SourceLocation TemplateLoc,SourceLocation & DeclEnd,AccessSpecifier AS)1204 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1205 SourceLocation ExternLoc,
1206 SourceLocation TemplateLoc,
1207 SourceLocation &DeclEnd,
1208 AccessSpecifier AS) {
1209 // This isn't really required here.
1210 ParsingDeclRAIIObject
1211 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1212
1213 return ParseSingleDeclarationAfterTemplate(Context,
1214 ParsedTemplateInfo(ExternLoc,
1215 TemplateLoc),
1216 ParsingTemplateParams,
1217 DeclEnd, AS);
1218 }
1219
getSourceRange() const1220 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1221 if (TemplateParams)
1222 return getTemplateParamsRange(TemplateParams->data(),
1223 TemplateParams->size());
1224
1225 SourceRange R(TemplateLoc);
1226 if (ExternLoc.isValid())
1227 R.setBegin(ExternLoc);
1228 return R;
1229 }
1230
LateTemplateParserCallback(void * P,const FunctionDecl * FD)1231 void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
1232 ((Parser*)P)->LateTemplateParser(FD);
1233 }
1234
1235
LateTemplateParser(const FunctionDecl * FD)1236 void Parser::LateTemplateParser(const FunctionDecl *FD) {
1237 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1238 if (LPT) {
1239 ParseLateTemplatedFuncDef(*LPT);
1240 return;
1241 }
1242
1243 llvm_unreachable("Late templated function without associated lexed tokens");
1244 }
1245
1246 /// \brief Late parse a C++ function template in Microsoft mode.
ParseLateTemplatedFuncDef(LateParsedTemplatedFunction & LMT)1247 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1248 if(!LMT.D)
1249 return;
1250
1251 // Get the FunctionDecl.
1252 FunctionDecl *FD = 0;
1253 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1254 FD = FunTmpl->getTemplatedDecl();
1255 else
1256 FD = cast<FunctionDecl>(LMT.D);
1257
1258 // To restore the context after late parsing.
1259 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1260
1261 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1262 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1263 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1264 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
1265 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1266 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1267 } else {
1268 // Get the list of DeclContext to reenter.
1269 SmallVector<DeclContext*, 4> DeclContextToReenter;
1270 DeclContext *DD = FD->getLexicalParent();
1271 while (DD && !DD->isTranslationUnit()) {
1272 DeclContextToReenter.push_back(DD);
1273 DD = DD->getLexicalParent();
1274 }
1275
1276 // Reenter template scopes from outmost to innermost.
1277 SmallVector<DeclContext*, 4>::reverse_iterator II =
1278 DeclContextToReenter.rbegin();
1279 for (; II != DeclContextToReenter.rend(); ++II) {
1280 if (ClassTemplatePartialSpecializationDecl* MD =
1281 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1282 TemplateParamScopeStack.push_back(new ParseScope(this,
1283 Scope::TemplateParamScope));
1284 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1285 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1286 TemplateParamScopeStack.push_back(new ParseScope(this,
1287 Scope::TemplateParamScope,
1288 MD->getDescribedClassTemplate() != 0 ));
1289 Actions.ActOnReenterTemplateScope(getCurScope(),
1290 MD->getDescribedClassTemplate());
1291 }
1292 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1293 Actions.PushDeclContext(Actions.getCurScope(), *II);
1294 }
1295 TemplateParamScopeStack.push_back(new ParseScope(this,
1296 Scope::TemplateParamScope));
1297 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1298 }
1299
1300 assert(!LMT.Toks.empty() && "Empty body!");
1301
1302 // Append the current token at the end of the new token stream so that it
1303 // doesn't get lost.
1304 LMT.Toks.push_back(Tok);
1305 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1306
1307 // Consume the previously pushed token.
1308 ConsumeAnyToken();
1309 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1310 && "Inline method not starting with '{', ':' or 'try'");
1311
1312 // Parse the method body. Function body parsing code is similar enough
1313 // to be re-used for method bodies as well.
1314 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1315
1316 // Recreate the containing function DeclContext.
1317 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
1318
1319 if (FunctionTemplateDecl *FunctionTemplate
1320 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1321 Actions.ActOnStartOfFunctionDef(getCurScope(),
1322 FunctionTemplate->getTemplatedDecl());
1323 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1324 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1325
1326
1327 if (Tok.is(tok::kw_try)) {
1328 ParseFunctionTryBlock(LMT.D, FnScope);
1329 } else {
1330 if (Tok.is(tok::colon))
1331 ParseConstructorInitializer(LMT.D);
1332 else
1333 Actions.ActOnDefaultCtorInitializers(LMT.D);
1334
1335 if (Tok.is(tok::l_brace)) {
1336 ParseFunctionStatementBody(LMT.D, FnScope);
1337 Actions.MarkAsLateParsedTemplate(FD, false);
1338 } else
1339 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1340 }
1341
1342 // Exit scopes.
1343 FnScope.Exit();
1344 SmallVector<ParseScope*, 4>::reverse_iterator I =
1345 TemplateParamScopeStack.rbegin();
1346 for (; I != TemplateParamScopeStack.rend(); ++I)
1347 delete *I;
1348
1349 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1350 if (grp)
1351 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1352 }
1353
1354 /// \brief Lex a delayed template function for late parsing.
LexTemplateFunctionForLateParsing(CachedTokens & Toks)1355 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1356 tok::TokenKind kind = Tok.getKind();
1357 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1358 // Consume everything up to (and including) the matching right brace.
1359 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1360 }
1361
1362 // If we're in a function-try-block, we need to store all the catch blocks.
1363 if (kind == tok::kw_try) {
1364 while (Tok.is(tok::kw_catch)) {
1365 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1366 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1367 }
1368 }
1369 }
1370