clang  9.0.0svn
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"
16 #include "clang/Parse/Parser.h"
18 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/Scope.h"
21 using namespace clang;
22 
23 /// Parse a template declaration, explicit instantiation, or
24 /// explicit specialization.
25 Decl *Parser::ParseDeclarationStartingWithTemplate(
26  DeclaratorContext Context, SourceLocation &DeclEnd,
27  ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
28  ObjCDeclContextSwitch ObjCDC(*this);
29 
30  if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
31  return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
32  DeclEnd, AccessAttrs, AS);
33  }
34  return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
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
53 Decl *Parser::ParseTemplateDeclarationOrSpecialization(
54  DeclaratorContext Context, SourceLocation &DeclEnd,
55  ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
56  assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
57  "Token does not start a template declaration.");
58 
59  // Enter template-parameter scope.
60  ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
61 
62  // Tell the action that names should be checked in the context of
63  // the declaration to come.
65  ParsingTemplateParams(*this, ParsingDeclRAIIObject::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_export, ExportLoc);
97 
98  // Consume the 'template', which should be here.
99  SourceLocation TemplateLoc;
100  if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
101  Diag(Tok.getLocation(), diag::err_expected_template);
102  return nullptr;
103  }
104 
105  // Parse the '<' template-parameter-list '>'
106  SourceLocation LAngleLoc, RAngleLoc;
107  SmallVector<NamedDecl*, 4> TemplateParams;
108  if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
109  TemplateParams, LAngleLoc, RAngleLoc)) {
110  // Skip until the semi-colon or a '}'.
111  SkipUntil(tok::r_brace, StopAtSemi | 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 =
124  if (!OptionalRequiresClauseConstraintER.isUsable()) {
125  // Skip until the semi-colon or a '}'.
126  SkipUntil(tok::r_brace, StopAtSemi | 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_export, tok::kw_template));
139 
140  unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
141  ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
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.
160 Decl *Parser::ParseSingleDeclarationAfterTemplate(
161  DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
162  ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
163  ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
164  assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
165  "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(AS, AccessAttrs, TemplateInfo,
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(Context, TemplateInfo, DeclEnd,
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(DS, TemplateInfo, AS,
198  getDeclSpecContextFromDeclaratorContext(Context));
199 
200  if (Tok.is(tok::semi)) {
201  ProhibitAttributes(prefixAttrs);
202  DeclEnd = ConsumeToken();
203  RecordDecl *AnonRecord = nullptr;
205  getCurScope(), AS, DS,
206  TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
208  TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
209  AnonRecord);
210  assert(!AnonRecord &&
211  "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(*this, DS, (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_brace, StopAtSemi | 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);
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() !=
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(DeclaratorInfo, ParsedTemplateInfo(),
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(DeclaratorInfo, TemplateInfo,
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(LateParsedAttrs, ThisDecl, true, false);
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.
320 bool Parser::ParseTemplateParameters(
321  unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
322  SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
323  // Get the template parameter list.
324  if (!TryConsumeToken(tok::less, LAngleLoc)) {
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(Depth, TemplateParams);
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();
343  } else if (!TryConsumeToken(tok::greater, RAngleLoc) && 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
358 bool
359 Parser::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::comma, tok::greater, tok::greatergreater,
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::greater, tok::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::comma, tok::greater, tok::greatergreater,
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.
394 bool 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
479 NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned 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)
487  Tok.getLocation(), Tok.getEndLoc()),
488  "typename");
489 
490  Tok.setKind(tok::kw_typename);
491  }
492 
493  return ParseTypeParameter(Depth, Position);
494  }
495 
496  if (Tok.is(tok::kw_template))
497  return ParseTemplateTemplateParameter(Depth, Position);
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(Depth, Position);
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
514 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
515  assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
516  "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::ellipsis, EllipsisLoc)) {
525  Diag(EllipsisLoc,
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::equal, tok::comma, tok::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::ellipsis, EllipsisLoc))
549  DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
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::equal, EqualLoc))
557  DefaultArg = ParseTypeName(/*Range=*/nullptr,
559 
560  return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
561  KeyLoc, ParamName, NameLoc, Depth, Position,
562  EqualLoc, DefaultArg);
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]
576 NamedDecl *
577 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
578  assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
579 
580  // Handle the template <...> part.
581  SourceLocation TemplateLoc = ConsumeToken();
582  SmallVector<NamedDecl*,8> TemplateParams;
583  SourceLocation LAngleLoc, RAngleLoc;
584  {
585  ParseScope TemplateParmScope(this, Scope::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_typename, tok::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::identifier, tok::comma, tok::greater,
609  tok::greatergreater, tok::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,
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::equal, tok::comma, tok::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::ellipsis, EllipsisLoc))
646  DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
647 
648  TemplateParameterList *ParamList =
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::equal, EqualLoc)) {
660  DefaultArg = ParseTemplateTemplateArgument();
661  if (DefaultArg.isInvalid()) {
662  Diag(Tok.getLocation(),
663  diag::err_default_template_template_parameter_not_template);
664  SkipUntil(tok::comma, tok::greater, tok::greatergreater,
666  }
667  }
668 
669  return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
670  ParamList, EllipsisLoc,
671  ParamName, NameLoc, Depth,
672  Position, EqualLoc, DefaultArg);
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
681 NamedDecl *
682 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned 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(DS, ParsedTemplateInfo(), AS_none,
688  DeclSpecContext::DSC_template_param);
689 
690  // Parse this as a typename.
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::ellipsis, EllipsisLoc))
701  DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
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::equal, EqualLoc)) {
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(GreaterThanIsOperator, false);
715  EnterExpressionEvaluationContext ConstantEvaluated(
717 
719  if (DefaultArg.isInvalid())
720  SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
721  }
722 
723  // Create the parameter.
724  return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
725  Depth, Position, EqualLoc,
726  DefaultArg.get());
727 }
728 
729 void 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 
741 void 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(EllipsisLoc, D.getIdentifierLoc(),
748  AlreadyHasEllipsis, D.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.
766 bool 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(Tok, NextToken())) {
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::greater, tok::greatergreater,
833  tok::greatergreatergreater, tok::equal, tok::greaterequal,
834  tok::greatergreaterequal, tok::equalequal)) &&
835  areTokensAdjacent(Tok, Next);
836 
837  // Diagnose this situation as appropriate.
838  if (!ObjCGenericList) {
839  // The source range of the replaced token(s).
841  TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.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(TokLoc, DiagId) << 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  TokLoc, 1, PP.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(TokLoc, GreaterLength);
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(AfterGreaterLoc, Tok.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)
904 
905  if (ConsumeLastToken)
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).
934 bool
935 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
936  SourceLocation &LAngleLoc,
937  TemplateArgList &TemplateArgs,
938  SourceLocation &RAngleLoc) {
939  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(GreaterThanIsOperator, false);
948  if (!Tok.isOneOf(tok::greater, tok::greatergreater,
949  tok::greatergreatergreater, tok::greaterequal,
950  tok::greatergreaterequal))
951  Invalid = ParseTemplateArgumentList(TemplateArgs);
952 
953  if (Invalid) {
954  // Try to find the closing '>'.
955  if (ConsumeLastToken)
956  SkipUntil(tok::greater, StopAtSemi);
957  else
958  SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
959  return true;
960  }
961  }
962 
963  return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
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 ///
1004 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1005  CXXScopeSpec &SS,
1006  SourceLocation TemplateKWLoc,
1008  bool AllowTypeAnnotation) {
1009  assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1010  assert(Template && Tok.is(tok::less) &&
1011  "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 LAngleLoc, RAngleLoc;
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) {
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(Tok, Type.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 
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.)
1099 void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
1100  assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1101 
1102  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1103  assert((TemplateId->Kind == TNK_Type_template ||
1104  TemplateId->Kind == TNK_Dependent_template_name) &&
1105  "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(Tok, Type.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.
1134 static bool isEndOfTemplateArgument(Token Tok) {
1135  return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1136 }
1137 
1138 /// Parse a C++ template template argument.
1139 ParsedTemplateArgument 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(SS, nullptr,
1157  /*EnteringContext=*/false);
1158 
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::ellipsis, EllipsisLoc);
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) &&
1180  getCurScope(), SS, TemplateKWLoc, Name,
1181  /*ObjectType=*/nullptr,
1182  /*EnteringContext=*/false, Template))
1183  Result = ParsedTemplateArgument(SS, Template, Name.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::ellipsis, EllipsisLoc);
1193 
1194  if (isEndOfTemplateArgument(Tok)) {
1195  bool MemberOfUnknownSpecialization;
1196  TemplateNameKind TNK = Actions.isTemplateName(
1197  getCurScope(), SS,
1198  /*hasTemplateKeyword=*/false, Name,
1199  /*ObjectType=*/nullptr,
1200  /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
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(SS, Template, Name.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(Result, EllipsisLoc);
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
1222 ParsedTemplateArgument 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(
1235  /*LambdaContextDecl=*/nullptr,
1237  if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1238  TypeResult TypeArg = ParseTypeName(
1239  /*Range=*/nullptr, DeclaratorContext::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();
1261  if (ExprArg.isInvalid() || !ExprArg.get())
1262  return ParsedTemplateArgument();
1263 
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.
1271 bool 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::greater, tok::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
1304 bool
1305 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1306 
1307  ColonProtectionRAIIObject ColonProtection(*this, false);
1308 
1309  do {
1310  ParsedTemplateArgument Arg = ParseTemplateArgument();
1311  SourceLocation EllipsisLoc;
1312  if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1313  Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1314 
1315  if (Arg.isInvalid()) {
1316  SkipUntil(tok::comma, tok::greater, StopAtSemi | 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.
1337 Decl *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.
1345  ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1346 
1347  return ParseSingleDeclarationAfterTemplate(
1348  Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1349  ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1350 }
1351 
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 
1363 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1364  ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1365 }
1366 
1367 /// Late parse a C++ function template in Microsoft mode.
1368 void 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  Actions, Actions.Context.getTranslationUnitDecl());
1380 
1381  SmallVector<ParseScope*, 4> TemplateParamScopeStack;
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 *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1389  llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1390  DeclContext *getDC() { return Pair.getPointer(); }
1391  bool shouldPushDC() { return Pair.getInt(); }
1392  };
1393  SmallVector<ContainingDC, 4> DeclContextsToReenter;
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  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  assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1427  "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(this, Scope::FnScope | Scope::DeclScope |
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.D, FnScope);
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  assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1450  cast<FunctionTemplateDecl>(LPT.D)
1451  ->getTemplateParameters()
1452  ->getDepth() == TemplateParameterDepth - 1) &&
1453  "TemplateParameterDepth should be greater than the depth of "
1454  "current template being instantiated!");
1455  ParseFunctionStatementBody(LPT.D, FnScope);
1456  Actions.UnmarkAsLateParsedTemplate(FunD);
1457  } else
1458  Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1459  }
1460 
1461  // Exit scopes.
1462  FnScope.Exit();
1464  TemplateParamScopeStack.rbegin();
1465  for (; I != TemplateParamScopeStack.rend(); ++I)
1466  delete *I;
1467 }
1468 
1469 /// Lex a delayed template function for late parsing.
1470 void 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_brace, Toks, /*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_brace, Toks, /*StopAtSemi=*/false);
1481  ConsumeAndStoreUntil(tok::r_brace, Toks, /*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.
1490 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1491  TentativeParsingAction TPA(*this);
1492  // FIXME: We could look at the token sequence in a lot more detail here.
1493  if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1495  TPA.Commit();
1496 
1498  ParseGreaterThanInTemplateList(Greater, true, false);
1499  Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1500  Less, Greater);
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 
1510 void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1511  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::greatergreater, tok::greatergreatergreater))) {
1525  SourceLocation Less = ConsumeToken();
1527  ParseGreaterThanInTemplateList(Greater, true, false);
1528  Actions.diagnoseExprIntendedAsTemplateName(
1529  getCurScope(), PotentialTemplateName, Less, Greater);
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(PotentialTemplateName, Less)) {
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 
1562 bool Parser::checkPotentialAngleBracketDelimiter(
1563  const AngleBracketTracker::Loc &LAngle, const 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.TemplateName, LAngle.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.TemplateName, LAngle.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 }
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:169
Represents a function declaration or definition.
Definition: Decl.h:1737
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:1133
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:991
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:961
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:94
The name refers to a dependent template name:
Definition: TemplateKinds.h:45
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
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:1414
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:97
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
static TemplateIdAnnotation * Create(CXXScopeSpec SS, 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. ...
RAII object that enters a new expression evaluation context.
Definition: Sema.h:11032
void EnterToken(const Token &Tok)
Enters a token in the token stream to be lexed next.
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1764
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:67
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:33
friend class ObjCDeclContextSwitch
Definition: Parser.h:61
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed...
tok::TokenKind getKind() const
Definition: Token.h:89
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:1080
Information about a template-id annotation token.
Represents a struct/union/class.
Definition: Decl.h:3592
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:745
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:446
One of these records is kept for each identifier that is lexed.
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:422
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:944
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:965
CachedTokens Toks
Definition: Sema.h:11087
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:90
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:933
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:151
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:348
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:62
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type...
Definition: Parser.h:466
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:217
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:318
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:1776
void setAnnotationValue(void *val)
Definition: Token.h:227
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:4118
Represents a character-granular source range.
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:1858
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:410
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:123
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:710
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:71
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:178
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:1015
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
DeclaratorContext
Definition: DeclSpec.h:1722
void setEllipsisLoc(SourceLocation EL)
Definition: DeclSpec.h:2455
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:393
static CharSourceRange getCharRange(SourceRange R)
SourceManager & getSourceManager() const
Definition: Preprocessor.h:818
A class for parsing a DeclSpec.
Stop skipping at semicolon.
Definition: Parser.h:1060
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:217
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition: DeclSpec.h:2116
Encodes a location in the source.
void setLength(unsigned Len)
Definition: Token.h:132
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:309
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:176
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:141
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
Scope * getCurScope() const
Definition: Parser.h:400
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:200
bool isNot(tok::TokenKind K) const
Definition: Token.h:95
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:1265
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:117
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:234
bool isInvalid() const
Determine whether the given template argument is invalid.
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:96
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:29
static const TST TST_unspecified
Definition: DeclSpec.h:271
unsigned getLength() const
Definition: Token.h:126
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed...
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.
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:159
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:91
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:412
This is a scope that can contain a declaration.
Definition: Scope.h:59
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2132
bool isSet() const
Deprecated.
Definition: DeclSpec.h:208
TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false)
Captures information about "declaration specifiers".
Definition: DeclSpec.h:227
SourceLocation ConsumeToken()
ConsumeToken - Consume the current &#39;peek token&#39; and lex the next one.
Definition: Parser.h:438
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2454
Decl * D
The template function declaration to be late parsed.
Definition: Sema.h:11089
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:190
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:128
A template-id, e.g., f<int>.
ExprResult ExprError()
Definition: Ownership.h:279
Contains a late templated function.
Definition: Sema.h:11086
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:65
void setLocation(SourceLocation L)
Definition: Token.h:131
A trivial tuple used to represent a source range.
This represents a decl that may have a name.
Definition: Decl.h:248
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1022
bool isTranslationUnit() const
Definition: DeclBase.h:1831
SourceLocation getBegin() const
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:882
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:1062
A RAII object to temporarily push a declaration context.
Definition: Sema.h:778
SourceLocation getEndLoc() const
Definition: Token.h:150