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