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