Clang Project

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