blob: 9bb5b6eac37e2190670c5621d012b51071e5b09e [file] [log] [blame]
Faisal Vali6a79ca12013-06-08 19:39:00 +00001//===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Faisal Vali6a79ca12013-06-08 19:39:00 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements parsing of C++ templates.
10//
11//===----------------------------------------------------------------------===//
12
Richard Smithb0b68012015-05-11 23:09:06 +000013#include "clang/AST/ASTContext.h"
Faisal Vali6a79ca12013-06-08 19:39:00 +000014#include "clang/AST/DeclTemplate.h"
15#include "clang/Parse/ParseDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "clang/Parse/Parser.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000017#include "clang/Parse/RAIIObjectsForParser.h"
Faisal Vali6a79ca12013-06-08 19:39:00 +000018#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/ParsedTemplate.h"
20#include "clang/Sema/Scope.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000021#include "llvm/Support/TimeProfiler.h"
Faisal Vali6a79ca12013-06-08 19:39:00 +000022using namespace clang;
23
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000024/// Parse a template declaration, explicit instantiation, or
Faisal Vali6a79ca12013-06-08 19:39:00 +000025/// explicit specialization.
Erich Keanec480f302018-07-12 21:09:05 +000026Decl *Parser::ParseDeclarationStartingWithTemplate(
27 DeclaratorContext Context, SourceLocation &DeclEnd,
28 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
Faisal Vali6a79ca12013-06-08 19:39:00 +000029 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +000030
Faisal Vali6a79ca12013-06-08 19:39:00 +000031 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
Erich Keanec480f302018-07-12 21:09:05 +000032 return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
33 DeclEnd, AccessAttrs, AS);
Faisal Vali6a79ca12013-06-08 19:39:00 +000034 }
Erich Keanec480f302018-07-12 21:09:05 +000035 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
36 AS);
Faisal Vali6a79ca12013-06-08 19:39:00 +000037}
38
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000039/// Parse a template declaration or an explicit specialization.
Faisal Vali6a79ca12013-06-08 19:39:00 +000040///
41/// Template declarations include one or more template parameter lists
42/// and either the function or class template declaration. Explicit
43/// specializations contain one or more 'template < >' prefixes
44/// followed by a (possibly templated) declaration. Since the
45/// syntactic form of both features is nearly identical, we parse all
46/// of the template headers together and let semantic analysis sort
47/// the declarations from the explicit specializations.
48///
49/// template-declaration: [C++ temp]
50/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
51///
Saar Razd7aae332019-07-10 21:25:49 +000052/// template-declaration: [C++2a]
53/// template-head declaration
54/// template-head concept-definition
55///
56/// TODO: requires-clause
57/// template-head: [C++2a]
58/// 'template' '<' template-parameter-list '>'
59/// requires-clause[opt]
60///
Faisal Vali6a79ca12013-06-08 19:39:00 +000061/// explicit-specialization: [ C++ temp.expl.spec]
62/// 'template' '<' '>' declaration
Erich Keanec480f302018-07-12 21:09:05 +000063Decl *Parser::ParseTemplateDeclarationOrSpecialization(
64 DeclaratorContext Context, SourceLocation &DeclEnd,
65 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +000066 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +000067 "Token does not start a template declaration.");
68
69 // Enter template-parameter scope.
70 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
71
72 // Tell the action that names should be checked in the context of
73 // the declaration to come.
74 ParsingDeclRAIIObject
75 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
76
77 // Parse multiple levels of template headers within this template
78 // parameter scope, e.g.,
79 //
80 // template<typename T>
81 // template<typename U>
82 // class A<T>::B { ... };
83 //
84 // We parse multiple levels non-recursively so that we can build a
85 // single data structure containing all of the template parameter
86 // lists to easily differentiate between the case above and:
87 //
88 // template<typename T>
89 // class A {
90 // template<typename U> class B;
91 // };
92 //
93 // In the first case, the action for declaring A<T>::B receives
94 // both template parameter lists. In the second case, the action for
95 // defining A<T>::B receives just the inner template parameter list
96 // (and retrieves the outer template parameter list from its
97 // context).
98 bool isSpecialization = true;
99 bool LastParamListWasEmpty = false;
100 TemplateParameterLists ParamLists;
101 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
102
103 do {
104 // Consume the 'export', if any.
105 SourceLocation ExportLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000106 TryConsumeToken(tok::kw_export, ExportLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000107
108 // Consume the 'template', which should be here.
109 SourceLocation TemplateLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000110 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000111 Diag(Tok.getLocation(), diag::err_expected_template);
Craig Topper161e4db2014-05-21 06:02:52 +0000112 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000113 }
114
115 // Parse the '<' template-parameter-list '>'
116 SourceLocation LAngleLoc, RAngleLoc;
Faisal Valif241b0d2017-08-25 18:24:20 +0000117 SmallVector<NamedDecl*, 4> TemplateParams;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000118 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
119 TemplateParams, LAngleLoc, RAngleLoc)) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000120 // Skip until the semi-colon or a '}'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000121 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000122 TryConsumeToken(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000123 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000124 }
125
Hubert Tongf608c052016-04-29 18:05:37 +0000126 ExprResult OptionalRequiresClauseConstraintER;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000127 if (!TemplateParams.empty()) {
128 isSpecialization = false;
129 ++CurTemplateDepthTracker;
Hubert Tongec3cb572015-06-25 00:23:39 +0000130
131 if (TryConsumeToken(tok::kw_requires)) {
Hubert Tongf608c052016-04-29 18:05:37 +0000132 OptionalRequiresClauseConstraintER =
Hubert Tongec3cb572015-06-25 00:23:39 +0000133 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
Hubert Tongf608c052016-04-29 18:05:37 +0000134 if (!OptionalRequiresClauseConstraintER.isUsable()) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000135 // Skip until the semi-colon or a '}'.
136 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
137 TryConsumeToken(tok::semi);
138 return nullptr;
139 }
140 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000141 } else {
142 LastParamListWasEmpty = true;
143 }
Hubert Tongf608c052016-04-29 18:05:37 +0000144
145 ParamLists.push_back(Actions.ActOnTemplateParameterList(
146 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
147 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000148 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000149
Akira Hatanaka10aced82016-04-29 02:24:14 +0000150 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
151 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
152
Faisal Valia534f072018-04-26 00:42:40 +0000153 // Parse the actual template declaration.
Saar Razd7aae332019-07-10 21:25:49 +0000154 if (Tok.is(tok::kw_concept))
155 return ParseConceptDefinition(
156 ParsedTemplateInfo(&ParamLists, isSpecialization,
157 LastParamListWasEmpty),
158 DeclEnd);
159
Erich Keanec480f302018-07-12 21:09:05 +0000160 return ParseSingleDeclarationAfterTemplate(
161 Context,
162 ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
163 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000164}
165
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000166/// Parse a single declaration that declares a template,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000167/// template specialization, or explicit instantiation of a template.
168///
169/// \param DeclEnd will receive the source location of the last token
170/// within this declaration.
171///
172/// \param AS the access specifier associated with this
173/// declaration. Will be AS_none for namespace-scope declarations.
174///
175/// \returns the new declaration.
Erich Keanec480f302018-07-12 21:09:05 +0000176Decl *Parser::ParseSingleDeclarationAfterTemplate(
177 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
178 ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
179 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000180 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
181 "Template information required");
182
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000183 if (Tok.is(tok::kw_static_assert)) {
184 // A static_assert declaration may not be templated.
185 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
186 << TemplateInfo.getSourceRange();
187 // Parse the static_assert declaration to improve error recovery.
188 return ParseStaticAssertDeclaration(DeclEnd);
189 }
190
Faisal Vali421b2d12017-12-29 05:41:00 +0000191 if (Context == DeclaratorContext::MemberContext) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000192 // We are parsing a member template.
193 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
194 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000195 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000196 }
197
198 ParsedAttributesWithRange prefixAttrs(AttrFactory);
199 MaybeParseCXX11Attributes(prefixAttrs);
200
Richard Smith6f1daa42016-12-16 00:58:48 +0000201 if (Tok.is(tok::kw_using)) {
Erik Verbruggen51ee12a2017-09-08 09:31:13 +0000202 auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
203 prefixAttrs);
204 if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
205 return nullptr;
206 return usingDeclPtr.get().getSingleDecl();
Richard Smith6f1daa42016-12-16 00:58:48 +0000207 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000208
209 // Parse the declaration specifiers, stealing any diagnostics from
210 // the template parameters.
211 ParsingDeclSpec DS(*this, &DiagsFromTParams);
212
Faisal Valia534f072018-04-26 00:42:40 +0000213 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000214 getDeclSpecContextFromDeclaratorContext(Context));
215
216 if (Tok.is(tok::semi)) {
217 ProhibitAttributes(prefixAttrs);
218 DeclEnd = ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +0000219 RecordDecl *AnonRecord = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000220 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
221 getCurScope(), AS, DS,
222 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
223 : MultiTemplateParamsArg(),
Nico Weber7b837f52016-01-28 19:25:00 +0000224 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
225 AnonRecord);
226 assert(!AnonRecord &&
227 "Anonymous unions/structs should not be valid with template");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000228 DS.complete(Decl);
229 return Decl;
230 }
231
232 // Move the attributes from the prefix into the DS.
233 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
234 ProhibitAttributes(prefixAttrs);
235 else
236 DS.takeAttributesFrom(prefixAttrs);
237
238 // Parse the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +0000239 ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000240 ParseDeclarator(DeclaratorInfo);
241 // Error parsing the declarator?
242 if (!DeclaratorInfo.hasName()) {
243 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000244 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000245 if (Tok.is(tok::semi))
246 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000247 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000248 }
249
Anton Afanasyevd880de22019-03-30 08:42:48 +0000250 llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
251 return DeclaratorInfo.getIdentifier() != nullptr
252 ? DeclaratorInfo.getIdentifier()->getName()
253 : "<unknown>";
254 });
255
Faisal Vali6a79ca12013-06-08 19:39:00 +0000256 LateParsedAttrList LateParsedAttrs(true);
257 if (DeclaratorInfo.isFunctionDeclarator())
258 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
259
260 if (DeclaratorInfo.isFunctionDeclarator() &&
261 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000262
263 // Function definitions are only allowed at file scope and in C++ classes.
264 // The C++ inline method definition case is handled elsewhere, so we only
265 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +0000266 if (Context != DeclaratorContext::FileContext) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000267 Diag(Tok, diag::err_function_definition_not_allowed);
268 SkipMalformedDecl();
269 return nullptr;
270 }
271
Faisal Vali6a79ca12013-06-08 19:39:00 +0000272 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
273 // Recover by ignoring the 'typedef'. This was probably supposed to be
274 // the 'typename' keyword, which we should have already suggested adding
275 // if it's appropriate.
276 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
277 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
278 DS.ClearStorageClassSpecs();
279 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000280
281 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000282 if (DeclaratorInfo.getName().getKind() !=
283 UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo725de3e2013-06-21 00:08:46 +0000284 // If the declarator-id is not a template-id, issue a diagnostic and
285 // recover by ignoring the 'template' keyword.
286 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000287 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
288 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000289 } else {
290 SourceLocation LAngleLoc
291 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000292 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000293 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000294 << SourceRange(TemplateInfo.TemplateLoc)
295 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000296
Larisse Voufo39a1e502013-08-06 01:03:05 +0000297 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000298 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000299 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +0000300 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +0000301 LAngleLoc, nullptr));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000302
Larisse Voufo39a1e502013-08-06 01:03:05 +0000303 return ParseFunctionDefinition(
304 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
305 /*isSpecialization=*/true,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000306 /*lastParameterListWasEmpty=*/true),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000307 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000308 }
309 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000310 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000311 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000312 }
313
314 // Parse this declaration.
315 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
316 TemplateInfo);
317
318 if (Tok.is(tok::comma)) {
319 Diag(Tok, diag::err_multiple_template_declarators)
320 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000321 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000322 return ThisDecl;
323 }
324
325 // Eat the semi colon after the declaration.
326 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
327 if (LateParsedAttrs.size() > 0)
328 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
329 DeclaratorInfo.complete(ThisDecl);
330 return ThisDecl;
331}
332
Saar Razd7aae332019-07-10 21:25:49 +0000333/// \brief Parse a single declaration that declares a concept.
334///
335/// \param DeclEnd will receive the source location of the last token
336/// within this declaration.
337///
338/// \returns the new declaration.
339Decl *
340Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
341 SourceLocation &DeclEnd) {
342 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
343 "Template information required");
344 assert(Tok.is(tok::kw_concept) &&
345 "ParseConceptDefinition must be called when at a 'concept' keyword");
346
347 ConsumeToken(); // Consume 'concept'
348
349 SourceLocation BoolKWLoc;
350 if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
351 Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) <<
352 FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
353
354 DiagnoseAndSkipCXX11Attributes();
355
356 CXXScopeSpec SS;
357 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
358 /*EnteringContext=*/false, /*MayBePseudoDestructor=*/nullptr,
359 /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
360 SS.isInvalid()) {
361 SkipUntil(tok::semi);
362 return nullptr;
363 }
364
365 if (SS.isNotEmpty())
366 Diag(SS.getBeginLoc(),
367 diag::err_concept_definition_not_identifier);
368
369 UnqualifiedId Result;
370 if (ParseUnqualifiedId(SS, /*EnteringContext=*/false,
371 /*AllowDestructorName=*/false,
372 /*AllowConstructorName=*/false,
373 /*AllowDeductionGuide=*/false,
374 /*ObjectType=*/ParsedType(), /*TemplateKWLoc=*/nullptr,
375 Result)) {
376 SkipUntil(tok::semi);
377 return nullptr;
378 }
379
380 if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
381 Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
382 SkipUntil(tok::semi);
383 return nullptr;
384 }
385
386 IdentifierInfo *Id = Result.Identifier;
387 SourceLocation IdLoc = Result.getBeginLoc();
388
389 DiagnoseAndSkipCXX11Attributes();
390
391 if (!TryConsumeToken(tok::equal)) {
392 Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
393 SkipUntil(tok::semi);
394 return nullptr;
395 }
396
397 ExprResult ConstraintExprResult =
398 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
399 if (ConstraintExprResult.isInvalid()) {
400 SkipUntil(tok::semi);
401 return nullptr;
402 }
403
404 DeclEnd = Tok.getLocation();
405 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
406 Expr *ConstraintExpr = ConstraintExprResult.get();
407 return Actions.ActOnConceptDefinition(getCurScope(),
408 *TemplateInfo.TemplateParams,
409 Id, IdLoc, ConstraintExpr);
410}
411
Faisal Vali6a79ca12013-06-08 19:39:00 +0000412/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
413/// angle brackets. Depth is the depth of this template-parameter-list, which
414/// is the number of template headers directly enclosing this template header.
415/// TemplateParams is the current list of template parameters we're building.
416/// The template parameter we parse will be added to this list. LAngleLoc and
417/// RAngleLoc will receive the positions of the '<' and '>', respectively,
418/// that enclose this template parameter list.
419///
420/// \returns true if an error occurred, false otherwise.
Faisal Valif241b0d2017-08-25 18:24:20 +0000421bool Parser::ParseTemplateParameters(
422 unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
423 SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000424 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000425 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000426 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
427 return true;
428 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000429
430 // Try to parse the template parameter list.
431 bool Failed = false;
432 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
433 Failed = ParseTemplateParameterList(Depth, TemplateParams);
434
435 if (Tok.is(tok::greatergreater)) {
436 // No diagnostic required here: a template-parameter-list can only be
437 // followed by a declaration or, for a template template parameter, the
438 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
439 // This matters for elegant diagnosis of:
440 // template<template<typename>> struct S;
441 Tok.setKind(tok::greater);
442 RAngleLoc = Tok.getLocation();
443 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000444 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
445 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000446 return true;
447 }
448 return false;
449}
450
451/// ParseTemplateParameterList - Parse a template parameter list. If
452/// the parsing fails badly (i.e., closing bracket was left out), this
453/// will try to put the token stream in a reasonable position (closing
454/// a statement, etc.) and return false.
455///
456/// template-parameter-list: [C++ temp]
457/// template-parameter
458/// template-parameter-list ',' template-parameter
459bool
Faisal Vali421b2d12017-12-29 05:41:00 +0000460Parser::ParseTemplateParameterList(const unsigned Depth,
Faisal Valif241b0d2017-08-25 18:24:20 +0000461 SmallVectorImpl<NamedDecl*> &TemplateParams) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000462 while (1) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000463
Faisal Valibe294032017-12-23 18:56:34 +0000464 if (NamedDecl *TmpParam
Faisal Vali6a79ca12013-06-08 19:39:00 +0000465 = ParseTemplateParameter(Depth, TemplateParams.size())) {
Faisal Valid9548c32017-12-23 19:27:07 +0000466 TemplateParams.push_back(TmpParam);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000467 } else {
468 // If we failed to parse a template parameter, skip until we find
469 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000470 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
471 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000472 }
473
474 // Did we find a comma or the end of the template parameter list?
475 if (Tok.is(tok::comma)) {
476 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000477 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000478 // Don't consume this... that's done by template parser.
479 break;
480 } else {
481 // Somebody probably forgot to close the template. Skip ahead and
482 // try to get out of the expression. This error is currently
483 // subsumed by whatever goes on in ParseTemplateParameter.
484 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000485 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
486 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000487 return false;
488 }
489 }
490 return true;
491}
492
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493/// Determine whether the parser is at the start of a template
Faisal Vali6a79ca12013-06-08 19:39:00 +0000494/// type parameter.
495bool Parser::isStartOfTemplateTypeParameter() {
496 if (Tok.is(tok::kw_class)) {
497 // "class" may be the start of an elaborated-type-specifier or a
498 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
499 switch (NextToken().getKind()) {
500 case tok::equal:
501 case tok::comma:
502 case tok::greater:
503 case tok::greatergreater:
504 case tok::ellipsis:
505 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000506
Faisal Vali6a79ca12013-06-08 19:39:00 +0000507 case tok::identifier:
Fangrui Song6907ce22018-07-30 19:24:48 +0000508 // This may be either a type-parameter or an elaborated-type-specifier.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000509 // We have to look further.
510 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000511
Faisal Vali6a79ca12013-06-08 19:39:00 +0000512 default:
513 return false;
514 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000515
Faisal Vali6a79ca12013-06-08 19:39:00 +0000516 switch (GetLookAheadToken(2).getKind()) {
517 case tok::equal:
518 case tok::comma:
519 case tok::greater:
520 case tok::greatergreater:
521 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000522
Faisal Vali6a79ca12013-06-08 19:39:00 +0000523 default:
524 return false;
525 }
526 }
527
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000528 // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
529 // ill-formed otherwise.
530 if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000531 return false;
532
533 // C++ [temp.param]p2:
534 // There is no semantic difference between class and typename in a
535 // template-parameter. typename followed by an unqualified-id
536 // names a template type parameter. typename followed by a
537 // qualified-id denotes the type in a non-type
538 // parameter-declaration.
539 Token Next = NextToken();
540
541 // If we have an identifier, skip over it.
542 if (Next.getKind() == tok::identifier)
543 Next = GetLookAheadToken(2);
544
545 switch (Next.getKind()) {
546 case tok::equal:
547 case tok::comma:
548 case tok::greater:
549 case tok::greatergreater:
550 case tok::ellipsis:
551 return true;
552
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000553 case tok::kw_typename:
554 case tok::kw_typedef:
555 case tok::kw_class:
556 // These indicate that a comma was missed after a type parameter, not that
557 // we have found a non-type parameter.
558 return true;
559
Faisal Vali6a79ca12013-06-08 19:39:00 +0000560 default:
561 return false;
562 }
563}
564
565/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
566///
567/// template-parameter: [C++ temp.param]
568/// type-parameter
569/// parameter-declaration
570///
571/// type-parameter: (see below)
572/// 'class' ...[opt] identifier[opt]
573/// 'class' identifier[opt] '=' type-id
574/// 'typename' ...[opt] identifier[opt]
575/// 'typename' identifier[opt] '=' type-id
Fangrui Song6907ce22018-07-30 19:24:48 +0000576/// 'template' '<' template-parameter-list '>'
Faisal Vali6a79ca12013-06-08 19:39:00 +0000577/// 'class' ...[opt] identifier[opt]
578/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
579/// = id-expression
Faisal Valibe294032017-12-23 18:56:34 +0000580NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000581 if (isStartOfTemplateTypeParameter()) {
582 // Is there just a typo in the input code? ('typedef' instead of 'typename')
583 if (Tok.is(tok::kw_typedef)) {
584 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000585
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000586 Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
587 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
588 Tok.getLocation(), Tok.getEndLoc()),
589 "typename");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000590
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000591 Tok.setKind(tok::kw_typename);
592 }
Jan Korous3a98e512018-02-08 14:37:58 +0000593
594 return ParseTypeParameter(Depth, Position);
595 }
596
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000597 if (Tok.is(tok::kw_template))
598 return ParseTemplateTemplateParameter(Depth, Position);
599
Faisal Vali6a79ca12013-06-08 19:39:00 +0000600 // If it's none of the above, then it must be a parameter declaration.
601 // NOTE: This will pick up errors in the closure of the template parameter
602 // list (e.g., template < ; Check here to implement >> style closures.
603 return ParseNonTypeTemplateParameter(Depth, Position);
604}
605
606/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
607/// Other kinds of template parameters are parsed in
608/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
609///
610/// type-parameter: [C++ temp.param]
611/// 'class' ...[opt][C++0x] identifier[opt]
612/// 'class' identifier[opt] '=' type-id
613/// 'typename' ...[opt][C++0x] identifier[opt]
614/// 'typename' identifier[opt] '=' type-id
Faisal Valibe294032017-12-23 18:56:34 +0000615NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000616 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000617 "A type-parameter starts with 'class' or 'typename'");
618
619 // Consume the 'class' or 'typename' keyword.
620 bool TypenameKeyword = Tok.is(tok::kw_typename);
621 SourceLocation KeyLoc = ConsumeToken();
622
623 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000624 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000625 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000626 Diag(EllipsisLoc,
627 getLangOpts().CPlusPlus11
628 ? diag::warn_cxx98_compat_variadic_templates
629 : diag::ext_variadic_templates);
630 }
631
632 // Grab the template parameter name (if given)
633 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000634 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000635 if (Tok.is(tok::identifier)) {
636 ParamName = Tok.getIdentifierInfo();
637 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000638 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
639 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000640 // Unnamed template parameter. Don't have to do anything here, just
641 // don't consume this token.
642 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000643 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000644 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000645 }
646
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000647 // Recover from misplaced ellipsis.
648 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
649 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
650 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
651
Faisal Vali6a79ca12013-06-08 19:39:00 +0000652 // Grab a default argument (if available).
653 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
654 // we introduce the type parameter into the local scope.
655 SourceLocation EqualLoc;
656 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000657 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000658 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali421b2d12017-12-29 05:41:00 +0000659 DeclaratorContext::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000660
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000661 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
662 KeyLoc, ParamName, NameLoc, Depth, Position,
663 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000664}
665
666/// ParseTemplateTemplateParameter - Handle the parsing of template
667/// template parameters.
668///
669/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000670/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000671/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000672/// 'template' '<' template-parameter-list '>' type-parameter-key
673/// identifier[opt] = id-expression
674/// type-parameter-key:
675/// 'class'
676/// 'typename' [C++1z]
Faisal Valibe294032017-12-23 18:56:34 +0000677NamedDecl *
Faisal Vali6a79ca12013-06-08 19:39:00 +0000678Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
679 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
680
681 // Handle the template <...> part.
682 SourceLocation TemplateLoc = ConsumeToken();
Faisal Valif241b0d2017-08-25 18:24:20 +0000683 SmallVector<NamedDecl*,8> TemplateParams;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000684 SourceLocation LAngleLoc, RAngleLoc;
685 {
686 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
687 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
688 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000689 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000690 }
691 }
692
Richard Smith78e1ca62014-06-16 15:51:22 +0000693 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000694 // Generate a meaningful error if the user forgot to put class before the
695 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000696 // or greater appear immediately or after 'struct'. In the latter case,
697 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000698 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000699 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000700 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
701 if (Tok.is(tok::kw_typename)) {
702 Diag(Tok.getLocation(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000703 getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000704 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000705 : diag::ext_template_template_param_typename)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000706 << (!getLangOpts().CPlusPlus17
Richard Smith78e1ca62014-06-16 15:51:22 +0000707 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
708 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000709 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
710 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000711 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
712 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
713 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000714 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000715 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
716
717 if (Replace)
718 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000719 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000720
721 // Parse the ellipsis, if given.
722 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000723 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000724 Diag(EllipsisLoc,
725 getLangOpts().CPlusPlus11
726 ? diag::warn_cxx98_compat_variadic_templates
727 : diag::ext_variadic_templates);
Fangrui Song6907ce22018-07-30 19:24:48 +0000728
Faisal Vali6a79ca12013-06-08 19:39:00 +0000729 // Get the identifier, if given.
730 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000731 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000732 if (Tok.is(tok::identifier)) {
733 ParamName = Tok.getIdentifierInfo();
734 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000735 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
736 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000737 // Unnamed template parameter. Don't have to do anything here, just
738 // don't consume this token.
739 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000740 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000741 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000742 }
743
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000744 // Recover from misplaced ellipsis.
745 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
746 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
747 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
748
Faisal Vali6a79ca12013-06-08 19:39:00 +0000749 TemplateParameterList *ParamList =
750 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
751 TemplateLoc, LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000752 TemplateParams,
Hubert Tongf608c052016-04-29 18:05:37 +0000753 RAngleLoc, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000754
755 // Grab a default argument (if available).
756 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
757 // we introduce the template parameter into the local scope.
758 SourceLocation EqualLoc;
759 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000760 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000761 DefaultArg = ParseTemplateTemplateArgument();
762 if (DefaultArg.isInvalid()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000763 Diag(Tok.getLocation(),
Faisal Vali6a79ca12013-06-08 19:39:00 +0000764 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000765 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
766 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000767 }
768 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000769
Faisal Vali6a79ca12013-06-08 19:39:00 +0000770 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +0000771 ParamList, EllipsisLoc,
772 ParamName, NameLoc, Depth,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000773 Position, EqualLoc, DefaultArg);
774}
775
776/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
777/// template parameters (e.g., in "template<int Size> class array;").
778///
779/// template-parameter:
780/// ...
781/// parameter-declaration
Faisal Valibe294032017-12-23 18:56:34 +0000782NamedDecl *
Faisal Vali6a79ca12013-06-08 19:39:00 +0000783Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
784 // Parse the declaration-specifiers (i.e., the type).
785 // FIXME: The type should probably be restricted in some way... Not all
786 // declarators (parts of declarators?) are accepted for parameters.
787 DeclSpec DS(AttrFactory);
Faisal Valia534f072018-04-26 00:42:40 +0000788 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
789 DeclSpecContext::DSC_template_param);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000790
791 // Parse this as a typename.
Faisal Vali421b2d12017-12-29 05:41:00 +0000792 Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000793 ParseDeclarator(ParamDecl);
794 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
795 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000796 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000797 }
798
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000799 // Recover from misplaced ellipsis.
800 SourceLocation EllipsisLoc;
801 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
802 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
803
Faisal Vali6a79ca12013-06-08 19:39:00 +0000804 // If there is a default value, parse it.
805 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
806 // we introduce the template parameter into the local scope.
807 SourceLocation EqualLoc;
808 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000809 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000810 // C++ [temp.param]p15:
811 // When parsing a default template-argument for a non-type
812 // template-parameter, the first non-nested > is taken as the
813 // end of the template-parameter-list rather than a greater-than
814 // operator.
815 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Faisal Valid143a0c2017-04-01 21:30:49 +0000816 EnterExpressionEvaluationContext ConstantEvaluated(
817 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000818
Kaelyn Takata999dd852014-12-02 23:32:20 +0000819 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000820 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000821 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000822 }
823
824 // Create the parameter.
Fangrui Song6907ce22018-07-30 19:24:48 +0000825 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
826 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000827 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000828}
829
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000830void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
831 SourceLocation CorrectLoc,
832 bool AlreadyHasEllipsis,
833 bool IdentifierHasName) {
834 FixItHint Insertion;
835 if (!AlreadyHasEllipsis)
836 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
837 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
838 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
839 << !IdentifierHasName;
840}
841
842void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
843 Declarator &D) {
844 assert(EllipsisLoc.isValid());
845 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
846 if (!AlreadyHasEllipsis)
847 D.setEllipsisLoc(EllipsisLoc);
848 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
849 AlreadyHasEllipsis, D.hasName());
850}
851
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000852/// Parses a '>' at the end of a template list.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000853///
854/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
855/// to determine if these tokens were supposed to be a '>' followed by
856/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
857///
858/// \param RAngleLoc the location of the consumed '>'.
859///
Douglas Gregor85f3f952015-07-07 03:57:15 +0000860/// \param ConsumeLastToken if true, the '>' is consumed.
861///
862/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
863/// type parameter or type argument list, rather than a C++ template parameter
864/// or argument list.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000865///
866/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000867bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000868 bool ConsumeLastToken,
869 bool ObjCGenericList) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000870 // What will be left once we've consumed the '>'.
871 tok::TokenKind RemainingToken;
872 const char *ReplacementStr = "> >";
Richard Smithb5f81712018-04-30 05:25:48 +0000873 bool MergeWithNextToken = false;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000874
875 switch (Tok.getKind()) {
876 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000877 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000878 return true;
879
880 case tok::greater:
881 // Determine the location of the '>' token. Only consume this token
882 // if the caller asked us to.
883 RAngleLoc = Tok.getLocation();
884 if (ConsumeLastToken)
885 ConsumeToken();
886 return false;
887
888 case tok::greatergreater:
889 RemainingToken = tok::greater;
890 break;
891
892 case tok::greatergreatergreater:
893 RemainingToken = tok::greatergreater;
894 break;
895
896 case tok::greaterequal:
897 RemainingToken = tok::equal;
898 ReplacementStr = "> =";
Richard Smithb5f81712018-04-30 05:25:48 +0000899
900 // Join two adjacent '=' tokens into one, for cases like:
901 // void (*p)() = f<int>;
902 // return f<int>==p;
903 if (NextToken().is(tok::equal) &&
904 areTokensAdjacent(Tok, NextToken())) {
905 RemainingToken = tok::equalequal;
906 MergeWithNextToken = true;
907 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000908 break;
909
910 case tok::greatergreaterequal:
911 RemainingToken = tok::greaterequal;
912 break;
913 }
914
Richard Smithb5f81712018-04-30 05:25:48 +0000915 // This template-id is terminated by a token that starts with a '>'.
916 // Outside C++11 and Objective-C, this is now error recovery.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000917 //
Richard Smithb5f81712018-04-30 05:25:48 +0000918 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
919 // extend that treatment to also apply to the '>>>' token.
920 //
921 // Objective-C allows this in its type parameter / argument lists.
922
923 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
924 SourceLocation TokLoc = Tok.getLocation();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000925 Token Next = NextToken();
Richard Smithb5f81712018-04-30 05:25:48 +0000926
927 // Whether splitting the current token after the '>' would undesirably result
928 // in the remaining token pasting with the token after it. This excludes the
929 // MergeWithNextToken cases, which we've already handled.
930 bool PreventMergeWithNextToken =
931 (RemainingToken == tok::greater ||
932 RemainingToken == tok::greatergreater) &&
933 (Next.isOneOf(tok::greater, tok::greatergreater,
934 tok::greatergreatergreater, tok::equal, tok::greaterequal,
935 tok::greatergreaterequal, tok::equalequal)) &&
936 areTokensAdjacent(Tok, Next);
937
938 // Diagnose this situation as appropriate.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000939 if (!ObjCGenericList) {
Richard Smithb5f81712018-04-30 05:25:48 +0000940 // The source range of the replaced token(s).
941 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
942 TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
943 getLangOpts()));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000944
Douglas Gregor85f3f952015-07-07 03:57:15 +0000945 // A hint to put a space between the '>>'s. In order to make the hint as
946 // clear as possible, we include the characters either side of the space in
947 // the replacement, rather than just inserting a space at SecondCharLoc.
948 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
949 ReplacementStr);
950
951 // A hint to put another space after the token, if it would otherwise be
952 // lexed differently.
953 FixItHint Hint2;
Richard Smithb5f81712018-04-30 05:25:48 +0000954 if (PreventMergeWithNextToken)
Douglas Gregor85f3f952015-07-07 03:57:15 +0000955 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
956
957 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
958 if (getLangOpts().CPlusPlus11 &&
959 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
960 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
961 else if (Tok.is(tok::greaterequal))
962 DiagId = diag::err_right_angle_bracket_equal_needs_space;
Richard Smithb5f81712018-04-30 05:25:48 +0000963 Diag(TokLoc, DiagId) << Hint1 << Hint2;
Douglas Gregor85f3f952015-07-07 03:57:15 +0000964 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000965
Richard Smithb5f81712018-04-30 05:25:48 +0000966 // Find the "length" of the resulting '>' token. This is not always 1, as it
967 // can contain escaped newlines.
968 unsigned GreaterLength = Lexer::getTokenPrefixLength(
969 TokLoc, 1, PP.getSourceManager(), getLangOpts());
970
971 // Annotate the source buffer to indicate that we split the token after the
972 // '>'. This allows us to properly find the end of, and extract the spelling
973 // of, the '>' token later.
974 RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
975
Faisal Vali6a79ca12013-06-08 19:39:00 +0000976 // Strip the initial '>' from the token.
Richard Smithb5f81712018-04-30 05:25:48 +0000977 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
978
979 Token Greater = Tok;
980 Greater.setLocation(RAngleLoc);
981 Greater.setKind(tok::greater);
982 Greater.setLength(GreaterLength);
983
984 unsigned OldLength = Tok.getLength();
985 if (MergeWithNextToken) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000986 ConsumeToken();
Richard Smithb5f81712018-04-30 05:25:48 +0000987 OldLength += Tok.getLength();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000988 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000989
Richard Smithb5f81712018-04-30 05:25:48 +0000990 Tok.setKind(RemainingToken);
991 Tok.setLength(OldLength - GreaterLength);
992
993 // Split the second token if lexing it normally would lex a different token
994 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
995 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
996 if (PreventMergeWithNextToken)
997 AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
998 Tok.setLocation(AfterGreaterLoc);
999
1000 // Update the token cache to match what we just did if necessary.
1001 if (CachingTokens) {
1002 // If the previous cached token is being merged, delete it.
1003 if (MergeWithNextToken)
1004 PP.ReplacePreviousCachedToken({});
1005
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +00001006 if (ConsumeLastToken)
Richard Smithb5f81712018-04-30 05:25:48 +00001007 PP.ReplacePreviousCachedToken({Greater, Tok});
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +00001008 else
Richard Smithb5f81712018-04-30 05:25:48 +00001009 PP.ReplacePreviousCachedToken({Greater});
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +00001010 }
1011
Richard Smithb5f81712018-04-30 05:25:48 +00001012 if (ConsumeLastToken) {
1013 PrevTokLocation = RAngleLoc;
1014 } else {
1015 PrevTokLocation = TokBeforeGreaterLoc;
Ilya Biryukov929af672019-05-17 09:32:05 +00001016 PP.EnterToken(Tok, /*IsReinject=*/true);
Richard Smithb5f81712018-04-30 05:25:48 +00001017 Tok = Greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001018 }
Richard Smithb5f81712018-04-30 05:25:48 +00001019
Faisal Vali6a79ca12013-06-08 19:39:00 +00001020 return false;
1021}
1022
1023
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001024/// Parses a template-id that after the template name has
Faisal Vali6a79ca12013-06-08 19:39:00 +00001025/// already been parsed.
1026///
1027/// This routine takes care of parsing the enclosed template argument
1028/// list ('<' template-parameter-list [opt] '>') and placing the
1029/// results into a form that can be transferred to semantic analysis.
1030///
Faisal Vali6a79ca12013-06-08 19:39:00 +00001031/// \param ConsumeLastToken if true, then we will consume the last
1032/// token that forms the template-id. Otherwise, we will leave the
1033/// last token in the stream (e.g., so that it can be replaced with an
1034/// annotation token).
1035bool
Richard Smith9a420f92017-05-10 21:47:30 +00001036Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001037 SourceLocation &LAngleLoc,
1038 TemplateArgList &TemplateArgs,
1039 SourceLocation &RAngleLoc) {
1040 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1041
1042 // Consume the '<'.
1043 LAngleLoc = ConsumeToken();
1044
1045 // Parse the optional template-argument-list.
1046 bool Invalid = false;
1047 {
1048 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Artem Belevich2eeb0482018-09-21 17:46:28 +00001049 if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1050 tok::greatergreatergreater, tok::greaterequal,
1051 tok::greatergreaterequal))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001052 Invalid = ParseTemplateArgumentList(TemplateArgs);
1053
1054 if (Invalid) {
1055 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001056 if (ConsumeLastToken)
1057 SkipUntil(tok::greater, StopAtSemi);
1058 else
1059 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001060 return true;
1061 }
1062 }
1063
Douglas Gregor85f3f952015-07-07 03:57:15 +00001064 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
1065 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001066}
1067
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001068/// Replace the tokens that form a simple-template-id with an
Faisal Vali6a79ca12013-06-08 19:39:00 +00001069/// annotation token containing the complete template-id.
1070///
1071/// The first token in the stream must be the name of a template that
1072/// is followed by a '<'. This routine will parse the complete
1073/// simple-template-id and replace the tokens with a single annotation
1074/// token with one of two different kinds: if the template-id names a
1075/// type (and \p AllowTypeAnnotation is true), the annotation token is
1076/// a type annotation that includes the optional nested-name-specifier
1077/// (\p SS). Otherwise, the annotation token is a template-id
1078/// annotation that does not include the optional
1079/// nested-name-specifier.
1080///
1081/// \param Template the declaration of the template named by the first
1082/// token (an identifier), as returned from \c Action::isTemplateName().
1083///
1084/// \param TNK the kind of template that \p Template
1085/// refers to, as returned from \c Action::isTemplateName().
1086///
1087/// \param SS if non-NULL, the nested-name-specifier that precedes
1088/// this template name.
1089///
1090/// \param TemplateKWLoc if valid, specifies that this template-id
1091/// annotation was preceded by the 'template' keyword and gives the
1092/// location of that keyword. If invalid (the default), then this
1093/// template-id was not preceded by a 'template' keyword.
1094///
1095/// \param AllowTypeAnnotation if true (the default), then a
1096/// simple-template-id that refers to a class template, template
1097/// template parameter, or other template that produces a type will be
1098/// replaced with a type annotation token. Otherwise, the
1099/// simple-template-id is always replaced with a template-id
1100/// annotation token.
1101///
1102/// If an unrecoverable parse error occurs and no annotation token can be
1103/// formed, this function returns true.
1104///
1105bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1106 CXXScopeSpec &SS,
1107 SourceLocation TemplateKWLoc,
1108 UnqualifiedId &TemplateName,
1109 bool AllowTypeAnnotation) {
1110 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1111 assert(Template && Tok.is(tok::less) &&
1112 "Parser isn't at the beginning of a template-id");
1113
1114 // Consume the template-name.
1115 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1116
1117 // Parse the enclosed template argument list.
1118 SourceLocation LAngleLoc, RAngleLoc;
1119 TemplateArgList TemplateArgs;
Richard Smith9a420f92017-05-10 21:47:30 +00001120 bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001121 TemplateArgs,
1122 RAngleLoc);
1123
1124 if (Invalid) {
1125 // If we failed to parse the template ID but skipped ahead to a >, we're not
1126 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001127 TryConsumeToken(tok::greater);
Richard Smithb23c5e82019-05-09 03:31:27 +00001128 // FIXME: Annotate the token stream so we don't produce the same errors
1129 // again if we're doing this annotation as part of a tentative parse.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001130 return true;
1131 }
1132
1133 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1134
1135 // Build the annotation token.
1136 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Richard Smith74f02342017-01-19 21:00:13 +00001137 TypeResult Type = Actions.ActOnTemplateIdType(
Richard Smithb23c5e82019-05-09 03:31:27 +00001138 getCurScope(), SS, TemplateKWLoc, Template, TemplateName.Identifier,
Richard Smith74f02342017-01-19 21:00:13 +00001139 TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001140 if (Type.isInvalid()) {
Richard Smith74f02342017-01-19 21:00:13 +00001141 // If we failed to parse the template ID but skipped ahead to a >, we're
1142 // not going to be able to form a token annotation. Eat the '>' if
1143 // present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001144 TryConsumeToken(tok::greater);
Richard Smithb23c5e82019-05-09 03:31:27 +00001145 // FIXME: Annotate the token stream so we don't produce the same errors
1146 // again if we're doing this annotation as part of a tentative parse.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001147 return true;
1148 }
1149
1150 Tok.setKind(tok::annot_typename);
1151 setTypeAnnotation(Tok, Type.get());
1152 if (SS.isNotEmpty())
1153 Tok.setLocation(SS.getBeginLoc());
1154 else if (TemplateKWLoc.isValid())
1155 Tok.setLocation(TemplateKWLoc);
1156 else
1157 Tok.setLocation(TemplateNameLoc);
1158 } else {
1159 // Build a template-id annotation token that can be processed
1160 // later.
1161 Tok.setKind(tok::annot_template_id);
Fangrui Song6907ce22018-07-30 19:24:48 +00001162
Faisal Vali43caf672017-05-23 01:07:12 +00001163 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00001164 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
Faisal Vali43caf672017-05-23 01:07:12 +00001165 ? TemplateName.Identifier
1166 : nullptr;
1167
1168 OverloadedOperatorKind OpKind =
Faisal Vali2ab8c152017-12-30 04:15:27 +00001169 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
Faisal Vali43caf672017-05-23 01:07:12 +00001170 ? OO_None
1171 : TemplateName.OperatorFunctionId.Operator;
1172
Dimitry Andrice4f5d012017-12-18 19:46:56 +00001173 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1174 SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
Faisal Vali43caf672017-05-23 01:07:12 +00001175 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
Fangrui Song6907ce22018-07-30 19:24:48 +00001176
Faisal Vali6a79ca12013-06-08 19:39:00 +00001177 Tok.setAnnotationValue(TemplateId);
1178 if (TemplateKWLoc.isValid())
1179 Tok.setLocation(TemplateKWLoc);
1180 else
1181 Tok.setLocation(TemplateNameLoc);
1182 }
1183
1184 // Common fields for the annotation token
1185 Tok.setAnnotationEndLoc(RAngleLoc);
1186
1187 // In case the tokens were cached, have Preprocessor replace them with the
1188 // annotation token.
1189 PP.AnnotateCachedTokens(Tok);
1190 return false;
1191}
1192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001193/// Replaces a template-id annotation token with a type
Faisal Vali6a79ca12013-06-08 19:39:00 +00001194/// annotation token.
1195///
1196/// If there was a failure when forming the type from the template-id,
1197/// a type annotation token will still be created, but will have a
1198/// NULL type pointer to signify an error.
Richard Smith62559bd2017-02-01 21:36:38 +00001199///
1200/// \param IsClassName Is this template-id appearing in a context where we
1201/// know it names a class, such as in an elaborated-type-specifier or
1202/// base-specifier? ('typename' and 'template' are unneeded and disallowed
1203/// in those contexts.)
1204void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001205 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1206
1207 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1208 assert((TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00001209 TemplateId->Kind == TNK_Dependent_template_name ||
1210 TemplateId->Kind == TNK_Undeclared_template) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001211 "Only works for type and dependent templates");
1212
1213 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1214 TemplateId->NumArgs);
1215
1216 TypeResult Type
Richard Smithb23c5e82019-05-09 03:31:27 +00001217 = Actions.ActOnTemplateIdType(getCurScope(),
1218 TemplateId->SS,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001219 TemplateId->TemplateKWLoc,
1220 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00001221 TemplateId->Name,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001222 TemplateId->TemplateNameLoc,
1223 TemplateId->LAngleLoc,
1224 TemplateArgsPtr,
Richard Smith62559bd2017-02-01 21:36:38 +00001225 TemplateId->RAngleLoc,
1226 /*IsCtorOrDtorName*/false,
1227 IsClassName);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001228 // Create the new "type" annotation token.
1229 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001230 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001231 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1232 Tok.setLocation(TemplateId->SS.getBeginLoc());
1233 // End location stays the same
1234
1235 // Replace the template-id annotation token, and possible the scope-specifier
1236 // that precedes it, with the typename annotation token.
1237 PP.AnnotateCachedTokens(Tok);
1238}
1239
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001240/// Determine whether the given token can end a template argument.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001241static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001242 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001243}
1244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001245/// Parse a C++ template template argument.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001246ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1247 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1248 !Tok.is(tok::annot_cxxscope))
1249 return ParsedTemplateArgument();
1250
1251 // C++0x [temp.arg.template]p1:
1252 // A template-argument for a template template-parameter shall be the name
1253 // of a class template or an alias template, expressed as id-expression.
Fangrui Song6907ce22018-07-30 19:24:48 +00001254 //
Faisal Vali6a79ca12013-06-08 19:39:00 +00001255 // We parse an id-expression that refers to a class template or alias
1256 // template. The grammar we parse is:
1257 //
1258 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1259 //
Fangrui Song6907ce22018-07-30 19:24:48 +00001260 // followed by a token that terminates a template argument, such as ',',
Faisal Vali6a79ca12013-06-08 19:39:00 +00001261 // '>', or (in some cases) '>>'.
1262 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001263 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001264 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001265
Faisal Vali6a79ca12013-06-08 19:39:00 +00001266 ParsedTemplateArgument Result;
1267 SourceLocation EllipsisLoc;
1268 if (SS.isSet() && Tok.is(tok::kw_template)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001269 // Parse the optional 'template' keyword following the
Faisal Vali6a79ca12013-06-08 19:39:00 +00001270 // nested-name-specifier.
1271 SourceLocation TemplateKWLoc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00001272
Faisal Vali6a79ca12013-06-08 19:39:00 +00001273 if (Tok.is(tok::identifier)) {
1274 // We appear to have a dependent template name.
1275 UnqualifiedId Name;
1276 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1277 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001278
1279 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1280
Faisal Vali6a79ca12013-06-08 19:39:00 +00001281 // If the next token signals the end of a template argument,
1282 // then we have a dependent template name that could be a template
1283 // template argument.
1284 TemplateTy Template;
1285 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001286 Actions.ActOnDependentTemplateName(
1287 getCurScope(), SS, TemplateKWLoc, Name,
1288 /*ObjectType=*/nullptr,
1289 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001290 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1291 }
1292 } else if (Tok.is(tok::identifier)) {
1293 // We may have a (non-dependent) template name.
1294 TemplateTy Template;
1295 UnqualifiedId Name;
1296 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1297 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001298
1299 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001300
1301 if (isEndOfTemplateArgument(Tok)) {
1302 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001303 TemplateNameKind TNK = Actions.isTemplateName(
1304 getCurScope(), SS,
1305 /*hasTemplateKeyword=*/false, Name,
1306 /*ObjectType=*/nullptr,
1307 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001308 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1309 // We have an id-expression that refers to a class template or
Fangrui Song6907ce22018-07-30 19:24:48 +00001310 // (C++0x) alias template.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001311 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1312 }
1313 }
1314 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001315
Faisal Vali6a79ca12013-06-08 19:39:00 +00001316 // If this is a pack expansion, build it as such.
1317 if (EllipsisLoc.isValid() && !Result.isInvalid())
1318 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001319
Faisal Vali6a79ca12013-06-08 19:39:00 +00001320 return Result;
1321}
1322
1323/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1324///
1325/// template-argument: [C++ 14.2]
1326/// constant-expression
1327/// type-id
1328/// id-expression
1329ParsedTemplateArgument Parser::ParseTemplateArgument() {
1330 // C++ [temp.arg]p2:
1331 // In a template-argument, an ambiguity between a type-id and an
1332 // expression is resolved to a type-id, regardless of the form of
1333 // the corresponding template-parameter.
1334 //
Faisal Vali56f1de42017-05-20 19:58:04 +00001335 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1336 // up and annotate an identifier as an id-expression during disambiguation,
1337 // so enter the appropriate context for a constant expression template
1338 // argument before trying to disambiguate.
1339
1340 EnterExpressionEvaluationContext EnterConstantEvaluated(
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00001341 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1342 /*LambdaContextDecl=*/nullptr,
1343 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001344 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001345 TypeResult TypeArg = ParseTypeName(
Richard Smith77a9c602018-02-28 03:02:23 +00001346 /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
1347 return Actions.ActOnTemplateTypeArgument(TypeArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001348 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001349
Faisal Vali6a79ca12013-06-08 19:39:00 +00001350 // Try to parse a template template argument.
1351 {
1352 TentativeParsingAction TPA(*this);
1353
1354 ParsedTemplateArgument TemplateTemplateArgument
1355 = ParseTemplateTemplateArgument();
1356 if (!TemplateTemplateArgument.isInvalid()) {
1357 TPA.Commit();
1358 return TemplateTemplateArgument;
1359 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001360
Faisal Vali6a79ca12013-06-08 19:39:00 +00001361 // Revert this tentative parse to parse a non-type template argument.
1362 TPA.Revert();
1363 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001364
1365 // Parse a non-type template argument.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001366 SourceLocation Loc = Tok.getLocation();
Faisal Vali56f1de42017-05-20 19:58:04 +00001367 ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001368 if (ExprArg.isInvalid() || !ExprArg.get())
1369 return ParsedTemplateArgument();
1370
Fangrui Song6907ce22018-07-30 19:24:48 +00001371 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001372 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001373}
1374
Faisal Vali6a79ca12013-06-08 19:39:00 +00001375/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1376/// (C++ [temp.names]). Returns true if there was an error.
1377///
1378/// template-argument-list: [C++ 14.2]
1379/// template-argument
1380/// template-argument-list ',' template-argument
1381bool
1382Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001383
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001384 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001385
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001386 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001387 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001388 SourceLocation EllipsisLoc;
1389 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001390 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001391
1392 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001393 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001394 return true;
1395 }
1396
1397 // Save this template argument.
1398 TemplateArgs.push_back(Arg);
Fangrui Song6907ce22018-07-30 19:24:48 +00001399
Faisal Vali6a79ca12013-06-08 19:39:00 +00001400 // If the next token is a comma, consume it and keep reading
1401 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001402 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001403
1404 return false;
1405}
1406
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001407/// Parse a C++ explicit template instantiation
Faisal Vali6a79ca12013-06-08 19:39:00 +00001408/// (C++ [temp.explicit]).
1409///
1410/// explicit-instantiation:
1411/// 'extern' [opt] 'template' declaration
1412///
1413/// Note that the 'extern' is a GNU extension and C++11 feature.
Faisal Vali421b2d12017-12-29 05:41:00 +00001414Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001415 SourceLocation ExternLoc,
1416 SourceLocation TemplateLoc,
1417 SourceLocation &DeclEnd,
Erich Keanec480f302018-07-12 21:09:05 +00001418 ParsedAttributes &AccessAttrs,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001419 AccessSpecifier AS) {
1420 // This isn't really required here.
1421 ParsingDeclRAIIObject
1422 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1423
Erich Keanec480f302018-07-12 21:09:05 +00001424 return ParseSingleDeclarationAfterTemplate(
1425 Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1426 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001427}
1428
1429SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1430 if (TemplateParams)
1431 return getTemplateParamsRange(TemplateParams->data(),
1432 TemplateParams->size());
1433
1434 SourceRange R(TemplateLoc);
1435 if (ExternLoc.isValid())
1436 R.setBegin(ExternLoc);
1437 return R;
1438}
1439
Richard Smithe40f2ba2013-08-07 21:41:30 +00001440void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1441 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001442}
1443
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001444/// Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001445void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001446 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001447 return;
1448
1449 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001450 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001451 // Track template parameter depth.
1452 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1453
1454 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001455 Sema::ContextRAII GlobalSavedContext(
1456 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001457
1458 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1459
Reid Kleckner229eee42018-11-27 21:20:42 +00001460 // Get the list of DeclContexts to reenter. For inline methods, we only want
1461 // to push the DeclContext of the outermost class. This matches the way the
1462 // parser normally parses bodies of inline methods when the outermost class is
1463 // complete.
1464 struct ContainingDC {
1465 ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1466 llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1467 DeclContext *getDC() { return Pair.getPointer(); }
1468 bool shouldPushDC() { return Pair.getInt(); }
1469 };
1470 SmallVector<ContainingDC, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001471 DeclContext *DD = FunD;
Reid Kleckner229eee42018-11-27 21:20:42 +00001472 DeclContext *NextContaining = Actions.getContainingDC(DD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001473 while (DD && !DD->isTranslationUnit()) {
Reid Kleckner229eee42018-11-27 21:20:42 +00001474 bool ShouldPush = DD == NextContaining;
1475 DeclContextsToReenter.push_back({DD, ShouldPush});
1476 if (ShouldPush)
1477 NextContaining = Actions.getContainingDC(DD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001478 DD = DD->getLexicalParent();
1479 }
1480
1481 // Reenter template scopes from outermost to innermost.
Reid Kleckner229eee42018-11-27 21:20:42 +00001482 for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
1483 TemplateParamScopeStack.push_back(
1484 new ParseScope(this, Scope::TemplateParamScope));
1485 unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
1486 getCurScope(), cast<Decl>(CDC.getDC()));
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001487 CurTemplateDepthTracker.addDepth(NumParamLists);
Reid Kleckner229eee42018-11-27 21:20:42 +00001488 if (CDC.shouldPushDC()) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001489 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
Reid Kleckner229eee42018-11-27 21:20:42 +00001490 Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001491 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001492 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001493
Richard Smithe40f2ba2013-08-07 21:41:30 +00001494 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001495
1496 // Append the current token at the end of the new token stream so that it
1497 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001498 LPT.Toks.push_back(Tok);
Ilya Biryukov929af672019-05-17 09:32:05 +00001499 PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001500
1501 // Consume the previously pushed token.
1502 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001503 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1504 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001505
1506 // Parse the method body. Function body parsing code is similar enough
1507 // to be re-used for method bodies as well.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001508 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1509 Scope::CompoundStmtScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001510
1511 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001512 Sema::ContextRAII FunctionSavedContext(Actions,
1513 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001514
1515 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1516
1517 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001518 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001519 } else {
1520 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001521 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001522 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001523 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001524
1525 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001526 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1527 cast<FunctionTemplateDecl>(LPT.D)
1528 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001529 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001530 "TemplateParameterDepth should be greater than the depth of "
1531 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001532 ParseFunctionStatementBody(LPT.D, FnScope);
1533 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001534 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001535 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001536 }
1537
1538 // Exit scopes.
1539 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001540 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001541 TemplateParamScopeStack.rbegin();
1542 for (; I != TemplateParamScopeStack.rend(); ++I)
1543 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001544}
1545
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001546/// Lex a delayed template function for late parsing.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001547void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1548 tok::TokenKind kind = Tok.getKind();
1549 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1550 // Consume everything up to (and including) the matching right brace.
1551 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1552 }
1553
1554 // If we're in a function-try-block, we need to store all the catch blocks.
1555 if (kind == tok::kw_try) {
1556 while (Tok.is(tok::kw_catch)) {
1557 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1558 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1559 }
1560 }
1561}
Richard Smithc2dead42018-06-27 01:32:04 +00001562
1563/// We've parsed something that could plausibly be intended to be a template
1564/// name (\p LHS) followed by a '<' token, and the following code can't possibly
1565/// be an expression. Determine if this is likely to be a template-id and if so,
1566/// diagnose it.
1567bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1568 TentativeParsingAction TPA(*this);
1569 // FIXME: We could look at the token sequence in a lot more detail here.
1570 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1571 StopAtSemi | StopBeforeMatch)) {
1572 TPA.Commit();
1573
1574 SourceLocation Greater;
1575 ParseGreaterThanInTemplateList(Greater, true, false);
1576 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1577 Less, Greater);
1578 return true;
1579 }
1580
1581 // There's no matching '>' token, this probably isn't supposed to be
1582 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1583 TPA.Revert();
1584 return false;
1585}
1586
1587void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1588 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1589
1590 bool DependentTemplateName = false;
1591 if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1592 DependentTemplateName))
1593 return;
1594
1595 // OK, this might be a name that the user intended to be parsed as a
1596 // template-name, followed by a '<' token. Check for some easy cases.
1597
1598 // If we have potential_template<>, then it's supposed to be a template-name.
1599 if (NextToken().is(tok::greater) ||
1600 (getLangOpts().CPlusPlus11 &&
1601 NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1602 SourceLocation Less = ConsumeToken();
1603 SourceLocation Greater;
1604 ParseGreaterThanInTemplateList(Greater, true, false);
1605 Actions.diagnoseExprIntendedAsTemplateName(
1606 getCurScope(), PotentialTemplateName, Less, Greater);
1607 // FIXME: Perform error recovery.
1608 PotentialTemplateName = ExprError();
1609 return;
1610 }
1611
1612 // If we have 'potential_template<type-id', assume it's supposed to be a
1613 // template-name if there's a matching '>' later on.
1614 {
1615 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1616 TentativeParsingAction TPA(*this);
1617 SourceLocation Less = ConsumeToken();
1618 if (isTypeIdUnambiguously() &&
1619 diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1620 TPA.Commit();
1621 // FIXME: Perform error recovery.
1622 PotentialTemplateName = ExprError();
1623 return;
1624 }
1625 TPA.Revert();
1626 }
1627
1628 // Otherwise, remember that we saw this in case we see a potentially-matching
1629 // '>' token later on.
1630 AngleBracketTracker::Priority Priority =
1631 (DependentTemplateName ? AngleBracketTracker::DependentName
1632 : AngleBracketTracker::PotentialTypo) |
1633 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1634 : AngleBracketTracker::NoSpaceBeforeLess);
1635 AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1636 Priority);
1637}
1638
1639bool Parser::checkPotentialAngleBracketDelimiter(
1640 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1641 // If a comma in an expression context is followed by a type that can be a
1642 // template argument and cannot be an expression, then this is ill-formed,
1643 // but might be intended to be part of a template-id.
1644 if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1645 diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1646 AngleBrackets.clear(*this);
1647 return true;
1648 }
1649
1650 // If a context that looks like a template-id is followed by '()', then
1651 // this is ill-formed, but might be intended to be a template-id
1652 // followed by '()'.
1653 if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1654 NextToken().is(tok::r_paren)) {
1655 Actions.diagnoseExprIntendedAsTemplateName(
1656 getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1657 OpToken.getLocation());
1658 AngleBrackets.clear(*this);
1659 return true;
1660 }
1661
1662 // After a '>' (etc), we're no longer potentially in a construct that's
1663 // intended to be treated as a template-id.
1664 if (OpToken.is(tok::greater) ||
1665 (getLangOpts().CPlusPlus11 &&
1666 OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1667 AngleBrackets.clear(*this);
1668 return false;
1669}