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