clang  10.0.0git
ParseTemplate.cpp
Go to the documentation of this file.
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"
17 #include "clang/Parse/Parser.h"
19 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/Support/TimeProfiler.h"
23 using namespace clang;
24 
25 /// Parse a template declaration, explicit instantiation, or
26 /// explicit specialization.
27 Decl *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
64 Decl *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.
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 =
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.
179 Decl *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;
224  getCurScope(), AS, DS,
225  TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
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);
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() !=
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.
348 Decl *
349 Parser::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) <<
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 
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 =
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.
430 bool 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();
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
468 bool
469 Parser::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,
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,
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.
504 Parser::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 ///
605 NamedDecl *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)
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();
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,
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.
663 bool 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.
680 bool 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  if (MemberOfUnknownSpecialization || !PossibleConcept ||
715  TNK != TNK_Concept_template) {
716  if (SS.isNotEmpty())
717  AnnotateScopeToken(SS, !WasScopeAnnotation);
718  return false;
719  }
720 
721  // At this point we're sure we're dealing with a constrained parameter. It
722  // may or may not have a template parameter list following the concept
723  // name.
724  if (AnnotateTemplateIdToken(PossibleConcept, TNK, SS,
725  /*TemplateKWLoc=*/SourceLocation(),
726  PossibleConceptName,
727  /*AllowTypeAnnotation=*/false,
728  /*TypeConstraint=*/true))
729  return true;
730  }
731 
732  if (SS.isNotEmpty())
733  AnnotateScopeToken(SS, !WasScopeAnnotation);
734  return false;
735 }
736 
737 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
738 /// Other kinds of template parameters are parsed in
739 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
740 ///
741 /// type-parameter: [C++ temp.param]
742 /// 'class' ...[opt][C++0x] identifier[opt]
743 /// 'class' identifier[opt] '=' type-id
744 /// 'typename' ...[opt][C++0x] identifier[opt]
745 /// 'typename' identifier[opt] '=' type-id
746 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
747  assert((Tok.isOneOf(tok::kw_class, tok::kw_typename) ||
748  isTypeConstraintAnnotation()) &&
749  "A type-parameter starts with 'class', 'typename' or a "
750  "type-constraint");
751 
752  CXXScopeSpec TypeConstraintSS;
754  bool TypenameKeyword = false;
755  SourceLocation KeyLoc;
756  ParseOptionalCXXScopeSpecifier(TypeConstraintSS, nullptr,
757  /*EnteringContext*/ false);
758  if (Tok.is(tok::annot_template_id)) {
759  // Consume the 'type-constraint'.
760  TypeConstraint =
761  static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
762  assert(TypeConstraint->Kind == TNK_Concept_template &&
763  "stray non-concept template-id annotation");
764  KeyLoc = ConsumeAnnotationToken();
765  } else {
766  assert(TypeConstraintSS.isEmpty() &&
767  "expected type constraint after scope specifier");
768 
769  // Consume the 'class' or 'typename' keyword.
770  TypenameKeyword = Tok.is(tok::kw_typename);
771  KeyLoc = ConsumeToken();
772  }
773 
774  // Grab the ellipsis (if given).
775  SourceLocation EllipsisLoc;
776  if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
777  Diag(EllipsisLoc,
779  ? diag::warn_cxx98_compat_variadic_templates
780  : diag::ext_variadic_templates);
781  }
782 
783  // Grab the template parameter name (if given)
784  SourceLocation NameLoc = Tok.getLocation();
785  IdentifierInfo *ParamName = nullptr;
786  if (Tok.is(tok::identifier)) {
787  ParamName = Tok.getIdentifierInfo();
788  ConsumeToken();
789  } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
790  tok::greatergreater)) {
791  // Unnamed template parameter. Don't have to do anything here, just
792  // don't consume this token.
793  } else {
794  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
795  return nullptr;
796  }
797 
798  // Recover from misplaced ellipsis.
799  bool AlreadyHasEllipsis = EllipsisLoc.isValid();
800  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
801  DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
802 
803  // Grab a default argument (if available).
804  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
805  // we introduce the type parameter into the local scope.
806  SourceLocation EqualLoc;
807  ParsedType DefaultArg;
808  if (TryConsumeToken(tok::equal, EqualLoc))
809  DefaultArg = ParseTypeName(/*Range=*/nullptr,
811  .get();
812 
813  NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
814  TypenameKeyword, EllipsisLoc,
815  KeyLoc, ParamName, NameLoc,
816  Depth, Position, EqualLoc,
817  DefaultArg,
818  TypeConstraint != nullptr);
819 
820  if (TypeConstraint) {
821  Actions.ActOnTypeConstraint(TypeConstraintSS, TypeConstraint,
822  cast<TemplateTypeParmDecl>(NewDecl),
823  EllipsisLoc);
824  }
825 
826  return NewDecl;
827 }
828 
829 /// ParseTemplateTemplateParameter - Handle the parsing of template
830 /// template parameters.
831 ///
832 /// type-parameter: [C++ temp.param]
833 /// 'template' '<' template-parameter-list '>' type-parameter-key
834 /// ...[opt] identifier[opt]
835 /// 'template' '<' template-parameter-list '>' type-parameter-key
836 /// identifier[opt] = id-expression
837 /// type-parameter-key:
838 /// 'class'
839 /// 'typename' [C++1z]
840 NamedDecl *
841 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
842  assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
843 
844  // Handle the template <...> part.
845  SourceLocation TemplateLoc = ConsumeToken();
846  SmallVector<NamedDecl*,8> TemplateParams;
847  SourceLocation LAngleLoc, RAngleLoc;
848  {
849  ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
850  if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
851  RAngleLoc)) {
852  return nullptr;
853  }
854  }
855 
856  // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
857  // Generate a meaningful error if the user forgot to put class before the
858  // identifier, comma, or greater. Provide a fixit if the identifier, comma,
859  // or greater appear immediately or after 'struct'. In the latter case,
860  // replace the keyword with 'class'.
861  if (!TryConsumeToken(tok::kw_class)) {
862  bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
863  const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
864  if (Tok.is(tok::kw_typename)) {
865  Diag(Tok.getLocation(),
866  getLangOpts().CPlusPlus17
867  ? diag::warn_cxx14_compat_template_template_param_typename
868  : diag::ext_template_template_param_typename)
869  << (!getLangOpts().CPlusPlus17
870  ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
871  : FixItHint());
872  } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
873  tok::greatergreater, tok::ellipsis)) {
874  Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
875  << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
876  : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
877  } else
878  Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
879 
880  if (Replace)
881  ConsumeToken();
882  }
883 
884  // Parse the ellipsis, if given.
885  SourceLocation EllipsisLoc;
886  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
887  Diag(EllipsisLoc,
889  ? diag::warn_cxx98_compat_variadic_templates
890  : diag::ext_variadic_templates);
891 
892  // Get the identifier, if given.
893  SourceLocation NameLoc = Tok.getLocation();
894  IdentifierInfo *ParamName = nullptr;
895  if (Tok.is(tok::identifier)) {
896  ParamName = Tok.getIdentifierInfo();
897  ConsumeToken();
898  } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
899  tok::greatergreater)) {
900  // Unnamed template parameter. Don't have to do anything here, just
901  // don't consume this token.
902  } else {
903  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
904  return nullptr;
905  }
906 
907  // Recover from misplaced ellipsis.
908  bool AlreadyHasEllipsis = EllipsisLoc.isValid();
909  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
910  DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
911 
912  TemplateParameterList *ParamList =
914  TemplateLoc, LAngleLoc,
915  TemplateParams,
916  RAngleLoc, nullptr);
917 
918  // Grab a default argument (if available).
919  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
920  // we introduce the template parameter into the local scope.
921  SourceLocation EqualLoc;
922  ParsedTemplateArgument DefaultArg;
923  if (TryConsumeToken(tok::equal, EqualLoc)) {
924  DefaultArg = ParseTemplateTemplateArgument();
925  if (DefaultArg.isInvalid()) {
926  Diag(Tok.getLocation(),
927  diag::err_default_template_template_parameter_not_template);
928  SkipUntil(tok::comma, tok::greater, tok::greatergreater,
930  }
931  }
932 
933  return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
934  ParamList, EllipsisLoc,
935  ParamName, NameLoc, Depth,
936  Position, EqualLoc, DefaultArg);
937 }
938 
939 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
940 /// template parameters (e.g., in "template<int Size> class array;").
941 ///
942 /// template-parameter:
943 /// ...
944 /// parameter-declaration
945 NamedDecl *
946 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
947  // Parse the declaration-specifiers (i.e., the type).
948  // FIXME: The type should probably be restricted in some way... Not all
949  // declarators (parts of declarators?) are accepted for parameters.
950  DeclSpec DS(AttrFactory);
951  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
952  DeclSpecContext::DSC_template_param);
953 
954  // Parse this as a typename.
956  ParseDeclarator(ParamDecl);
957  if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
958  Diag(Tok.getLocation(), diag::err_expected_template_parameter);
959  return nullptr;
960  }
961 
962  // Recover from misplaced ellipsis.
963  SourceLocation EllipsisLoc;
964  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
965  DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
966 
967  // If there is a default value, parse it.
968  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
969  // we introduce the template parameter into the local scope.
970  SourceLocation EqualLoc;
971  ExprResult DefaultArg;
972  if (TryConsumeToken(tok::equal, EqualLoc)) {
973  // C++ [temp.param]p15:
974  // When parsing a default template-argument for a non-type
975  // template-parameter, the first non-nested > is taken as the
976  // end of the template-parameter-list rather than a greater-than
977  // operator.
978  GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
979  EnterExpressionEvaluationContext ConstantEvaluated(
981 
983  if (DefaultArg.isInvalid())
984  SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
985  }
986 
987  // Create the parameter.
988  return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
989  Depth, Position, EqualLoc,
990  DefaultArg.get());
991 }
992 
993 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
994  SourceLocation CorrectLoc,
995  bool AlreadyHasEllipsis,
996  bool IdentifierHasName) {
997  FixItHint Insertion;
998  if (!AlreadyHasEllipsis)
999  Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
1000  Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
1001  << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
1002  << !IdentifierHasName;
1003 }
1004 
1005 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
1006  Declarator &D) {
1007  assert(EllipsisLoc.isValid());
1008  bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
1009  if (!AlreadyHasEllipsis)
1010  D.setEllipsisLoc(EllipsisLoc);
1011  DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
1012  AlreadyHasEllipsis, D.hasName());
1013 }
1014 
1015 /// Parses a '>' at the end of a template list.
1016 ///
1017 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
1018 /// to determine if these tokens were supposed to be a '>' followed by
1019 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
1020 ///
1021 /// \param RAngleLoc the location of the consumed '>'.
1022 ///
1023 /// \param ConsumeLastToken if true, the '>' is consumed.
1024 ///
1025 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
1026 /// type parameter or type argument list, rather than a C++ template parameter
1027 /// or argument list.
1028 ///
1029 /// \returns true, if current token does not start with '>', false otherwise.
1030 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
1031  bool ConsumeLastToken,
1032  bool ObjCGenericList) {
1033  // What will be left once we've consumed the '>'.
1034  tok::TokenKind RemainingToken;
1035  const char *ReplacementStr = "> >";
1036  bool MergeWithNextToken = false;
1037 
1038  switch (Tok.getKind()) {
1039  default:
1040  Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
1041  return true;
1042 
1043  case tok::greater:
1044  // Determine the location of the '>' token. Only consume this token
1045  // if the caller asked us to.
1046  RAngleLoc = Tok.getLocation();
1047  if (ConsumeLastToken)
1048  ConsumeToken();
1049  return false;
1050 
1051  case tok::greatergreater:
1052  RemainingToken = tok::greater;
1053  break;
1054 
1055  case tok::greatergreatergreater:
1056  RemainingToken = tok::greatergreater;
1057  break;
1058 
1059  case tok::greaterequal:
1060  RemainingToken = tok::equal;
1061  ReplacementStr = "> =";
1062 
1063  // Join two adjacent '=' tokens into one, for cases like:
1064  // void (*p)() = f<int>;
1065  // return f<int>==p;
1066  if (NextToken().is(tok::equal) &&
1067  areTokensAdjacent(Tok, NextToken())) {
1068  RemainingToken = tok::equalequal;
1069  MergeWithNextToken = true;
1070  }
1071  break;
1072 
1073  case tok::greatergreaterequal:
1074  RemainingToken = tok::greaterequal;
1075  break;
1076  }
1077 
1078  // This template-id is terminated by a token that starts with a '>'.
1079  // Outside C++11 and Objective-C, this is now error recovery.
1080  //
1081  // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
1082  // extend that treatment to also apply to the '>>>' token.
1083  //
1084  // Objective-C allows this in its type parameter / argument lists.
1085 
1086  SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
1087  SourceLocation TokLoc = Tok.getLocation();
1088  Token Next = NextToken();
1089 
1090  // Whether splitting the current token after the '>' would undesirably result
1091  // in the remaining token pasting with the token after it. This excludes the
1092  // MergeWithNextToken cases, which we've already handled.
1093  bool PreventMergeWithNextToken =
1094  (RemainingToken == tok::greater ||
1095  RemainingToken == tok::greatergreater) &&
1096  (Next.isOneOf(tok::greater, tok::greatergreater,
1097  tok::greatergreatergreater, tok::equal, tok::greaterequal,
1098  tok::greatergreaterequal, tok::equalequal)) &&
1099  areTokensAdjacent(Tok, Next);
1100 
1101  // Diagnose this situation as appropriate.
1102  if (!ObjCGenericList) {
1103  // The source range of the replaced token(s).
1105  TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
1106  getLangOpts()));
1107 
1108  // A hint to put a space between the '>>'s. In order to make the hint as
1109  // clear as possible, we include the characters either side of the space in
1110  // the replacement, rather than just inserting a space at SecondCharLoc.
1111  FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
1112  ReplacementStr);
1113 
1114  // A hint to put another space after the token, if it would otherwise be
1115  // lexed differently.
1116  FixItHint Hint2;
1117  if (PreventMergeWithNextToken)
1118  Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
1119 
1120  unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1121  if (getLangOpts().CPlusPlus11 &&
1122  (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
1123  DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1124  else if (Tok.is(tok::greaterequal))
1125  DiagId = diag::err_right_angle_bracket_equal_needs_space;
1126  Diag(TokLoc, DiagId) << Hint1 << Hint2;
1127  }
1128 
1129  // Find the "length" of the resulting '>' token. This is not always 1, as it
1130  // can contain escaped newlines.
1131  unsigned GreaterLength = Lexer::getTokenPrefixLength(
1132  TokLoc, 1, PP.getSourceManager(), getLangOpts());
1133 
1134  // Annotate the source buffer to indicate that we split the token after the
1135  // '>'. This allows us to properly find the end of, and extract the spelling
1136  // of, the '>' token later.
1137  RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
1138 
1139  // Strip the initial '>' from the token.
1140  bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1141 
1142  Token Greater = Tok;
1143  Greater.setLocation(RAngleLoc);
1144  Greater.setKind(tok::greater);
1145  Greater.setLength(GreaterLength);
1146 
1147  unsigned OldLength = Tok.getLength();
1148  if (MergeWithNextToken) {
1149  ConsumeToken();
1150  OldLength += Tok.getLength();
1151  }
1152 
1153  Tok.setKind(RemainingToken);
1154  Tok.setLength(OldLength - GreaterLength);
1155 
1156  // Split the second token if lexing it normally would lex a different token
1157  // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1158  SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
1159  if (PreventMergeWithNextToken)
1160  AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
1161  Tok.setLocation(AfterGreaterLoc);
1162 
1163  // Update the token cache to match what we just did if necessary.
1164  if (CachingTokens) {
1165  // If the previous cached token is being merged, delete it.
1166  if (MergeWithNextToken)
1168 
1169  if (ConsumeLastToken)
1171  else
1172  PP.ReplacePreviousCachedToken({Greater});
1173  }
1174 
1175  if (ConsumeLastToken) {
1176  PrevTokLocation = RAngleLoc;
1177  } else {
1178  PrevTokLocation = TokBeforeGreaterLoc;
1179  PP.EnterToken(Tok, /*IsReinject=*/true);
1180  Tok = Greater;
1181  }
1182 
1183  return false;
1184 }
1185 
1186 
1187 /// Parses a template-id that after the template name has
1188 /// already been parsed.
1189 ///
1190 /// This routine takes care of parsing the enclosed template argument
1191 /// list ('<' template-parameter-list [opt] '>') and placing the
1192 /// results into a form that can be transferred to semantic analysis.
1193 ///
1194 /// \param ConsumeLastToken if true, then we will consume the last
1195 /// token that forms the template-id. Otherwise, we will leave the
1196 /// last token in the stream (e.g., so that it can be replaced with an
1197 /// annotation token).
1198 bool
1199 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1200  SourceLocation &LAngleLoc,
1201  TemplateArgList &TemplateArgs,
1202  SourceLocation &RAngleLoc) {
1203  assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1204 
1205  // Consume the '<'.
1206  LAngleLoc = ConsumeToken();
1207 
1208  // Parse the optional template-argument-list.
1209  bool Invalid = false;
1210  {
1211  GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1212  if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1213  tok::greatergreatergreater, tok::greaterequal,
1214  tok::greatergreaterequal))
1215  Invalid = ParseTemplateArgumentList(TemplateArgs);
1216 
1217  if (Invalid) {
1218  // Try to find the closing '>'.
1219  if (ConsumeLastToken)
1220  SkipUntil(tok::greater, StopAtSemi);
1221  else
1222  SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1223  return true;
1224  }
1225  }
1226 
1227  return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
1228  /*ObjCGenericList=*/false);
1229 }
1230 
1231 /// Replace the tokens that form a simple-template-id with an
1232 /// annotation token containing the complete template-id.
1233 ///
1234 /// The first token in the stream must be the name of a template that
1235 /// is followed by a '<'. This routine will parse the complete
1236 /// simple-template-id and replace the tokens with a single annotation
1237 /// token with one of two different kinds: if the template-id names a
1238 /// type (and \p AllowTypeAnnotation is true), the annotation token is
1239 /// a type annotation that includes the optional nested-name-specifier
1240 /// (\p SS). Otherwise, the annotation token is a template-id
1241 /// annotation that does not include the optional
1242 /// nested-name-specifier.
1243 ///
1244 /// \param Template the declaration of the template named by the first
1245 /// token (an identifier), as returned from \c Action::isTemplateName().
1246 ///
1247 /// \param TNK the kind of template that \p Template
1248 /// refers to, as returned from \c Action::isTemplateName().
1249 ///
1250 /// \param SS if non-NULL, the nested-name-specifier that precedes
1251 /// this template name.
1252 ///
1253 /// \param TemplateKWLoc if valid, specifies that this template-id
1254 /// annotation was preceded by the 'template' keyword and gives the
1255 /// location of that keyword. If invalid (the default), then this
1256 /// template-id was not preceded by a 'template' keyword.
1257 ///
1258 /// \param AllowTypeAnnotation if true (the default), then a
1259 /// simple-template-id that refers to a class template, template
1260 /// template parameter, or other template that produces a type will be
1261 /// replaced with a type annotation token. Otherwise, the
1262 /// simple-template-id is always replaced with a template-id
1263 /// annotation token.
1264 ///
1265 /// \param TypeConstraint if true, then this is actually a type-constraint,
1266 /// meaning that the template argument list can be omitted (and the template in
1267 /// question must be a concept).
1268 ///
1269 /// If an unrecoverable parse error occurs and no annotation token can be
1270 /// formed, this function returns true.
1271 ///
1272 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1273  CXXScopeSpec &SS,
1274  SourceLocation TemplateKWLoc,
1276  bool AllowTypeAnnotation,
1277  bool TypeConstraint) {
1278  assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1279  assert(Template && (Tok.is(tok::less) || TypeConstraint) &&
1280  "Parser isn't at the beginning of a template-id");
1281  assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1282  "a type annotation");
1283  assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1284  "must accompany a concept name");
1285 
1286  // Consume the template-name.
1287  SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1288 
1289  // Parse the enclosed template argument list.
1290  SourceLocation LAngleLoc, RAngleLoc;
1291  TemplateArgList TemplateArgs;
1292  if (!TypeConstraint || Tok.is(tok::less)) {
1293  bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
1294  TemplateArgs,
1295  RAngleLoc);
1296 
1297  if (Invalid) {
1298  // If we failed to parse the template ID but skipped ahead to a >, we're not
1299  // going to be able to form a token annotation. Eat the '>' if present.
1300  TryConsumeToken(tok::greater);
1301  // FIXME: Annotate the token stream so we don't produce the same errors
1302  // again if we're doing this annotation as part of a tentative parse.
1303  return true;
1304  }
1305  }
1306 
1307  ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1308 
1309  // Build the annotation token.
1310  if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1312  getCurScope(), SS, TemplateKWLoc, Template, TemplateName.Identifier,
1313  TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
1314  if (Type.isInvalid()) {
1315  // If we failed to parse the template ID but skipped ahead to a >, we're
1316  // not going to be able to form a token annotation. Eat the '>' if
1317  // present.
1318  TryConsumeToken(tok::greater);
1319  // FIXME: Annotate the token stream so we don't produce the same errors
1320  // again if we're doing this annotation as part of a tentative parse.
1321  return true;
1322  }
1323 
1324  Tok.setKind(tok::annot_typename);
1325  setTypeAnnotation(Tok, Type.get());
1326  if (SS.isNotEmpty())
1327  Tok.setLocation(SS.getBeginLoc());
1328  else if (TemplateKWLoc.isValid())
1329  Tok.setLocation(TemplateKWLoc);
1330  else
1331  Tok.setLocation(TemplateNameLoc);
1332  } else {
1333  // Build a template-id annotation token that can be processed
1334  // later.
1335  Tok.setKind(tok::annot_template_id);
1336 
1337  IdentifierInfo *TemplateII =
1338  TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1339  ? TemplateName.Identifier
1340  : nullptr;
1341 
1342  OverloadedOperatorKind OpKind =
1343  TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1344  ? OO_None
1345  : TemplateName.OperatorFunctionId.Operator;
1346 
1348  TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1349  LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
1350 
1351  Tok.setAnnotationValue(TemplateId);
1352  if (TemplateKWLoc.isValid())
1353  Tok.setLocation(TemplateKWLoc);
1354  else
1355  Tok.setLocation(TemplateNameLoc);
1356  }
1357 
1358  // Common fields for the annotation token
1359  Tok.setAnnotationEndLoc(RAngleLoc);
1360 
1361  // In case the tokens were cached, have Preprocessor replace them with the
1362  // annotation token.
1363  PP.AnnotateCachedTokens(Tok);
1364  return false;
1365 }
1366 
1367 /// Replaces a template-id annotation token with a type
1368 /// annotation token.
1369 ///
1370 /// If there was a failure when forming the type from the template-id,
1371 /// a type annotation token will still be created, but will have a
1372 /// NULL type pointer to signify an error.
1373 ///
1374 /// \param SS The scope specifier appearing before the template-id, if any.
1375 ///
1376 /// \param IsClassName Is this template-id appearing in a context where we
1377 /// know it names a class, such as in an elaborated-type-specifier or
1378 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
1379 /// in those contexts.)
1380 void Parser::AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
1381  bool IsClassName) {
1382  assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1383 
1384  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1385  assert((TemplateId->Kind == TNK_Type_template ||
1386  TemplateId->Kind == TNK_Dependent_template_name ||
1387  TemplateId->Kind == TNK_Undeclared_template) &&
1388  "Only works for type and dependent templates");
1389 
1390  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1391  TemplateId->NumArgs);
1392 
1393  TypeResult Type
1394  = Actions.ActOnTemplateIdType(getCurScope(),
1395  SS,
1396  TemplateId->TemplateKWLoc,
1397  TemplateId->Template,
1398  TemplateId->Name,
1399  TemplateId->TemplateNameLoc,
1400  TemplateId->LAngleLoc,
1401  TemplateArgsPtr,
1402  TemplateId->RAngleLoc,
1403  /*IsCtorOrDtorName*/false,
1404  IsClassName);
1405  // Create the new "type" annotation token.
1406  Tok.setKind(tok::annot_typename);
1407  setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1408  if (SS.isNotEmpty()) // it was a C++ qualified type name.
1409  Tok.setLocation(SS.getBeginLoc());
1410  // End location stays the same
1411 
1412  // Replace the template-id annotation token, and possible the scope-specifier
1413  // that precedes it, with the typename annotation token.
1414  PP.AnnotateCachedTokens(Tok);
1415 }
1416 
1417 /// Determine whether the given token can end a template argument.
1418 static bool isEndOfTemplateArgument(Token Tok) {
1419  return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1420 }
1421 
1422 /// Parse a C++ template template argument.
1423 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1424  if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1425  !Tok.is(tok::annot_cxxscope))
1426  return ParsedTemplateArgument();
1427 
1428  // C++0x [temp.arg.template]p1:
1429  // A template-argument for a template template-parameter shall be the name
1430  // of a class template or an alias template, expressed as id-expression.
1431  //
1432  // We parse an id-expression that refers to a class template or alias
1433  // template. The grammar we parse is:
1434  //
1435  // nested-name-specifier[opt] template[opt] identifier ...[opt]
1436  //
1437  // followed by a token that terminates a template argument, such as ',',
1438  // '>', or (in some cases) '>>'.
1439  CXXScopeSpec SS; // nested-name-specifier, if present
1440  ParseOptionalCXXScopeSpecifier(SS, nullptr,
1441  /*EnteringContext=*/false);
1442 
1444  SourceLocation EllipsisLoc;
1445  if (SS.isSet() && Tok.is(tok::kw_template)) {
1446  // Parse the optional 'template' keyword following the
1447  // nested-name-specifier.
1448  SourceLocation TemplateKWLoc = ConsumeToken();
1449 
1450  if (Tok.is(tok::identifier)) {
1451  // We appear to have a dependent template name.
1452  UnqualifiedId Name;
1453  Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1454  ConsumeToken(); // the identifier
1455 
1456  TryConsumeToken(tok::ellipsis, EllipsisLoc);
1457 
1458  // If the next token signals the end of a template argument,
1459  // then we have a dependent template name that could be a template
1460  // template argument.
1461  TemplateTy Template;
1462  if (isEndOfTemplateArgument(Tok) &&
1464  getCurScope(), SS, TemplateKWLoc, Name,
1465  /*ObjectType=*/nullptr,
1466  /*EnteringContext=*/false, Template))
1467  Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1468  }
1469  } else if (Tok.is(tok::identifier)) {
1470  // We may have a (non-dependent) template name.
1471  TemplateTy Template;
1472  UnqualifiedId Name;
1473  Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1474  ConsumeToken(); // the identifier
1475 
1476  TryConsumeToken(tok::ellipsis, EllipsisLoc);
1477 
1478  if (isEndOfTemplateArgument(Tok)) {
1479  bool MemberOfUnknownSpecialization;
1480  TemplateNameKind TNK = Actions.isTemplateName(
1481  getCurScope(), SS,
1482  /*hasTemplateKeyword=*/false, Name,
1483  /*ObjectType=*/nullptr,
1484  /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1485  if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1486  // We have an id-expression that refers to a class template or
1487  // (C++0x) alias template.
1488  Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1489  }
1490  }
1491  }
1492 
1493  // If this is a pack expansion, build it as such.
1494  if (EllipsisLoc.isValid() && !Result.isInvalid())
1495  Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1496 
1497  return Result;
1498 }
1499 
1500 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1501 ///
1502 /// template-argument: [C++ 14.2]
1503 /// constant-expression
1504 /// type-id
1505 /// id-expression
1506 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1507  // C++ [temp.arg]p2:
1508  // In a template-argument, an ambiguity between a type-id and an
1509  // expression is resolved to a type-id, regardless of the form of
1510  // the corresponding template-parameter.
1511  //
1512  // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1513  // up and annotate an identifier as an id-expression during disambiguation,
1514  // so enter the appropriate context for a constant expression template
1515  // argument before trying to disambiguate.
1516 
1517  EnterExpressionEvaluationContext EnterConstantEvaluated(
1519  /*LambdaContextDecl=*/nullptr,
1521  if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1522  TypeResult TypeArg = ParseTypeName(
1523  /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
1524  return Actions.ActOnTemplateTypeArgument(TypeArg);
1525  }
1526 
1527  // Try to parse a template template argument.
1528  {
1529  TentativeParsingAction TPA(*this);
1530 
1531  ParsedTemplateArgument TemplateTemplateArgument
1532  = ParseTemplateTemplateArgument();
1533  if (!TemplateTemplateArgument.isInvalid()) {
1534  TPA.Commit();
1535  return TemplateTemplateArgument;
1536  }
1537 
1538  // Revert this tentative parse to parse a non-type template argument.
1539  TPA.Revert();
1540  }
1541 
1542  // Parse a non-type template argument.
1543  SourceLocation Loc = Tok.getLocation();
1545  if (ExprArg.isInvalid() || !ExprArg.get()) {
1546  return ParsedTemplateArgument();
1547  }
1548 
1550  ExprArg.get(), Loc);
1551 }
1552 
1553 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1554 /// (C++ [temp.names]). Returns true if there was an error.
1555 ///
1556 /// template-argument-list: [C++ 14.2]
1557 /// template-argument
1558 /// template-argument-list ',' template-argument
1559 bool
1560 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1561 
1562  ColonProtectionRAIIObject ColonProtection(*this, false);
1563 
1564  do {
1565  ParsedTemplateArgument Arg = ParseTemplateArgument();
1566  SourceLocation EllipsisLoc;
1567  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1568  Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1569 
1570  if (Arg.isInvalid()) {
1571  SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1572  return true;
1573  }
1574 
1575  // Save this template argument.
1576  TemplateArgs.push_back(Arg);
1577 
1578  // If the next token is a comma, consume it and keep reading
1579  // arguments.
1580  } while (TryConsumeToken(tok::comma));
1581 
1582  return false;
1583 }
1584 
1585 /// Parse a C++ explicit template instantiation
1586 /// (C++ [temp.explicit]).
1587 ///
1588 /// explicit-instantiation:
1589 /// 'extern' [opt] 'template' declaration
1590 ///
1591 /// Note that the 'extern' is a GNU extension and C++11 feature.
1592 Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
1593  SourceLocation ExternLoc,
1594  SourceLocation TemplateLoc,
1595  SourceLocation &DeclEnd,
1596  ParsedAttributes &AccessAttrs,
1597  AccessSpecifier AS) {
1598  // This isn't really required here.
1600  ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1601 
1602  return ParseSingleDeclarationAfterTemplate(
1603  Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1604  ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1605 }
1606 
1608  if (TemplateParams)
1609  return getTemplateParamsRange(TemplateParams->data(),
1610  TemplateParams->size());
1611 
1612  SourceRange R(TemplateLoc);
1613  if (ExternLoc.isValid())
1614  R.setBegin(ExternLoc);
1615  return R;
1616 }
1617 
1618 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1619  ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1620 }
1621 
1622 /// Late parse a C++ function template in Microsoft mode.
1623 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1624  if (!LPT.D)
1625  return;
1626 
1627  // Get the FunctionDecl.
1628  FunctionDecl *FunD = LPT.D->getAsFunction();
1629  // Track template parameter depth.
1630  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1631 
1632  // To restore the context after late parsing.
1633  Sema::ContextRAII GlobalSavedContext(
1634  Actions, Actions.Context.getTranslationUnitDecl());
1635 
1636  SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1637 
1638  // Get the list of DeclContexts to reenter. For inline methods, we only want
1639  // to push the DeclContext of the outermost class. This matches the way the
1640  // parser normally parses bodies of inline methods when the outermost class is
1641  // complete.
1642  struct ContainingDC {
1643  ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1644  llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1645  DeclContext *getDC() { return Pair.getPointer(); }
1646  bool shouldPushDC() { return Pair.getInt(); }
1647  };
1648  SmallVector<ContainingDC, 4> DeclContextsToReenter;
1649  DeclContext *DD = FunD;
1650  DeclContext *NextContaining = Actions.getContainingDC(DD);
1651  while (DD && !DD->isTranslationUnit()) {
1652  bool ShouldPush = DD == NextContaining;
1653  DeclContextsToReenter.push_back({DD, ShouldPush});
1654  if (ShouldPush)
1655  NextContaining = Actions.getContainingDC(DD);
1656  DD = DD->getLexicalParent();
1657  }
1658 
1659  // Reenter template scopes from outermost to innermost.
1660  for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
1661  TemplateParamScopeStack.push_back(
1662  new ParseScope(this, Scope::TemplateParamScope));
1663  unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
1664  getCurScope(), cast<Decl>(CDC.getDC()));
1665  CurTemplateDepthTracker.addDepth(NumParamLists);
1666  if (CDC.shouldPushDC()) {
1667  TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1668  Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
1669  }
1670  }
1671 
1672  assert(!LPT.Toks.empty() && "Empty body!");
1673 
1674  // Append the current token at the end of the new token stream so that it
1675  // doesn't get lost.
1676  LPT.Toks.push_back(Tok);
1677  PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1678 
1679  // Consume the previously pushed token.
1680  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1681  assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1682  "Inline method not starting with '{', ':' or 'try'");
1683 
1684  // Parse the method body. Function body parsing code is similar enough
1685  // to be re-used for method bodies as well.
1686  ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1688 
1689  // Recreate the containing function DeclContext.
1690  Sema::ContextRAII FunctionSavedContext(Actions,
1691  Actions.getContainingDC(FunD));
1692 
1693  Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1694 
1695  if (Tok.is(tok::kw_try)) {
1696  ParseFunctionTryBlock(LPT.D, FnScope);
1697  } else {
1698  if (Tok.is(tok::colon))
1699  ParseConstructorInitializer(LPT.D);
1700  else
1701  Actions.ActOnDefaultCtorInitializers(LPT.D);
1702 
1703  if (Tok.is(tok::l_brace)) {
1704  assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1705  cast<FunctionTemplateDecl>(LPT.D)
1706  ->getTemplateParameters()
1707  ->getDepth() == TemplateParameterDepth - 1) &&
1708  "TemplateParameterDepth should be greater than the depth of "
1709  "current template being instantiated!");
1710  ParseFunctionStatementBody(LPT.D, FnScope);
1711  Actions.UnmarkAsLateParsedTemplate(FunD);
1712  } else
1713  Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1714  }
1715 
1716  // Exit scopes.
1717  FnScope.Exit();
1719  TemplateParamScopeStack.rbegin();
1720  for (; I != TemplateParamScopeStack.rend(); ++I)
1721  delete *I;
1722 }
1723 
1724 /// Lex a delayed template function for late parsing.
1725 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1726  tok::TokenKind kind = Tok.getKind();
1727  if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1728  // Consume everything up to (and including) the matching right brace.
1729  ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1730  }
1731 
1732  // If we're in a function-try-block, we need to store all the catch blocks.
1733  if (kind == tok::kw_try) {
1734  while (Tok.is(tok::kw_catch)) {
1735  ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1736  ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1737  }
1738  }
1739 }
1740 
1741 /// We've parsed something that could plausibly be intended to be a template
1742 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
1743 /// be an expression. Determine if this is likely to be a template-id and if so,
1744 /// diagnose it.
1745 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1746  TentativeParsingAction TPA(*this);
1747  // FIXME: We could look at the token sequence in a lot more detail here.
1748  if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1750  TPA.Commit();
1751 
1753  ParseGreaterThanInTemplateList(Greater, true, false);
1754  Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1755  Less, Greater);
1756  return true;
1757  }
1758 
1759  // There's no matching '>' token, this probably isn't supposed to be
1760  // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1761  TPA.Revert();
1762  return false;
1763 }
1764 
1765 void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1766  assert(Tok.is(tok::less) && "not at a potential angle bracket");
1767 
1768  bool DependentTemplateName = false;
1769  if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1770  DependentTemplateName))
1771  return;
1772 
1773  // OK, this might be a name that the user intended to be parsed as a
1774  // template-name, followed by a '<' token. Check for some easy cases.
1775 
1776  // If we have potential_template<>, then it's supposed to be a template-name.
1777  if (NextToken().is(tok::greater) ||
1778  (getLangOpts().CPlusPlus11 &&
1779  NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1780  SourceLocation Less = ConsumeToken();
1782  ParseGreaterThanInTemplateList(Greater, true, false);
1783  Actions.diagnoseExprIntendedAsTemplateName(
1784  getCurScope(), PotentialTemplateName, Less, Greater);
1785  // FIXME: Perform error recovery.
1786  PotentialTemplateName = ExprError();
1787  return;
1788  }
1789 
1790  // If we have 'potential_template<type-id', assume it's supposed to be a
1791  // template-name if there's a matching '>' later on.
1792  {
1793  // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1794  TentativeParsingAction TPA(*this);
1795  SourceLocation Less = ConsumeToken();
1796  if (isTypeIdUnambiguously() &&
1797  diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1798  TPA.Commit();
1799  // FIXME: Perform error recovery.
1800  PotentialTemplateName = ExprError();
1801  return;
1802  }
1803  TPA.Revert();
1804  }
1805 
1806  // Otherwise, remember that we saw this in case we see a potentially-matching
1807  // '>' token later on.
1809  (DependentTemplateName ? AngleBracketTracker::DependentName
1810  : AngleBracketTracker::PotentialTypo) |
1811  (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1812  : AngleBracketTracker::NoSpaceBeforeLess);
1813  AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1814  Priority);
1815 }
1816 
1817 bool Parser::checkPotentialAngleBracketDelimiter(
1818  const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1819  // If a comma in an expression context is followed by a type that can be a
1820  // template argument and cannot be an expression, then this is ill-formed,
1821  // but might be intended to be part of a template-id.
1822  if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1823  diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1824  AngleBrackets.clear(*this);
1825  return true;
1826  }
1827 
1828  // If a context that looks like a template-id is followed by '()', then
1829  // this is ill-formed, but might be intended to be a template-id
1830  // followed by '()'.
1831  if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1832  NextToken().is(tok::r_paren)) {
1833  Actions.diagnoseExprIntendedAsTemplateName(
1834  getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1835  OpToken.getLocation());
1836  AngleBrackets.clear(*this);
1837  return true;
1838  }
1839 
1840  // After a '>' (etc), we're no longer potentially in a construct that's
1841  // intended to be treated as a template-id.
1842  if (OpToken.is(tok::greater) ||
1843  (getLangOpts().CPlusPlus11 &&
1844  OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1845  AngleBrackets.clear(*this);
1846  return false;
1847 }
Defines the clang::ASTContext interface.
void ReplacePreviousCachedToken(ArrayRef< Token > NewToks)
Replace token in CachedLexPos - 1 in CachedTokens by the tokens in NewToks.
Definition: PPCaching.cpp:157
Represents a function declaration or definition.
Definition: Decl.h:1783
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1160
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1018
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:988
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization)
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:97
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
RAII object used to inform the actions that we&#39;re currently parsing a declaration.
Defines the C++ template declaration subclasses.
StringRef P
The base class of the type hierarchy.
Definition: Type.h:1450
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:47
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:113
TemplateNameKind Kind
The kind of template that Template refers to.
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
RAII object that enters a new expression evaluation context.
Definition: Sema.h:12029
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1792
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:69
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
friend class ObjCDeclContextSwitch
Definition: Parser.h:62
Defines the clang::Expr interface and subclasses for C++ expressions.
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed...
tok::TokenKind getKind() const
Definition: Token.h:92
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:1118
Information about a template-id annotation token.
Represents a struct/union/class.
Definition: Decl.h:3748
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:759
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:460
One of these records is kept for each identifier that is lexed.
Lookup for the name failed, but we&#39;re assuming it was a template name anyway.
Definition: TemplateKinds.h:50
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:446
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:971
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:992
CachedTokens Toks
Definition: Sema.h:12084
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
A non-type template parameter, stored as an expression.
void setKind(tok::TokenKind K)
Definition: Token.h:93
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:244
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e.g.
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:960
PtrTy get() const
Definition: Ownership.h:170
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
bool IsPreviousCachedToken(const Token &Tok) const
Whether Tok is the most recent token (CachedLexPos - 1) in CachedTokens.
Definition: PPCaching.cpp:139
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token...
Definition: Lexer.h:363
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
static TemplateIdAnnotation * Create(SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, IdentifierInfo *Name, OverloadedOperatorKind OperatorKind, ParsedTemplateTy OpaqueTemplateName, TemplateNameKind TemplateKind, SourceLocation LAngleLoc, SourceLocation RAngleLoc, ArrayRef< ParsedTemplateArgument > TemplateArgs, SmallVectorImpl< TemplateIdAnnotation *> &CleanupList)
Creates a new TemplateIdAnnotation with NumArgs arguments and appends it to List. ...
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type...
Definition: Parser.h:480
AttributeFactory & getAttrFactory()
Definition: Parser.h:411
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:220
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:323
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1163
A class for parsing a declarator.
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1800
void setAnnotationValue(void *val)
Definition: Token.h:230
This represents one expression.
Definition: Expr.h:108
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e...
Definition: SemaDecl.cpp:4305
Represents a character-granular source range.
int Id
Definition: ASTDiff.cpp:190
void AnnotateCachedTokens(const Token &Tok)
We notify the Preprocessor that if it is caching tokens (because backtrack is enabled) it should repl...
This file defines the classes used to store parsed information about declaration-specifiers and decla...
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:1922
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
The name refers to a concept.
Definition: TemplateKinds.h:52
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:424
static constexpr bool isOneOf()
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:126
static unsigned getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo, const SourceManager &SM, const LangOptions &LangOpts)
Get the physical length (including trigraphs and escaped newlines) of the first Characters characters...
Definition: Lexer.cpp:718
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
static bool isEndOfTemplateArgument(Token Tok)
Determine whether the given token can end a template argument.
Represents a C++ template name within the type system.
Definition: TemplateName.h:191
This is a compound statement scope.
Definition: Scope.h:130
int Depth
Definition: ASTDiff.cpp:190
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1042
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
DeclaratorContext
Definition: DeclSpec.h:1749
void setEllipsisLoc(SourceLocation EL)
Definition: DeclSpec.h:2543
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:167
The result type of a method or function.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion...
RAII object that makes &#39;>&#39; behave either as an operator or as the closing angle bracket for a templat...
const LangOptions & getLangOpts() const
Definition: Parser.h:407
static CharSourceRange getCharRange(SourceRange R)
SourceManager & getSourceManager() const
Definition: Preprocessor.h:911
A class for parsing a DeclSpec.
Stop skipping at semicolon.
Definition: Parser.h:1098
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
Represents the parsed form of a C++ template argument.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition: DeclSpec.h:2162
Encodes a location in the source.
void setLength(unsigned Len)
Definition: Token.h:135
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:314
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:179
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:144
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
TemplateNameKind ActOnDependentTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a dependent template name.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:24
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
Scope * getCurScope() const
Definition: Parser.h:414
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:201
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false)
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length)
Split the first Length characters out of the token starting at TokLoc and return a location pointing ...
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:77
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:235
bool isInvalid() const
Determine whether the given template argument is invalid.
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:99
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
static const TST TST_unspecified
Definition: DeclSpec.h:272
unsigned getLength() const
Definition: Token.h:129
Not an overloaded operator.
Definition: OperatorKinds.h:22
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:72
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn&#39;t include (top-level) commas.
Definition: ParseExpr.cpp:160
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:426
This is a scope that can contain a declaration.
Definition: Scope.h:59
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed...
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2178
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
SourceLocation ConsumeToken()
ConsumeToken - Consume the current &#39;peek token&#39; and lex the next one.
Definition: Parser.h:452
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2542
Decl * D
The template function declaration to be late parsed.
Definition: Sema.h:12086
int Priority
Definition: Format.cpp:1829
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:60
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
A template-id, e.g., f<int>.
ExprResult ExprError()
Definition: Ownership.h:279
Contains a late templated function.
Definition: Sema.h:12083
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
void setLocation(SourceLocation L)
Definition: Token.h:134
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:385
This represents a decl that may have a name.
Definition: Decl.h:223
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1049
bool isTranslationUnit() const
Definition: DeclBase.h:1859
Decl * ActOnConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr)
void * getAnnotationValue() const
Definition: Token.h:226
SourceLocation getBegin() const
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:824
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:349
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeNameContext, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName type-name: [C99 6.7.6] specifier-qualifier-list abstract-declarator[opt].
Definition: ParseDecl.cpp:42
Stop skipping at specified token, but don&#39;t skip the token itself.
Definition: Parser.h:1100
A RAII object to temporarily push a declaration context.
Definition: Sema.h:797
SourceLocation getEndLoc() const
Definition: Token.h:153