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