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