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