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