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