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(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(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 return Actions.ConvertDeclToDeclGroup(
172 Ptr: ParseConceptDefinition(TemplateInfo, DeclEnd));
173
174 return ParseDeclarationAfterTemplate(
175 Context, TemplateInfo, DiagsFromParams&: 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(K: 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 Ptr: ParseStaticAssertDeclaration(DeclEnd));
202 }
203
204 // We are parsing a member template.
205 if (Context == DeclaratorContext::Member)
206 return ParseCXXClassMemberDeclaration(AS, Attr&: AccessAttrs, TemplateInfo,
207 DiagsFromTParams: &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(Attrs&: DeclAttrs) ||
217 MaybeParseGNUAttributes(Attrs&: DeclSpecAttrs))
218 ;
219
220 if (Tok.is(K: tok::kw_using))
221 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
222 Attrs&: 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(attrs&: DeclSpecAttrs);
230
231 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
232 DSC: getDeclSpecContextFromDeclaratorContext(Context));
233
234 if (Tok.is(K: tok::semi)) {
235 ProhibitAttributes(Attrs&: DeclAttrs);
236 DeclEnd = ConsumeToken();
237 RecordDecl *AnonRecord = nullptr;
238 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
239 S: getCurScope(), AS, DS, DeclAttrs: ParsedAttributesView::none(),
240 TemplateParams: TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
241 : MultiTemplateParamsArg(),
242 IsExplicitInstantiation: TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
243 AnonRecord);
244 Actions.ActOnDefinedDeclarationSpecifier(D: Decl);
245 assert(!AnonRecord &&
246 "Anonymous unions/structs should not be valid with template");
247 DS.complete(D: Decl);
248 return Actions.ConvertDeclToDeclGroup(Ptr: Decl);
249 }
250
251 if (DS.hasTagDefinition())
252 Actions.ActOnDefinedDeclarationSpecifier(D: DS.getRepAsDecl());
253
254 // Move the attributes from the prefix into the DS.
255 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
256 ProhibitAttributes(Attrs&: DeclAttrs);
257
258 return ParseDeclGroup(DS, Context, Attrs&: DeclAttrs, TemplateInfo, DeclEnd: &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) <<
280 FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
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(T: tok::semi);
292 return nullptr;
293 }
294
295 if (SS.isNotEmpty())
296 Diag(SS.getBeginLoc(),
297 diag::err_concept_definition_not_identifier);
298
299 UnqualifiedId Result;
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(T: 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(T: tok::semi);
313 return nullptr;
314 }
315
316 IdentifierInfo *Id = Result.Identifier;
317 SourceLocation IdLoc = Result.getBeginLoc();
318
319 DiagnoseAndSkipCXX11Attributes();
320
321 if (!TryConsumeToken(Expected: tok::equal)) {
322 Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
323 SkipUntil(T: tok::semi);
324 return nullptr;
325 }
326
327 ExprResult ConstraintExprResult =
328 Actions.CorrectDelayedTyposInExpr(ER: ParseConstraintExpression());
329 if (ConstraintExprResult.isInvalid()) {
330 SkipUntil(T: 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(S: getCurScope(),
338 TemplateParameterLists: *TemplateInfo.TemplateParams,
339 Name: Id, NameLoc: 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(Expected: tok::less, Loc&: 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(K: tok::greater) && !Tok.is(K: tok::greatergreater)) {
365 TemplateScopes.Enter(ScopeFlags: Scope::TemplateParamScope);
366 Failed = ParseTemplateParameterList(Depth, TemplateParams);
367 }
368
369 if (Tok.is(K: 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();
377 Tok.setLocation(Tok.getLocation().getLocWithOffset(Offset: 1));
378 } else if (!TryConsumeToken(Expected: tok::greater, Loc&: 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, Position: TemplateParams.size())) {
400 TemplateParams.push_back(Elt: TmpParam);
401 } else {
402 // If we failed to parse a template parameter, skip until we find
403 // a comma or closing brace.
404 SkipUntil(T1: tok::comma, T2: tok::greater, T3: tok::greatergreater,
405 Flags: StopAtSemi | StopBeforeMatch);
406 }
407
408 // Did we find a comma or the end of the template parameter list?
409 if (Tok.is(K: tok::comma)) {
410 ConsumeToken();
411 } else if (Tok.isOneOf(K1: tok::greater, K2: 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(T1: tok::comma, T2: tok::greater, T3: tok::greatergreater,
420 Flags: StopAtSemi | StopBeforeMatch);
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(K: 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(N: 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(N: Tok.is(K: tok::annot_cxxscope) ? 2 : 1)
470 .isOneOf(K1: tok::kw_auto, K2: 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(K: tok::kw_typename) && Tok.isNot(K: 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(N: 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(K: tok::kw_typedef)) {
537 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
538
539 Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
540 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
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.
559 DeclSpec DS(getAttrFactory());
560 DS.SetTypeSpecError();
561 Declarator D(DS, ParsedAttributesView::none(),
562 DeclaratorContext::TemplateParam);
563 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
564 D.setInvalidType(true);
565 NamedDecl *ErrorParam = Actions.ActOnNonTypeTemplateParameter(
566 S: getCurScope(), D, Depth, Position, /*EqualLoc=*/SourceLocation(),
567 /*DefaultArg=*/nullptr);
568 ErrorParam->setInvalidDecl(true);
569 SkipUntil(T1: tok::comma, T2: tok::greater, T3: tok::greatergreater,
570 Flags: StopAtSemi | StopBeforeMatch);
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(K: 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(K: tok::annot_cxxscope) ? NextToken() : Tok;
591 if (T.isNot(K: 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() {
607 if (!getLangOpts().CPlusPlus20)
608 return false;
609 CXXScopeSpec SS;
610 bool WasScopeAnnotation = Tok.is(K: 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(K: tok::identifier)) {
627 UnqualifiedId PossibleConceptName;
628 PossibleConceptName.setIdentifier(Id: Tok.getIdentifierInfo(),
629 IdLoc: Tok.getLocation());
630
631 TemplateTy PossibleConcept;
632 bool MemberOfUnknownSpecialization = false;
633 auto TNK = Actions.isTemplateName(S: getCurScope(), SS,
634 /*hasTemplateKeyword=*/false,
635 Name: PossibleConceptName,
636 /*ObjectType=*/ParsedType(),
637 /*EnteringContext=*/false,
638 Template&: PossibleConcept,
639 MemberOfUnknownSpecialization,
640 /*Disambiguation=*/true);
641 if (MemberOfUnknownSpecialization || !PossibleConcept ||
642 TNK != TNK_Concept_template) {
643 if (SS.isNotEmpty())
644 AnnotateScopeToken(SS, IsNewAnnotation: !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(Template: PossibleConcept, TNK, SS,
652 /*TemplateKWLoc=*/SourceLocation(),
653 TemplateName&: PossibleConceptName,
654 /*AllowTypeAnnotation=*/false,
655 /*TypeConstraint=*/true))
656 return true;
657 }
658
659 if (SS.isNotEmpty())
660 AnnotateScopeToken(SS, IsNewAnnotation: !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;
680 TemplateIdAnnotation *TypeConstraint = nullptr;
681 bool TypenameKeyword = false;
682 SourceLocation KeyLoc;
683 ParseOptionalCXXScopeSpecifier(SS&: TypeConstraintSS, /*ObjectType=*/nullptr,
684 /*ObjectHasErrors=*/false,
685 /*EnteringContext*/ false);
686 if (Tok.is(K: tok::annot_template_id)) {
687 // Consume the 'type-constraint'.
688 TypeConstraint =
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(K: tok::kw_typename);
699 KeyLoc = ConsumeToken();
700 }
701
702 // Grab the ellipsis (if given).
703 SourceLocation EllipsisLoc;
704 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc)) {
705 Diag(EllipsisLoc,
706 getLangOpts().CPlusPlus11
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(K: tok::identifier)) {
715 ParamName = Tok.getIdentifierInfo();
716 ConsumeToken();
717 } else if (Tok.isOneOf(K1: tok::equal, Ks: tok::comma, Ks: tok::greater,
718 Ks: 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(Expected: tok::ellipsis, Loc&: EllipsisLoc))
729 DiagnoseMisplacedEllipsis(EllipsisLoc, CorrectLoc: NameLoc, AlreadyHasEllipsis, IdentifierHasName: 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(Expected: tok::equal, Loc&: 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 =
744 ParseTypeName(/*Range=*/nullptr, Context: DeclaratorContext::TemplateTypeArg)
745 .get();
746 }
747
748 NamedDecl *NewDecl = Actions.ActOnTypeParameter(S: getCurScope(),
749 Typename: TypenameKeyword, EllipsisLoc,
750 KeyLoc, ParamName, ParamNameLoc: NameLoc,
751 Depth, Position, EqualLoc,
752 DefaultArg,
753 HasTypeConstraint: TypeConstraint != nullptr);
754
755 if (TypeConstraint) {
756 Actions.ActOnTypeConstraint(SS: TypeConstraintSS, TypeConstraint,
757 ConstrainedParameter: cast<TemplateTypeParmDecl>(Val: 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(TemplateScopes&: TemplateParmScope, Depth: Depth + 1, TemplateParams,
788 LAngleLoc, RAngleLoc)) {
789 return nullptr;
790 }
791 if (TryConsumeToken(Expected: tok::kw_requires)) {
792 OptionalRequiresClauseConstraintER =
793 Actions.ActOnRequiresClause(ConstraintExpr: ParseConstraintLogicalOrExpression(
794 /*IsTrailingRequiresClause=*/false));
795 if (!OptionalRequiresClauseConstraintER.isUsable()) {
796 SkipUntil(T1: tok::comma, T2: tok::greater, T3: tok::greatergreater,
797 Flags: StopAtSemi | StopBeforeMatch);
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 if (!TryConsumeToken(Expected: tok::kw_class)) {
809 bool Replace = Tok.isOneOf(K1: tok::kw_typename, K2: tok::kw_struct);
810 const Token &Next = Tok.is(K: tok::kw_struct) ? NextToken() : Tok;
811 if (Tok.is(K: tok::kw_typename)) {
812 Diag(Tok.getLocation(),
813 getLangOpts().CPlusPlus17
814 ? diag::warn_cxx14_compat_template_template_param_typename
815 : diag::ext_template_template_param_typename)
816 << (!getLangOpts().CPlusPlus17
817 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
818 : FixItHint());
819 } else if (Next.isOneOf(K1: tok::identifier, Ks: tok::comma, Ks: tok::greater,
820 Ks: tok::greatergreater, Ks: tok::ellipsis)) {
821 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
822 << getLangOpts().CPlusPlus17
823 << (Replace
824 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
825 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
826 } else
827 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
828 << getLangOpts().CPlusPlus17;
829
830 if (Replace)
831 ConsumeToken();
832 }
833
834 // Parse the ellipsis, if given.
835 SourceLocation EllipsisLoc;
836 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
837 Diag(EllipsisLoc,
838 getLangOpts().CPlusPlus11
839 ? diag::warn_cxx98_compat_variadic_templates
840 : diag::ext_variadic_templates);
841
842 // Get the identifier, if given.
843 SourceLocation NameLoc = Tok.getLocation();
844 IdentifierInfo *ParamName = nullptr;
845 if (Tok.is(K: tok::identifier)) {
846 ParamName = Tok.getIdentifierInfo();
847 ConsumeToken();
848 } else if (Tok.isOneOf(K1: tok::equal, Ks: tok::comma, Ks: tok::greater,
849 Ks: tok::greatergreater)) {
850 // Unnamed template parameter. Don't have to do anything here, just
851 // don't consume this token.
852 } else {
853 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
854 return nullptr;
855 }
856
857 // Recover from misplaced ellipsis.
858 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
859 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc))
860 DiagnoseMisplacedEllipsis(EllipsisLoc, CorrectLoc: NameLoc, AlreadyHasEllipsis, IdentifierHasName: true);
861
862 TemplateParameterList *ParamList = Actions.ActOnTemplateParameterList(
863 Depth, ExportLoc: SourceLocation(), TemplateLoc, LAngleLoc, Params: TemplateParams,
864 RAngleLoc, RequiresClause: OptionalRequiresClauseConstraintER.get());
865
866 // Grab a default argument (if available).
867 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
868 // we introduce the template parameter into the local scope.
869 SourceLocation EqualLoc;
870 ParsedTemplateArgument DefaultArg;
871 if (TryConsumeToken(Expected: tok::equal, Loc&: EqualLoc)) {
872 DefaultArg = ParseTemplateTemplateArgument();
873 if (DefaultArg.isInvalid()) {
874 Diag(Tok.getLocation(),
875 diag::err_default_template_template_parameter_not_template);
876 SkipUntil(T1: tok::comma, T2: tok::greater, T3: tok::greatergreater,
877 Flags: StopAtSemi | StopBeforeMatch);
878 }
879 }
880
881 return Actions.ActOnTemplateTemplateParameter(S: getCurScope(), TmpLoc: TemplateLoc,
882 Params: ParamList, EllipsisLoc,
883 ParamName, ParamNameLoc: NameLoc, Depth,
884 Position, EqualLoc, DefaultArg);
885}
886
887/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
888/// template parameters (e.g., in "template<int Size> class array;").
889///
890/// template-parameter:
891/// ...
892/// parameter-declaration
893NamedDecl *
894Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
895 // Parse the declaration-specifiers (i.e., the type).
896 // FIXME: The type should probably be restricted in some way... Not all
897 // declarators (parts of declarators?) are accepted for parameters.
898 DeclSpec DS(AttrFactory);
899 ParseDeclarationSpecifiers(DS, TemplateInfo: ParsedTemplateInfo(), AS: AS_none,
900 DSC: DeclSpecContext::DSC_template_param);
901
902 // Parse this as a typename.
903 Declarator ParamDecl(DS, ParsedAttributesView::none(),
904 DeclaratorContext::TemplateParam);
905 ParseDeclarator(D&: ParamDecl);
906 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
907 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
908 return nullptr;
909 }
910
911 // Recover from misplaced ellipsis.
912 SourceLocation EllipsisLoc;
913 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc))
914 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D&: ParamDecl);
915
916 // If there is a default value, parse it.
917 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
918 // we introduce the template parameter into the local scope.
919 SourceLocation EqualLoc;
920 ExprResult DefaultArg;
921 if (TryConsumeToken(Expected: tok::equal, Loc&: EqualLoc)) {
922 if (Tok.is(K: tok::l_paren) && NextToken().is(K: tok::l_brace)) {
923 Diag(Tok.getLocation(), diag::err_stmt_expr_in_default_arg) << 1;
924 SkipUntil(T1: tok::comma, T2: tok::greater, Flags: StopAtSemi | StopBeforeMatch);
925 } else {
926 // C++ [temp.param]p15:
927 // When parsing a default template-argument for a non-type
928 // template-parameter, the first non-nested > is taken as the
929 // end of the template-parameter-list rather than a greater-than
930 // operator.
931 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
932
933 // The default argument may declare template parameters, notably
934 // if it contains a generic lambda, so we need to increase
935 // the template depth as these parameters would not be instantiated
936 // at the current level.
937 TemplateParameterDepthRAII CurTemplateDepthTracker(
938 TemplateParameterDepth);
939 ++CurTemplateDepthTracker;
940 EnterExpressionEvaluationContext ConstantEvaluated(
941 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
942 DefaultArg = Actions.CorrectDelayedTyposInExpr(ER: ParseInitializer());
943 if (DefaultArg.isInvalid())
944 SkipUntil(T1: tok::comma, T2: tok::greater, Flags: StopAtSemi | StopBeforeMatch);
945 }
946 }
947
948 // Create the parameter.
949 return Actions.ActOnNonTypeTemplateParameter(S: getCurScope(), D&: ParamDecl,
950 Depth, Position, EqualLoc,
951 DefaultArg: DefaultArg.get());
952}
953
954void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
955 SourceLocation CorrectLoc,
956 bool AlreadyHasEllipsis,
957 bool IdentifierHasName) {
958 FixItHint Insertion;
959 if (!AlreadyHasEllipsis)
960 Insertion = FixItHint::CreateInsertion(InsertionLoc: CorrectLoc, Code: "...");
961 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
962 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
963 << !IdentifierHasName;
964}
965
966void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
967 Declarator &D) {
968 assert(EllipsisLoc.isValid());
969 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
970 if (!AlreadyHasEllipsis)
971 D.setEllipsisLoc(EllipsisLoc);
972 DiagnoseMisplacedEllipsis(EllipsisLoc, CorrectLoc: D.getIdentifierLoc(),
973 AlreadyHasEllipsis, IdentifierHasName: D.hasName());
974}
975
976/// Parses a '>' at the end of a template list.
977///
978/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
979/// to determine if these tokens were supposed to be a '>' followed by
980/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
981///
982/// \param RAngleLoc the location of the consumed '>'.
983///
984/// \param ConsumeLastToken if true, the '>' is consumed.
985///
986/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
987/// type parameter or type argument list, rather than a C++ template parameter
988/// or argument list.
989///
990/// \returns true, if current token does not start with '>', false otherwise.
991bool Parser::ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
992 SourceLocation &RAngleLoc,
993 bool ConsumeLastToken,
994 bool ObjCGenericList) {
995 // What will be left once we've consumed the '>'.
996 tok::TokenKind RemainingToken;
997 const char *ReplacementStr = "> >";
998 bool MergeWithNextToken = false;
999
1000 switch (Tok.getKind()) {
1001 default:
1002 Diag(getEndOfPreviousToken(), diag::err_expected) << tok::greater;
1003 Diag(LAngleLoc, diag::note_matching) << tok::less;
1004 return true;
1005
1006 case tok::greater:
1007 // Determine the location of the '>' token. Only consume this token
1008 // if the caller asked us to.
1009 RAngleLoc = Tok.getLocation();
1010 if (ConsumeLastToken)
1011 ConsumeToken();
1012 return false;
1013
1014 case tok::greatergreater:
1015 RemainingToken = tok::greater;
1016 break;
1017
1018 case tok::greatergreatergreater:
1019 RemainingToken = tok::greatergreater;
1020 break;
1021
1022 case tok::greaterequal:
1023 RemainingToken = tok::equal;
1024 ReplacementStr = "> =";
1025
1026 // Join two adjacent '=' tokens into one, for cases like:
1027 // void (*p)() = f<int>;
1028 // return f<int>==p;
1029 if (NextToken().is(K: tok::equal) &&
1030 areTokensAdjacent(A: Tok, B: NextToken())) {
1031 RemainingToken = tok::equalequal;
1032 MergeWithNextToken = true;
1033 }
1034 break;
1035
1036 case tok::greatergreaterequal:
1037 RemainingToken = tok::greaterequal;
1038 break;
1039 }
1040
1041 // This template-id is terminated by a token that starts with a '>'.
1042 // Outside C++11 and Objective-C, this is now error recovery.
1043 //
1044 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
1045 // extend that treatment to also apply to the '>>>' token.
1046 //
1047 // Objective-C allows this in its type parameter / argument lists.
1048
1049 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
1050 SourceLocation TokLoc = Tok.getLocation();
1051 Token Next = NextToken();
1052
1053 // Whether splitting the current token after the '>' would undesirably result
1054 // in the remaining token pasting with the token after it. This excludes the
1055 // MergeWithNextToken cases, which we've already handled.
1056 bool PreventMergeWithNextToken =
1057 (RemainingToken == tok::greater ||
1058 RemainingToken == tok::greatergreater) &&
1059 (Next.isOneOf(K1: tok::greater, Ks: tok::greatergreater,
1060 Ks: tok::greatergreatergreater, Ks: tok::equal, Ks: tok::greaterequal,
1061 Ks: tok::greatergreaterequal, Ks: tok::equalequal)) &&
1062 areTokensAdjacent(A: Tok, B: Next);
1063
1064 // Diagnose this situation as appropriate.
1065 if (!ObjCGenericList) {
1066 // The source range of the replaced token(s).
1067 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
1068 B: TokLoc, E: Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: 2, SM: PP.getSourceManager(),
1069 LangOpts: getLangOpts()));
1070
1071 // A hint to put a space between the '>>'s. In order to make the hint as
1072 // clear as possible, we include the characters either side of the space in
1073 // the replacement, rather than just inserting a space at SecondCharLoc.
1074 FixItHint Hint1 = FixItHint::CreateReplacement(RemoveRange: ReplacementRange,
1075 Code: ReplacementStr);
1076
1077 // A hint to put another space after the token, if it would otherwise be
1078 // lexed differently.
1079 FixItHint Hint2;
1080 if (PreventMergeWithNextToken)
1081 Hint2 = FixItHint::CreateInsertion(InsertionLoc: Next.getLocation(), Code: " ");
1082
1083 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1084 if (getLangOpts().CPlusPlus11 &&
1085 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
1086 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1087 else if (Tok.is(tok::greaterequal))
1088 DiagId = diag::err_right_angle_bracket_equal_needs_space;
1089 Diag(Loc: TokLoc, DiagID: DiagId) << Hint1 << Hint2;
1090 }
1091
1092 // Find the "length" of the resulting '>' token. This is not always 1, as it
1093 // can contain escaped newlines.
1094 unsigned GreaterLength = Lexer::getTokenPrefixLength(
1095 TokStart: TokLoc, CharNo: 1, SM: PP.getSourceManager(), LangOpts: getLangOpts());
1096
1097 // Annotate the source buffer to indicate that we split the token after the
1098 // '>'. This allows us to properly find the end of, and extract the spelling
1099 // of, the '>' token later.
1100 RAngleLoc = PP.SplitToken(TokLoc, Length: GreaterLength);
1101
1102 // Strip the initial '>' from the token.
1103 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1104
1105 Token Greater = Tok;
1106 Greater.setLocation(RAngleLoc);
1107 Greater.setKind(tok::greater);
1108 Greater.setLength(GreaterLength);
1109
1110 unsigned OldLength = Tok.getLength();
1111 if (MergeWithNextToken) {
1112 ConsumeToken();
1113 OldLength += Tok.getLength();
1114 }
1115
1116 Tok.setKind(RemainingToken);
1117 Tok.setLength(OldLength - GreaterLength);
1118
1119 // Split the second token if lexing it normally would lex a different token
1120 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1121 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(Offset: GreaterLength);
1122 if (PreventMergeWithNextToken)
1123 AfterGreaterLoc = PP.SplitToken(TokLoc: AfterGreaterLoc, Length: Tok.getLength());
1124 Tok.setLocation(AfterGreaterLoc);
1125
1126 // Update the token cache to match what we just did if necessary.
1127 if (CachingTokens) {
1128 // If the previous cached token is being merged, delete it.
1129 if (MergeWithNextToken)
1130 PP.ReplacePreviousCachedToken(NewToks: {});
1131
1132 if (ConsumeLastToken)
1133 PP.ReplacePreviousCachedToken(NewToks: {Greater, Tok});
1134 else
1135 PP.ReplacePreviousCachedToken(NewToks: {Greater});
1136 }
1137
1138 if (ConsumeLastToken) {
1139 PrevTokLocation = RAngleLoc;
1140 } else {
1141 PrevTokLocation = TokBeforeGreaterLoc;
1142 PP.EnterToken(Tok, /*IsReinject=*/true);
1143 Tok = Greater;
1144 }
1145
1146 return false;
1147}
1148
1149/// Parses a template-id that after the template name has
1150/// already been parsed.
1151///
1152/// This routine takes care of parsing the enclosed template argument
1153/// list ('<' template-parameter-list [opt] '>') and placing the
1154/// results into a form that can be transferred to semantic analysis.
1155///
1156/// \param ConsumeLastToken if true, then we will consume the last
1157/// token that forms the template-id. Otherwise, we will leave the
1158/// last token in the stream (e.g., so that it can be replaced with an
1159/// annotation token).
1160bool Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1161 SourceLocation &LAngleLoc,
1162 TemplateArgList &TemplateArgs,
1163 SourceLocation &RAngleLoc,
1164 TemplateTy Template) {
1165 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1166
1167 // Consume the '<'.
1168 LAngleLoc = ConsumeToken();
1169
1170 // Parse the optional template-argument-list.
1171 bool Invalid = false;
1172 {
1173 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1174 if (!Tok.isOneOf(K1: tok::greater, Ks: tok::greatergreater,
1175 Ks: tok::greatergreatergreater, Ks: tok::greaterequal,
1176 Ks: tok::greatergreaterequal))
1177 Invalid = ParseTemplateArgumentList(TemplateArgs, Template, OpenLoc: LAngleLoc);
1178
1179 if (Invalid) {
1180 // Try to find the closing '>'.
1181 if (getLangOpts().CPlusPlus11)
1182 SkipUntil(T1: tok::greater, T2: tok::greatergreater,
1183 T3: tok::greatergreatergreater, Flags: StopAtSemi | StopBeforeMatch);
1184 else
1185 SkipUntil(T: tok::greater, Flags: StopAtSemi | StopBeforeMatch);
1186 }
1187 }
1188
1189 return ParseGreaterThanInTemplateList(LAngleLoc, RAngleLoc, ConsumeLastToken,
1190 /*ObjCGenericList=*/false) ||
1191 Invalid;
1192}
1193
1194/// Replace the tokens that form a simple-template-id with an
1195/// annotation token containing the complete template-id.
1196///
1197/// The first token in the stream must be the name of a template that
1198/// is followed by a '<'. This routine will parse the complete
1199/// simple-template-id and replace the tokens with a single annotation
1200/// token with one of two different kinds: if the template-id names a
1201/// type (and \p AllowTypeAnnotation is true), the annotation token is
1202/// a type annotation that includes the optional nested-name-specifier
1203/// (\p SS). Otherwise, the annotation token is a template-id
1204/// annotation that does not include the optional
1205/// nested-name-specifier.
1206///
1207/// \param Template the declaration of the template named by the first
1208/// token (an identifier), as returned from \c Action::isTemplateName().
1209///
1210/// \param TNK the kind of template that \p Template
1211/// refers to, as returned from \c Action::isTemplateName().
1212///
1213/// \param SS if non-NULL, the nested-name-specifier that precedes
1214/// this template name.
1215///
1216/// \param TemplateKWLoc if valid, specifies that this template-id
1217/// annotation was preceded by the 'template' keyword and gives the
1218/// location of that keyword. If invalid (the default), then this
1219/// template-id was not preceded by a 'template' keyword.
1220///
1221/// \param AllowTypeAnnotation if true (the default), then a
1222/// simple-template-id that refers to a class template, template
1223/// template parameter, or other template that produces a type will be
1224/// replaced with a type annotation token. Otherwise, the
1225/// simple-template-id is always replaced with a template-id
1226/// annotation token.
1227///
1228/// \param TypeConstraint if true, then this is actually a type-constraint,
1229/// meaning that the template argument list can be omitted (and the template in
1230/// question must be a concept).
1231///
1232/// If an unrecoverable parse error occurs and no annotation token can be
1233/// formed, this function returns true.
1234///
1235bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1236 CXXScopeSpec &SS,
1237 SourceLocation TemplateKWLoc,
1238 UnqualifiedId &TemplateName,
1239 bool AllowTypeAnnotation,
1240 bool TypeConstraint) {
1241 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1242 assert((Tok.is(tok::less) || TypeConstraint) &&
1243 "Parser isn't at the beginning of a template-id");
1244 assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1245 "a type annotation");
1246 assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1247 "must accompany a concept name");
1248 assert((Template || TNK == TNK_Non_template) && "missing template name");
1249
1250 // Consume the template-name.
1251 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1252
1253 // Parse the enclosed template argument list.
1254 SourceLocation LAngleLoc, RAngleLoc;
1255 TemplateArgList TemplateArgs;
1256 bool ArgsInvalid = false;
1257 if (!TypeConstraint || Tok.is(K: tok::less)) {
1258 ArgsInvalid = ParseTemplateIdAfterTemplateName(
1259 ConsumeLastToken: false, LAngleLoc, TemplateArgs, RAngleLoc, Template);
1260 // If we couldn't recover from invalid arguments, don't form an annotation
1261 // token -- we don't know how much to annotate.
1262 // FIXME: This can lead to duplicate diagnostics if we retry parsing this
1263 // template-id in another context. Try to annotate anyway?
1264 if (RAngleLoc.isInvalid())
1265 return true;
1266 }
1267
1268 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1269
1270 // Build the annotation token.
1271 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1272 TypeResult Type = ArgsInvalid
1273 ? TypeError()
1274 : Actions.ActOnTemplateIdType(
1275 S: getCurScope(), SS, TemplateKWLoc, Template,
1276 TemplateII: TemplateName.Identifier, TemplateIILoc: TemplateNameLoc,
1277 LAngleLoc, TemplateArgs: TemplateArgsPtr, RAngleLoc);
1278
1279 Tok.setKind(tok::annot_typename);
1280 setTypeAnnotation(Tok, T: Type);
1281 if (SS.isNotEmpty())
1282 Tok.setLocation(SS.getBeginLoc());
1283 else if (TemplateKWLoc.isValid())
1284 Tok.setLocation(TemplateKWLoc);
1285 else
1286 Tok.setLocation(TemplateNameLoc);
1287 } else {
1288 // Build a template-id annotation token that can be processed
1289 // later.
1290 Tok.setKind(tok::annot_template_id);
1291
1292 IdentifierInfo *TemplateII =
1293 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1294 ? TemplateName.Identifier
1295 : nullptr;
1296
1297 OverloadedOperatorKind OpKind =
1298 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1299 ? OO_None
1300 : TemplateName.OperatorFunctionId.Operator;
1301
1302 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1303 TemplateKWLoc, TemplateNameLoc, Name: TemplateII, OperatorKind: OpKind, OpaqueTemplateName: Template, TemplateKind: TNK,
1304 LAngleLoc, RAngleLoc, TemplateArgs, ArgsInvalid, CleanupList&: TemplateIds);
1305
1306 Tok.setAnnotationValue(TemplateId);
1307 if (TemplateKWLoc.isValid())
1308 Tok.setLocation(TemplateKWLoc);
1309 else
1310 Tok.setLocation(TemplateNameLoc);
1311 }
1312
1313 // Common fields for the annotation token
1314 Tok.setAnnotationEndLoc(RAngleLoc);
1315
1316 // In case the tokens were cached, have Preprocessor replace them with the
1317 // annotation token.
1318 PP.AnnotateCachedTokens(Tok);
1319 return false;
1320}
1321
1322/// Replaces a template-id annotation token with a type
1323/// annotation token.
1324///
1325/// If there was a failure when forming the type from the template-id,
1326/// a type annotation token will still be created, but will have a
1327/// NULL type pointer to signify an error.
1328///
1329/// \param SS The scope specifier appearing before the template-id, if any.
1330///
1331/// \param AllowImplicitTypename whether this is a context where T::type
1332/// denotes a dependent type.
1333/// \param IsClassName Is this template-id appearing in a context where we
1334/// know it names a class, such as in an elaborated-type-specifier or
1335/// base-specifier? ('typename' and 'template' are unneeded and disallowed
1336/// in those contexts.)
1337void Parser::AnnotateTemplateIdTokenAsType(
1338 CXXScopeSpec &SS, ImplicitTypenameContext AllowImplicitTypename,
1339 bool IsClassName) {
1340 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1341
1342 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok);
1343 assert(TemplateId->mightBeType() &&
1344 "Only works for type and dependent templates");
1345
1346 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1347 TemplateId->NumArgs);
1348
1349 TypeResult Type =
1350 TemplateId->isInvalid()
1351 ? TypeError()
1352 : Actions.ActOnTemplateIdType(
1353 S: getCurScope(), SS, TemplateKWLoc: TemplateId->TemplateKWLoc,
1354 Template: TemplateId->Template, TemplateII: TemplateId->Name,
1355 TemplateIILoc: TemplateId->TemplateNameLoc, LAngleLoc: TemplateId->LAngleLoc,
1356 TemplateArgs: TemplateArgsPtr, RAngleLoc: TemplateId->RAngleLoc,
1357 /*IsCtorOrDtorName=*/false, IsClassName, AllowImplicitTypename);
1358 // Create the new "type" annotation token.
1359 Tok.setKind(tok::annot_typename);
1360 setTypeAnnotation(Tok, T: Type);
1361 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1362 Tok.setLocation(SS.getBeginLoc());
1363 // End location stays the same
1364
1365 // Replace the template-id annotation token, and possible the scope-specifier
1366 // that precedes it, with the typename annotation token.
1367 PP.AnnotateCachedTokens(Tok);
1368}
1369
1370/// Determine whether the given token can end a template argument.
1371static bool isEndOfTemplateArgument(Token Tok) {
1372 // FIXME: Handle '>>>'.
1373 return Tok.isOneOf(K1: tok::comma, Ks: tok::greater, Ks: tok::greatergreater,
1374 Ks: tok::greatergreatergreater);
1375}
1376
1377/// Parse a C++ template template argument.
1378ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1379 if (!Tok.is(K: tok::identifier) && !Tok.is(K: tok::coloncolon) &&
1380 !Tok.is(K: tok::annot_cxxscope))
1381 return ParsedTemplateArgument();
1382
1383 // C++0x [temp.arg.template]p1:
1384 // A template-argument for a template template-parameter shall be the name
1385 // of a class template or an alias template, expressed as id-expression.
1386 //
1387 // We parse an id-expression that refers to a class template or alias
1388 // template. The grammar we parse is:
1389 //
1390 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1391 //
1392 // followed by a token that terminates a template argument, such as ',',
1393 // '>', or (in some cases) '>>'.
1394 CXXScopeSpec SS; // nested-name-specifier, if present
1395 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1396 /*ObjectHasErrors=*/false,
1397 /*EnteringContext=*/false);
1398
1399 ParsedTemplateArgument Result;
1400 SourceLocation EllipsisLoc;
1401 if (SS.isSet() && Tok.is(K: tok::kw_template)) {
1402 // Parse the optional 'template' keyword following the
1403 // nested-name-specifier.
1404 SourceLocation TemplateKWLoc = ConsumeToken();
1405
1406 if (Tok.is(K: tok::identifier)) {
1407 // We appear to have a dependent template name.
1408 UnqualifiedId Name;
1409 Name.setIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation());
1410 ConsumeToken(); // the identifier
1411
1412 TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc);
1413
1414 // If the next token signals the end of a template argument, then we have
1415 // a (possibly-dependent) template name that could be a template template
1416 // argument.
1417 TemplateTy Template;
1418 if (isEndOfTemplateArgument(Tok) &&
1419 Actions.ActOnTemplateName(S: getCurScope(), SS, TemplateKWLoc, Name,
1420 /*ObjectType=*/nullptr,
1421 /*EnteringContext=*/false, Template))
1422 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1423 }
1424 } else if (Tok.is(K: tok::identifier)) {
1425 // We may have a (non-dependent) template name.
1426 TemplateTy Template;
1427 UnqualifiedId Name;
1428 Name.setIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation());
1429 ConsumeToken(); // the identifier
1430
1431 TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc);
1432
1433 if (isEndOfTemplateArgument(Tok)) {
1434 bool MemberOfUnknownSpecialization;
1435 TemplateNameKind TNK = Actions.isTemplateName(
1436 S: getCurScope(), SS,
1437 /*hasTemplateKeyword=*/false, Name,
1438 /*ObjectType=*/nullptr,
1439 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1440 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1441 // We have an id-expression that refers to a class template or
1442 // (C++0x) alias template.
1443 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1444 }
1445 }
1446 }
1447
1448 // If this is a pack expansion, build it as such.
1449 if (EllipsisLoc.isValid() && !Result.isInvalid())
1450 Result = Actions.ActOnPackExpansion(Arg: Result, EllipsisLoc);
1451
1452 return Result;
1453}
1454
1455/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1456///
1457/// template-argument: [C++ 14.2]
1458/// constant-expression
1459/// type-id
1460/// id-expression
1461/// braced-init-list [C++26, DR]
1462///
1463ParsedTemplateArgument Parser::ParseTemplateArgument() {
1464 // C++ [temp.arg]p2:
1465 // In a template-argument, an ambiguity between a type-id and an
1466 // expression is resolved to a type-id, regardless of the form of
1467 // the corresponding template-parameter.
1468 //
1469 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1470 // up and annotate an identifier as an id-expression during disambiguation,
1471 // so enter the appropriate context for a constant expression template
1472 // argument before trying to disambiguate.
1473
1474 EnterExpressionEvaluationContext EnterConstantEvaluated(
1475 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1476 /*LambdaContextDecl=*/nullptr,
1477 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1478 if (isCXXTypeId(Context: TypeIdAsTemplateArgument)) {
1479 TypeResult TypeArg = ParseTypeName(
1480 /*Range=*/nullptr, Context: DeclaratorContext::TemplateArg);
1481 return Actions.ActOnTemplateTypeArgument(ParsedType: TypeArg);
1482 }
1483
1484 // Try to parse a template template argument.
1485 {
1486 TentativeParsingAction TPA(*this);
1487
1488 ParsedTemplateArgument TemplateTemplateArgument
1489 = ParseTemplateTemplateArgument();
1490 if (!TemplateTemplateArgument.isInvalid()) {
1491 TPA.Commit();
1492 return TemplateTemplateArgument;
1493 }
1494
1495 // Revert this tentative parse to parse a non-type template argument.
1496 TPA.Revert();
1497 }
1498
1499 // Parse a non-type template argument.
1500 ExprResult ExprArg;
1501 SourceLocation Loc = Tok.getLocation();
1502 if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace))
1503 ExprArg = ParseBraceInitializer();
1504 else
1505 ExprArg = ParseConstantExpressionInExprEvalContext(isTypeCast: MaybeTypeCast);
1506 if (ExprArg.isInvalid() || !ExprArg.get()) {
1507 return ParsedTemplateArgument();
1508 }
1509
1510 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1511 ExprArg.get(), Loc);
1512}
1513
1514/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1515/// (C++ [temp.names]). Returns true if there was an error.
1516///
1517/// template-argument-list: [C++ 14.2]
1518/// template-argument
1519/// template-argument-list ',' template-argument
1520///
1521/// \param Template is only used for code completion, and may be null.
1522bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
1523 TemplateTy Template,
1524 SourceLocation OpenLoc) {
1525
1526 ColonProtectionRAIIObject ColonProtection(*this, false);
1527
1528 auto RunSignatureHelp = [&] {
1529 if (!Template)
1530 return QualType();
1531 CalledSignatureHelp = true;
1532 return Actions.ProduceTemplateArgumentSignatureHelp(Template, TemplateArgs,
1533 LAngleLoc: OpenLoc);
1534 };
1535
1536 do {
1537 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
1538 ParsedTemplateArgument Arg = ParseTemplateArgument();
1539 SourceLocation EllipsisLoc;
1540 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc))
1541 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1542
1543 if (Arg.isInvalid()) {
1544 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1545 RunSignatureHelp();
1546 return true;
1547 }
1548
1549 // Save this template argument.
1550 TemplateArgs.push_back(Elt: Arg);
1551
1552 // If the next token is a comma, consume it and keep reading
1553 // arguments.
1554 } while (TryConsumeToken(Expected: tok::comma));
1555
1556 return false;
1557}
1558
1559/// Parse a C++ explicit template instantiation
1560/// (C++ [temp.explicit]).
1561///
1562/// explicit-instantiation:
1563/// 'extern' [opt] 'template' declaration
1564///
1565/// Note that the 'extern' is a GNU extension and C++11 feature.
1566Parser::DeclGroupPtrTy Parser::ParseExplicitInstantiation(
1567 DeclaratorContext Context, SourceLocation ExternLoc,
1568 SourceLocation TemplateLoc, SourceLocation &DeclEnd,
1569 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
1570 // This isn't really required here.
1571 ParsingDeclRAIIObject
1572 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1573 ParsedTemplateInfo TemplateInfo(ExternLoc, TemplateLoc);
1574 return ParseDeclarationAfterTemplate(
1575 Context, TemplateInfo, DiagsFromTParams&: ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1576}
1577
1578SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1579 if (TemplateParams)
1580 return getTemplateParamsRange(Params: TemplateParams->data(),
1581 NumParams: TemplateParams->size());
1582
1583 SourceRange R(TemplateLoc);
1584 if (ExternLoc.isValid())
1585 R.setBegin(ExternLoc);
1586 return R;
1587}
1588
1589void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1590 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1591}
1592
1593/// Late parse a C++ function template in Microsoft mode.
1594void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1595 if (!LPT.D)
1596 return;
1597
1598 // Destroy TemplateIdAnnotations when we're done, if possible.
1599 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
1600
1601 // Get the FunctionDecl.
1602 FunctionDecl *FunD = LPT.D->getAsFunction();
1603 // Track template parameter depth.
1604 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1605
1606 // To restore the context after late parsing.
1607 Sema::ContextRAII GlobalSavedContext(
1608 Actions, Actions.Context.getTranslationUnitDecl());
1609
1610 MultiParseScope Scopes(*this);
1611
1612 // Get the list of DeclContexts to reenter.
1613 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1614 for (DeclContext *DC = FunD; DC && !DC->isTranslationUnit();
1615 DC = DC->getLexicalParent())
1616 DeclContextsToReenter.push_back(Elt: DC);
1617
1618 // Reenter scopes from outermost to innermost.
1619 for (DeclContext *DC : reverse(C&: DeclContextsToReenter)) {
1620 CurTemplateDepthTracker.addDepth(
1621 D: ReenterTemplateScopes(S&: Scopes, D: cast<Decl>(Val: DC)));
1622 Scopes.Enter(ScopeFlags: Scope::DeclScope);
1623 // We'll reenter the function context itself below.
1624 if (DC != FunD)
1625 Actions.PushDeclContext(S: Actions.getCurScope(), DC);
1626 }
1627
1628 // Parsing should occur with empty FP pragma stack and FP options used in the
1629 // point of the template definition.
1630 Sema::FpPragmaStackSaveRAII SavedStack(Actions);
1631 Actions.resetFPOptions(FPO: LPT.FPO);
1632
1633 assert(!LPT.Toks.empty() && "Empty body!");
1634
1635 // Append the current token at the end of the new token stream so that it
1636 // doesn't get lost.
1637 LPT.Toks.push_back(Elt: Tok);
1638 PP.EnterTokenStream(Toks: LPT.Toks, DisableMacroExpansion: true, /*IsReinject*/true);
1639
1640 // Consume the previously pushed token.
1641 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1642 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1643 "Inline method not starting with '{', ':' or 'try'");
1644
1645 // Parse the method body. Function body parsing code is similar enough
1646 // to be re-used for method bodies as well.
1647 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1648 Scope::CompoundStmtScope);
1649
1650 // Recreate the containing function DeclContext.
1651 Sema::ContextRAII FunctionSavedContext(Actions, FunD->getLexicalParent());
1652
1653 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1654
1655 if (Tok.is(K: tok::kw_try)) {
1656 ParseFunctionTryBlock(Decl: LPT.D, BodyScope&: FnScope);
1657 } else {
1658 if (Tok.is(K: tok::colon))
1659 ParseConstructorInitializer(ConstructorDecl: LPT.D);
1660 else
1661 Actions.ActOnDefaultCtorInitializers(CDtorDecl: LPT.D);
1662
1663 if (Tok.is(K: tok::l_brace)) {
1664 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1665 cast<FunctionTemplateDecl>(LPT.D)
1666 ->getTemplateParameters()
1667 ->getDepth() == TemplateParameterDepth - 1) &&
1668 "TemplateParameterDepth should be greater than the depth of "
1669 "current template being instantiated!");
1670 ParseFunctionStatementBody(Decl: LPT.D, BodyScope&: FnScope);
1671 Actions.UnmarkAsLateParsedTemplate(FD: FunD);
1672 } else
1673 Actions.ActOnFinishFunctionBody(Decl: LPT.D, Body: nullptr);
1674 }
1675}
1676
1677/// Lex a delayed template function for late parsing.
1678void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1679 tok::TokenKind kind = Tok.getKind();
1680 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1681 // Consume everything up to (and including) the matching right brace.
1682 ConsumeAndStoreUntil(T1: tok::r_brace, Toks, /*StopAtSemi=*/false);
1683 }
1684
1685 // If we're in a function-try-block, we need to store all the catch blocks.
1686 if (kind == tok::kw_try) {
1687 while (Tok.is(K: tok::kw_catch)) {
1688 ConsumeAndStoreUntil(T1: tok::l_brace, Toks, /*StopAtSemi=*/false);
1689 ConsumeAndStoreUntil(T1: tok::r_brace, Toks, /*StopAtSemi=*/false);
1690 }
1691 }
1692}
1693
1694/// We've parsed something that could plausibly be intended to be a template
1695/// name (\p LHS) followed by a '<' token, and the following code can't possibly
1696/// be an expression. Determine if this is likely to be a template-id and if so,
1697/// diagnose it.
1698bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1699 TentativeParsingAction TPA(*this);
1700 // FIXME: We could look at the token sequence in a lot more detail here.
1701 if (SkipUntil(T1: tok::greater, T2: tok::greatergreater, T3: tok::greatergreatergreater,
1702 Flags: StopAtSemi | StopBeforeMatch)) {
1703 TPA.Commit();
1704
1705 SourceLocation Greater;
1706 ParseGreaterThanInTemplateList(LAngleLoc: Less, RAngleLoc&: Greater, ConsumeLastToken: true, ObjCGenericList: false);
1707 Actions.diagnoseExprIntendedAsTemplateName(S: getCurScope(), TemplateName: LHS,
1708 Less, Greater);
1709 return true;
1710 }
1711
1712 // There's no matching '>' token, this probably isn't supposed to be
1713 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1714 TPA.Revert();
1715 return false;
1716}
1717
1718void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1719 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1720
1721 bool DependentTemplateName = false;
1722 if (!Actions.mightBeIntendedToBeTemplateName(E: PotentialTemplateName,
1723 Dependent&: DependentTemplateName))
1724 return;
1725
1726 // OK, this might be a name that the user intended to be parsed as a
1727 // template-name, followed by a '<' token. Check for some easy cases.
1728
1729 // If we have potential_template<>, then it's supposed to be a template-name.
1730 if (NextToken().is(K: tok::greater) ||
1731 (getLangOpts().CPlusPlus11 &&
1732 NextToken().isOneOf(K1: tok::greatergreater, K2: tok::greatergreatergreater))) {
1733 SourceLocation Less = ConsumeToken();
1734 SourceLocation Greater;
1735 ParseGreaterThanInTemplateList(LAngleLoc: Less, RAngleLoc&: Greater, ConsumeLastToken: true, ObjCGenericList: false);
1736 Actions.diagnoseExprIntendedAsTemplateName(
1737 S: getCurScope(), TemplateName: PotentialTemplateName, Less, Greater);
1738 // FIXME: Perform error recovery.
1739 PotentialTemplateName = ExprError();
1740 return;
1741 }
1742
1743 // If we have 'potential_template<type-id', assume it's supposed to be a
1744 // template-name if there's a matching '>' later on.
1745 {
1746 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1747 TentativeParsingAction TPA(*this);
1748 SourceLocation Less = ConsumeToken();
1749 if (isTypeIdUnambiguously() &&
1750 diagnoseUnknownTemplateId(LHS: PotentialTemplateName, Less)) {
1751 TPA.Commit();
1752 // FIXME: Perform error recovery.
1753 PotentialTemplateName = ExprError();
1754 return;
1755 }
1756 TPA.Revert();
1757 }
1758
1759 // Otherwise, remember that we saw this in case we see a potentially-matching
1760 // '>' token later on.
1761 AngleBracketTracker::Priority Priority =
1762 (DependentTemplateName ? AngleBracketTracker::DependentName
1763 : AngleBracketTracker::PotentialTypo) |
1764 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1765 : AngleBracketTracker::NoSpaceBeforeLess);
1766 AngleBrackets.add(P&: *this, TemplateName: PotentialTemplateName.get(), LessLoc: Tok.getLocation(),
1767 Prio: Priority);
1768}
1769
1770bool Parser::checkPotentialAngleBracketDelimiter(
1771 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1772 // If a comma in an expression context is followed by a type that can be a
1773 // template argument and cannot be an expression, then this is ill-formed,
1774 // but might be intended to be part of a template-id.
1775 if (OpToken.is(K: tok::comma) && isTypeIdUnambiguously() &&
1776 diagnoseUnknownTemplateId(LHS: LAngle.TemplateName, Less: LAngle.LessLoc)) {
1777 AngleBrackets.clear(P&: *this);
1778 return true;
1779 }
1780
1781 // If a context that looks like a template-id is followed by '()', then
1782 // this is ill-formed, but might be intended to be a template-id
1783 // followed by '()'.
1784 if (OpToken.is(K: tok::greater) && Tok.is(K: tok::l_paren) &&
1785 NextToken().is(K: tok::r_paren)) {
1786 Actions.diagnoseExprIntendedAsTemplateName(
1787 S: getCurScope(), TemplateName: LAngle.TemplateName, Less: LAngle.LessLoc,
1788 Greater: OpToken.getLocation());
1789 AngleBrackets.clear(P&: *this);
1790 return true;
1791 }
1792
1793 // After a '>' (etc), we're no longer potentially in a construct that's
1794 // intended to be treated as a template-id.
1795 if (OpToken.is(K: tok::greater) ||
1796 (getLangOpts().CPlusPlus11 &&
1797 OpToken.isOneOf(K1: tok::greatergreater, K2: tok::greatergreatergreater)))
1798 AngleBrackets.clear(P&: *this);
1799 return false;
1800}
1801

source code of clang/lib/Parse/ParseTemplate.cpp