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