blob: b53e6ea09bb53f41a17512c47626bd7b62776cf3 [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///
52/// explicit-specialization: [ C++ temp.expl.spec]
53/// 'template' '<' '>' declaration
Erich Keanec480f302018-07-12 21:09:05 +000054Decl *Parser::ParseTemplateDeclarationOrSpecialization(
55 DeclaratorContext Context, SourceLocation &DeclEnd,
56 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +000057 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +000058 "Token does not start a template declaration.");
59
60 // Enter template-parameter scope.
61 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
62
63 // Tell the action that names should be checked in the context of
64 // the declaration to come.
65 ParsingDeclRAIIObject
66 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
67
68 // Parse multiple levels of template headers within this template
69 // parameter scope, e.g.,
70 //
71 // template<typename T>
72 // template<typename U>
73 // class A<T>::B { ... };
74 //
75 // We parse multiple levels non-recursively so that we can build a
76 // single data structure containing all of the template parameter
77 // lists to easily differentiate between the case above and:
78 //
79 // template<typename T>
80 // class A {
81 // template<typename U> class B;
82 // };
83 //
84 // In the first case, the action for declaring A<T>::B receives
85 // both template parameter lists. In the second case, the action for
86 // defining A<T>::B receives just the inner template parameter list
87 // (and retrieves the outer template parameter list from its
88 // context).
89 bool isSpecialization = true;
90 bool LastParamListWasEmpty = false;
91 TemplateParameterLists ParamLists;
92 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
93
94 do {
95 // Consume the 'export', if any.
96 SourceLocation ExportLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +000097 TryConsumeToken(tok::kw_export, ExportLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +000098
99 // Consume the 'template', which should be here.
100 SourceLocation TemplateLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000101 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000102 Diag(Tok.getLocation(), diag::err_expected_template);
Craig Topper161e4db2014-05-21 06:02:52 +0000103 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000104 }
105
106 // Parse the '<' template-parameter-list '>'
107 SourceLocation LAngleLoc, RAngleLoc;
Faisal Valif241b0d2017-08-25 18:24:20 +0000108 SmallVector<NamedDecl*, 4> TemplateParams;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000109 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
110 TemplateParams, LAngleLoc, RAngleLoc)) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000111 // Skip until the semi-colon or a '}'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000112 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000113 TryConsumeToken(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000114 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000115 }
116
Hubert Tongf608c052016-04-29 18:05:37 +0000117 ExprResult OptionalRequiresClauseConstraintER;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000118 if (!TemplateParams.empty()) {
119 isSpecialization = false;
120 ++CurTemplateDepthTracker;
Hubert Tongec3cb572015-06-25 00:23:39 +0000121
122 if (TryConsumeToken(tok::kw_requires)) {
Hubert Tongf608c052016-04-29 18:05:37 +0000123 OptionalRequiresClauseConstraintER =
Hubert Tongec3cb572015-06-25 00:23:39 +0000124 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
Hubert Tongf608c052016-04-29 18:05:37 +0000125 if (!OptionalRequiresClauseConstraintER.isUsable()) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000126 // Skip until the semi-colon or a '}'.
127 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
128 TryConsumeToken(tok::semi);
129 return nullptr;
130 }
131 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000132 } else {
133 LastParamListWasEmpty = true;
134 }
Hubert Tongf608c052016-04-29 18:05:37 +0000135
136 ParamLists.push_back(Actions.ActOnTemplateParameterList(
137 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
138 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000139 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000140
Akira Hatanaka10aced82016-04-29 02:24:14 +0000141 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
142 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
143
Faisal Valia534f072018-04-26 00:42:40 +0000144 // Parse the actual template declaration.
Erich Keanec480f302018-07-12 21:09:05 +0000145 return ParseSingleDeclarationAfterTemplate(
146 Context,
147 ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
148 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000149}
150
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000151/// Parse a single declaration that declares a template,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000152/// template specialization, or explicit instantiation of a template.
153///
154/// \param DeclEnd will receive the source location of the last token
155/// within this declaration.
156///
157/// \param AS the access specifier associated with this
158/// declaration. Will be AS_none for namespace-scope declarations.
159///
160/// \returns the new declaration.
Erich Keanec480f302018-07-12 21:09:05 +0000161Decl *Parser::ParseSingleDeclarationAfterTemplate(
162 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
163 ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
164 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000165 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
166 "Template information required");
167
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000168 if (Tok.is(tok::kw_static_assert)) {
169 // A static_assert declaration may not be templated.
170 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
171 << TemplateInfo.getSourceRange();
172 // Parse the static_assert declaration to improve error recovery.
173 return ParseStaticAssertDeclaration(DeclEnd);
174 }
175
Faisal Vali421b2d12017-12-29 05:41:00 +0000176 if (Context == DeclaratorContext::MemberContext) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000177 // We are parsing a member template.
178 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
179 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000180 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000181 }
182
183 ParsedAttributesWithRange prefixAttrs(AttrFactory);
184 MaybeParseCXX11Attributes(prefixAttrs);
185
Richard Smith6f1daa42016-12-16 00:58:48 +0000186 if (Tok.is(tok::kw_using)) {
Erik Verbruggen51ee12a2017-09-08 09:31:13 +0000187 auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
188 prefixAttrs);
189 if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
190 return nullptr;
191 return usingDeclPtr.get().getSingleDecl();
Richard Smith6f1daa42016-12-16 00:58:48 +0000192 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000193
194 // Parse the declaration specifiers, stealing any diagnostics from
195 // the template parameters.
196 ParsingDeclSpec DS(*this, &DiagsFromTParams);
197
Faisal Valia534f072018-04-26 00:42:40 +0000198 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000199 getDeclSpecContextFromDeclaratorContext(Context));
200
201 if (Tok.is(tok::semi)) {
202 ProhibitAttributes(prefixAttrs);
203 DeclEnd = ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +0000204 RecordDecl *AnonRecord = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000205 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
206 getCurScope(), AS, DS,
207 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
208 : MultiTemplateParamsArg(),
Nico Weber7b837f52016-01-28 19:25:00 +0000209 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
210 AnonRecord);
211 assert(!AnonRecord &&
212 "Anonymous unions/structs should not be valid with template");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000213 DS.complete(Decl);
214 return Decl;
215 }
216
217 // Move the attributes from the prefix into the DS.
218 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
219 ProhibitAttributes(prefixAttrs);
220 else
221 DS.takeAttributesFrom(prefixAttrs);
222
223 // Parse the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +0000224 ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000225 ParseDeclarator(DeclaratorInfo);
226 // Error parsing the declarator?
227 if (!DeclaratorInfo.hasName()) {
228 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000229 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000230 if (Tok.is(tok::semi))
231 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000232 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000233 }
234
Anton Afanasyevd880de22019-03-30 08:42:48 +0000235 llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
236 return DeclaratorInfo.getIdentifier() != nullptr
237 ? DeclaratorInfo.getIdentifier()->getName()
238 : "<unknown>";
239 });
240
Faisal Vali6a79ca12013-06-08 19:39:00 +0000241 LateParsedAttrList LateParsedAttrs(true);
242 if (DeclaratorInfo.isFunctionDeclarator())
243 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
244
245 if (DeclaratorInfo.isFunctionDeclarator() &&
246 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000247
248 // Function definitions are only allowed at file scope and in C++ classes.
249 // The C++ inline method definition case is handled elsewhere, so we only
250 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +0000251 if (Context != DeclaratorContext::FileContext) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000252 Diag(Tok, diag::err_function_definition_not_allowed);
253 SkipMalformedDecl();
254 return nullptr;
255 }
256
Faisal Vali6a79ca12013-06-08 19:39:00 +0000257 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
258 // Recover by ignoring the 'typedef'. This was probably supposed to be
259 // the 'typename' keyword, which we should have already suggested adding
260 // if it's appropriate.
261 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
262 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
263 DS.ClearStorageClassSpecs();
264 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000265
266 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000267 if (DeclaratorInfo.getName().getKind() !=
268 UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo725de3e2013-06-21 00:08:46 +0000269 // If the declarator-id is not a template-id, issue a diagnostic and
270 // recover by ignoring the 'template' keyword.
271 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000272 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
273 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000274 } else {
275 SourceLocation LAngleLoc
276 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000277 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000278 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000279 << SourceRange(TemplateInfo.TemplateLoc)
280 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000281
Larisse Voufo39a1e502013-08-06 01:03:05 +0000282 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000283 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000284 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +0000285 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +0000286 LAngleLoc, nullptr));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000287
Larisse Voufo39a1e502013-08-06 01:03:05 +0000288 return ParseFunctionDefinition(
289 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
290 /*isSpecialization=*/true,
291 /*LastParamListWasEmpty=*/true),
292 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000293 }
294 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000295 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000296 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000297 }
298
299 // Parse this declaration.
300 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
301 TemplateInfo);
302
303 if (Tok.is(tok::comma)) {
304 Diag(Tok, diag::err_multiple_template_declarators)
305 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000306 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000307 return ThisDecl;
308 }
309
310 // Eat the semi colon after the declaration.
311 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
312 if (LateParsedAttrs.size() > 0)
313 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
314 DeclaratorInfo.complete(ThisDecl);
315 return ThisDecl;
316}
317
318/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
319/// angle brackets. Depth is the depth of this template-parameter-list, which
320/// is the number of template headers directly enclosing this template header.
321/// TemplateParams is the current list of template parameters we're building.
322/// The template parameter we parse will be added to this list. LAngleLoc and
323/// RAngleLoc will receive the positions of the '<' and '>', respectively,
324/// that enclose this template parameter list.
325///
326/// \returns true if an error occurred, false otherwise.
Faisal Valif241b0d2017-08-25 18:24:20 +0000327bool Parser::ParseTemplateParameters(
328 unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
329 SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000330 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000331 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000332 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
333 return true;
334 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000335
336 // Try to parse the template parameter list.
337 bool Failed = false;
338 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
339 Failed = ParseTemplateParameterList(Depth, TemplateParams);
340
341 if (Tok.is(tok::greatergreater)) {
342 // No diagnostic required here: a template-parameter-list can only be
343 // followed by a declaration or, for a template template parameter, the
344 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
345 // This matters for elegant diagnosis of:
346 // template<template<typename>> struct S;
347 Tok.setKind(tok::greater);
348 RAngleLoc = Tok.getLocation();
349 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000350 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
351 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000352 return true;
353 }
354 return false;
355}
356
357/// ParseTemplateParameterList - Parse a template parameter list. If
358/// the parsing fails badly (i.e., closing bracket was left out), this
359/// will try to put the token stream in a reasonable position (closing
360/// a statement, etc.) and return false.
361///
362/// template-parameter-list: [C++ temp]
363/// template-parameter
364/// template-parameter-list ',' template-parameter
365bool
Faisal Vali421b2d12017-12-29 05:41:00 +0000366Parser::ParseTemplateParameterList(const unsigned Depth,
Faisal Valif241b0d2017-08-25 18:24:20 +0000367 SmallVectorImpl<NamedDecl*> &TemplateParams) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000368 while (1) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000369
Faisal Valibe294032017-12-23 18:56:34 +0000370 if (NamedDecl *TmpParam
Faisal Vali6a79ca12013-06-08 19:39:00 +0000371 = ParseTemplateParameter(Depth, TemplateParams.size())) {
Faisal Valid9548c32017-12-23 19:27:07 +0000372 TemplateParams.push_back(TmpParam);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000373 } else {
374 // If we failed to parse a template parameter, skip until we find
375 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000376 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
377 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000378 }
379
380 // Did we find a comma or the end of the template parameter list?
381 if (Tok.is(tok::comma)) {
382 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000383 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000384 // Don't consume this... that's done by template parser.
385 break;
386 } else {
387 // Somebody probably forgot to close the template. Skip ahead and
388 // try to get out of the expression. This error is currently
389 // subsumed by whatever goes on in ParseTemplateParameter.
390 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000391 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
392 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000393 return false;
394 }
395 }
396 return true;
397}
398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000399/// Determine whether the parser is at the start of a template
Faisal Vali6a79ca12013-06-08 19:39:00 +0000400/// type parameter.
401bool Parser::isStartOfTemplateTypeParameter() {
402 if (Tok.is(tok::kw_class)) {
403 // "class" may be the start of an elaborated-type-specifier or a
404 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
405 switch (NextToken().getKind()) {
406 case tok::equal:
407 case tok::comma:
408 case tok::greater:
409 case tok::greatergreater:
410 case tok::ellipsis:
411 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000412
Faisal Vali6a79ca12013-06-08 19:39:00 +0000413 case tok::identifier:
Fangrui Song6907ce22018-07-30 19:24:48 +0000414 // This may be either a type-parameter or an elaborated-type-specifier.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000415 // We have to look further.
416 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000417
Faisal Vali6a79ca12013-06-08 19:39:00 +0000418 default:
419 return false;
420 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000421
Faisal Vali6a79ca12013-06-08 19:39:00 +0000422 switch (GetLookAheadToken(2).getKind()) {
423 case tok::equal:
424 case tok::comma:
425 case tok::greater:
426 case tok::greatergreater:
427 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000428
Faisal Vali6a79ca12013-06-08 19:39:00 +0000429 default:
430 return false;
431 }
432 }
433
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000434 // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
435 // ill-formed otherwise.
436 if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000437 return false;
438
439 // C++ [temp.param]p2:
440 // There is no semantic difference between class and typename in a
441 // template-parameter. typename followed by an unqualified-id
442 // names a template type parameter. typename followed by a
443 // qualified-id denotes the type in a non-type
444 // parameter-declaration.
445 Token Next = NextToken();
446
447 // If we have an identifier, skip over it.
448 if (Next.getKind() == tok::identifier)
449 Next = GetLookAheadToken(2);
450
451 switch (Next.getKind()) {
452 case tok::equal:
453 case tok::comma:
454 case tok::greater:
455 case tok::greatergreater:
456 case tok::ellipsis:
457 return true;
458
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000459 case tok::kw_typename:
460 case tok::kw_typedef:
461 case tok::kw_class:
462 // These indicate that a comma was missed after a type parameter, not that
463 // we have found a non-type parameter.
464 return true;
465
Faisal Vali6a79ca12013-06-08 19:39:00 +0000466 default:
467 return false;
468 }
469}
470
471/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
472///
473/// template-parameter: [C++ temp.param]
474/// type-parameter
475/// parameter-declaration
476///
477/// type-parameter: (see below)
478/// 'class' ...[opt] identifier[opt]
479/// 'class' identifier[opt] '=' type-id
480/// 'typename' ...[opt] identifier[opt]
481/// 'typename' identifier[opt] '=' type-id
Fangrui Song6907ce22018-07-30 19:24:48 +0000482/// 'template' '<' template-parameter-list '>'
Faisal Vali6a79ca12013-06-08 19:39:00 +0000483/// 'class' ...[opt] identifier[opt]
484/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
485/// = id-expression
Faisal Valibe294032017-12-23 18:56:34 +0000486NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000487 if (isStartOfTemplateTypeParameter()) {
488 // Is there just a typo in the input code? ('typedef' instead of 'typename')
489 if (Tok.is(tok::kw_typedef)) {
490 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000491
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000492 Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
493 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
494 Tok.getLocation(), Tok.getEndLoc()),
495 "typename");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000496
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000497 Tok.setKind(tok::kw_typename);
498 }
Jan Korous3a98e512018-02-08 14:37:58 +0000499
500 return ParseTypeParameter(Depth, Position);
501 }
502
Richard Smithf9a5d5f2018-08-17 19:43:40 +0000503 if (Tok.is(tok::kw_template))
504 return ParseTemplateTemplateParameter(Depth, Position);
505
Faisal Vali6a79ca12013-06-08 19:39:00 +0000506 // If it's none of the above, then it must be a parameter declaration.
507 // NOTE: This will pick up errors in the closure of the template parameter
508 // list (e.g., template < ; Check here to implement >> style closures.
509 return ParseNonTypeTemplateParameter(Depth, Position);
510}
511
512/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
513/// Other kinds of template parameters are parsed in
514/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
515///
516/// type-parameter: [C++ temp.param]
517/// 'class' ...[opt][C++0x] identifier[opt]
518/// 'class' identifier[opt] '=' type-id
519/// 'typename' ...[opt][C++0x] identifier[opt]
520/// 'typename' identifier[opt] '=' type-id
Faisal Valibe294032017-12-23 18:56:34 +0000521NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000522 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000523 "A type-parameter starts with 'class' or 'typename'");
524
525 // Consume the 'class' or 'typename' keyword.
526 bool TypenameKeyword = Tok.is(tok::kw_typename);
527 SourceLocation KeyLoc = ConsumeToken();
528
529 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000530 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000531 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000532 Diag(EllipsisLoc,
533 getLangOpts().CPlusPlus11
534 ? diag::warn_cxx98_compat_variadic_templates
535 : diag::ext_variadic_templates);
536 }
537
538 // Grab the template parameter name (if given)
539 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000540 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000541 if (Tok.is(tok::identifier)) {
542 ParamName = Tok.getIdentifierInfo();
543 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000544 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
545 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000546 // Unnamed template parameter. Don't have to do anything here, just
547 // don't consume this token.
548 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000549 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000550 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000551 }
552
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000553 // Recover from misplaced ellipsis.
554 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
555 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
556 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
557
Faisal Vali6a79ca12013-06-08 19:39:00 +0000558 // Grab a default argument (if available).
559 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
560 // we introduce the type parameter into the local scope.
561 SourceLocation EqualLoc;
562 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000563 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000564 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali421b2d12017-12-29 05:41:00 +0000565 DeclaratorContext::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000566
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000567 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
568 KeyLoc, ParamName, NameLoc, Depth, Position,
569 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000570}
571
572/// ParseTemplateTemplateParameter - Handle the parsing of template
573/// template parameters.
574///
575/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000576/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000577/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000578/// 'template' '<' template-parameter-list '>' type-parameter-key
579/// identifier[opt] = id-expression
580/// type-parameter-key:
581/// 'class'
582/// 'typename' [C++1z]
Faisal Valibe294032017-12-23 18:56:34 +0000583NamedDecl *
Faisal Vali6a79ca12013-06-08 19:39:00 +0000584Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
585 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
586
587 // Handle the template <...> part.
588 SourceLocation TemplateLoc = ConsumeToken();
Faisal Valif241b0d2017-08-25 18:24:20 +0000589 SmallVector<NamedDecl*,8> TemplateParams;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000590 SourceLocation LAngleLoc, RAngleLoc;
591 {
592 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
593 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
594 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000595 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000596 }
597 }
598
Richard Smith78e1ca62014-06-16 15:51:22 +0000599 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000600 // Generate a meaningful error if the user forgot to put class before the
601 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000602 // or greater appear immediately or after 'struct'. In the latter case,
603 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000604 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000605 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000606 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
607 if (Tok.is(tok::kw_typename)) {
608 Diag(Tok.getLocation(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000609 getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000610 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000611 : diag::ext_template_template_param_typename)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000612 << (!getLangOpts().CPlusPlus17
Richard Smith78e1ca62014-06-16 15:51:22 +0000613 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
614 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000615 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
616 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000617 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
618 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
619 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000620 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000621 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
622
623 if (Replace)
624 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000625 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000626
627 // Parse the ellipsis, if given.
628 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000629 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000630 Diag(EllipsisLoc,
631 getLangOpts().CPlusPlus11
632 ? diag::warn_cxx98_compat_variadic_templates
633 : diag::ext_variadic_templates);
Fangrui Song6907ce22018-07-30 19:24:48 +0000634
Faisal Vali6a79ca12013-06-08 19:39:00 +0000635 // Get the identifier, if given.
636 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000637 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000638 if (Tok.is(tok::identifier)) {
639 ParamName = Tok.getIdentifierInfo();
640 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000641 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
642 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000643 // Unnamed template parameter. Don't have to do anything here, just
644 // don't consume this token.
645 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000646 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000647 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000648 }
649
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000650 // Recover from misplaced ellipsis.
651 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
652 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
653 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
654
Faisal Vali6a79ca12013-06-08 19:39:00 +0000655 TemplateParameterList *ParamList =
656 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
657 TemplateLoc, LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000658 TemplateParams,
Hubert Tongf608c052016-04-29 18:05:37 +0000659 RAngleLoc, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000660
661 // Grab a default argument (if available).
662 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
663 // we introduce the template parameter into the local scope.
664 SourceLocation EqualLoc;
665 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000666 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000667 DefaultArg = ParseTemplateTemplateArgument();
668 if (DefaultArg.isInvalid()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000669 Diag(Tok.getLocation(),
Faisal Vali6a79ca12013-06-08 19:39:00 +0000670 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000671 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
672 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000673 }
674 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000675
Faisal Vali6a79ca12013-06-08 19:39:00 +0000676 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +0000677 ParamList, EllipsisLoc,
678 ParamName, NameLoc, Depth,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000679 Position, EqualLoc, DefaultArg);
680}
681
682/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
683/// template parameters (e.g., in "template<int Size> class array;").
684///
685/// template-parameter:
686/// ...
687/// parameter-declaration
Faisal Valibe294032017-12-23 18:56:34 +0000688NamedDecl *
Faisal Vali6a79ca12013-06-08 19:39:00 +0000689Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
690 // Parse the declaration-specifiers (i.e., the type).
691 // FIXME: The type should probably be restricted in some way... Not all
692 // declarators (parts of declarators?) are accepted for parameters.
693 DeclSpec DS(AttrFactory);
Faisal Valia534f072018-04-26 00:42:40 +0000694 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
695 DeclSpecContext::DSC_template_param);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000696
697 // Parse this as a typename.
Faisal Vali421b2d12017-12-29 05:41:00 +0000698 Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000699 ParseDeclarator(ParamDecl);
700 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
701 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000702 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000703 }
704
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000705 // Recover from misplaced ellipsis.
706 SourceLocation EllipsisLoc;
707 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
708 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
709
Faisal Vali6a79ca12013-06-08 19:39:00 +0000710 // If there is a default value, parse it.
711 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
712 // we introduce the template parameter into the local scope.
713 SourceLocation EqualLoc;
714 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000715 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000716 // C++ [temp.param]p15:
717 // When parsing a default template-argument for a non-type
718 // template-parameter, the first non-nested > is taken as the
719 // end of the template-parameter-list rather than a greater-than
720 // operator.
721 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Faisal Valid143a0c2017-04-01 21:30:49 +0000722 EnterExpressionEvaluationContext ConstantEvaluated(
723 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000724
Kaelyn Takata999dd852014-12-02 23:32:20 +0000725 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000726 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000727 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000728 }
729
730 // Create the parameter.
Fangrui Song6907ce22018-07-30 19:24:48 +0000731 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
732 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000733 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000734}
735
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000736void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
737 SourceLocation CorrectLoc,
738 bool AlreadyHasEllipsis,
739 bool IdentifierHasName) {
740 FixItHint Insertion;
741 if (!AlreadyHasEllipsis)
742 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
743 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
744 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
745 << !IdentifierHasName;
746}
747
748void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
749 Declarator &D) {
750 assert(EllipsisLoc.isValid());
751 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
752 if (!AlreadyHasEllipsis)
753 D.setEllipsisLoc(EllipsisLoc);
754 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
755 AlreadyHasEllipsis, D.hasName());
756}
757
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000758/// Parses a '>' at the end of a template list.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000759///
760/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
761/// to determine if these tokens were supposed to be a '>' followed by
762/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
763///
764/// \param RAngleLoc the location of the consumed '>'.
765///
Douglas Gregor85f3f952015-07-07 03:57:15 +0000766/// \param ConsumeLastToken if true, the '>' is consumed.
767///
768/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
769/// type parameter or type argument list, rather than a C++ template parameter
770/// or argument list.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000771///
772/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000773bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000774 bool ConsumeLastToken,
775 bool ObjCGenericList) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000776 // What will be left once we've consumed the '>'.
777 tok::TokenKind RemainingToken;
778 const char *ReplacementStr = "> >";
Richard Smithb5f81712018-04-30 05:25:48 +0000779 bool MergeWithNextToken = false;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000780
781 switch (Tok.getKind()) {
782 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000783 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000784 return true;
785
786 case tok::greater:
787 // Determine the location of the '>' token. Only consume this token
788 // if the caller asked us to.
789 RAngleLoc = Tok.getLocation();
790 if (ConsumeLastToken)
791 ConsumeToken();
792 return false;
793
794 case tok::greatergreater:
795 RemainingToken = tok::greater;
796 break;
797
798 case tok::greatergreatergreater:
799 RemainingToken = tok::greatergreater;
800 break;
801
802 case tok::greaterequal:
803 RemainingToken = tok::equal;
804 ReplacementStr = "> =";
Richard Smithb5f81712018-04-30 05:25:48 +0000805
806 // Join two adjacent '=' tokens into one, for cases like:
807 // void (*p)() = f<int>;
808 // return f<int>==p;
809 if (NextToken().is(tok::equal) &&
810 areTokensAdjacent(Tok, NextToken())) {
811 RemainingToken = tok::equalequal;
812 MergeWithNextToken = true;
813 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000814 break;
815
816 case tok::greatergreaterequal:
817 RemainingToken = tok::greaterequal;
818 break;
819 }
820
Richard Smithb5f81712018-04-30 05:25:48 +0000821 // This template-id is terminated by a token that starts with a '>'.
822 // Outside C++11 and Objective-C, this is now error recovery.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000823 //
Richard Smithb5f81712018-04-30 05:25:48 +0000824 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
825 // extend that treatment to also apply to the '>>>' token.
826 //
827 // Objective-C allows this in its type parameter / argument lists.
828
829 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
830 SourceLocation TokLoc = Tok.getLocation();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000831 Token Next = NextToken();
Richard Smithb5f81712018-04-30 05:25:48 +0000832
833 // Whether splitting the current token after the '>' would undesirably result
834 // in the remaining token pasting with the token after it. This excludes the
835 // MergeWithNextToken cases, which we've already handled.
836 bool PreventMergeWithNextToken =
837 (RemainingToken == tok::greater ||
838 RemainingToken == tok::greatergreater) &&
839 (Next.isOneOf(tok::greater, tok::greatergreater,
840 tok::greatergreatergreater, tok::equal, tok::greaterequal,
841 tok::greatergreaterequal, tok::equalequal)) &&
842 areTokensAdjacent(Tok, Next);
843
844 // Diagnose this situation as appropriate.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000845 if (!ObjCGenericList) {
Richard Smithb5f81712018-04-30 05:25:48 +0000846 // The source range of the replaced token(s).
847 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
848 TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
849 getLangOpts()));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000850
Douglas Gregor85f3f952015-07-07 03:57:15 +0000851 // A hint to put a space between the '>>'s. In order to make the hint as
852 // clear as possible, we include the characters either side of the space in
853 // the replacement, rather than just inserting a space at SecondCharLoc.
854 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
855 ReplacementStr);
856
857 // A hint to put another space after the token, if it would otherwise be
858 // lexed differently.
859 FixItHint Hint2;
Richard Smithb5f81712018-04-30 05:25:48 +0000860 if (PreventMergeWithNextToken)
Douglas Gregor85f3f952015-07-07 03:57:15 +0000861 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
862
863 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
864 if (getLangOpts().CPlusPlus11 &&
865 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
866 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
867 else if (Tok.is(tok::greaterequal))
868 DiagId = diag::err_right_angle_bracket_equal_needs_space;
Richard Smithb5f81712018-04-30 05:25:48 +0000869 Diag(TokLoc, DiagId) << Hint1 << Hint2;
Douglas Gregor85f3f952015-07-07 03:57:15 +0000870 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000871
Richard Smithb5f81712018-04-30 05:25:48 +0000872 // Find the "length" of the resulting '>' token. This is not always 1, as it
873 // can contain escaped newlines.
874 unsigned GreaterLength = Lexer::getTokenPrefixLength(
875 TokLoc, 1, PP.getSourceManager(), getLangOpts());
876
877 // Annotate the source buffer to indicate that we split the token after the
878 // '>'. This allows us to properly find the end of, and extract the spelling
879 // of, the '>' token later.
880 RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
881
Faisal Vali6a79ca12013-06-08 19:39:00 +0000882 // Strip the initial '>' from the token.
Richard Smithb5f81712018-04-30 05:25:48 +0000883 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
884
885 Token Greater = Tok;
886 Greater.setLocation(RAngleLoc);
887 Greater.setKind(tok::greater);
888 Greater.setLength(GreaterLength);
889
890 unsigned OldLength = Tok.getLength();
891 if (MergeWithNextToken) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000892 ConsumeToken();
Richard Smithb5f81712018-04-30 05:25:48 +0000893 OldLength += Tok.getLength();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000894 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000895
Richard Smithb5f81712018-04-30 05:25:48 +0000896 Tok.setKind(RemainingToken);
897 Tok.setLength(OldLength - GreaterLength);
898
899 // Split the second token if lexing it normally would lex a different token
900 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
901 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
902 if (PreventMergeWithNextToken)
903 AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
904 Tok.setLocation(AfterGreaterLoc);
905
906 // Update the token cache to match what we just did if necessary.
907 if (CachingTokens) {
908 // If the previous cached token is being merged, delete it.
909 if (MergeWithNextToken)
910 PP.ReplacePreviousCachedToken({});
911
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +0000912 if (ConsumeLastToken)
Richard Smithb5f81712018-04-30 05:25:48 +0000913 PP.ReplacePreviousCachedToken({Greater, Tok});
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +0000914 else
Richard Smithb5f81712018-04-30 05:25:48 +0000915 PP.ReplacePreviousCachedToken({Greater});
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000916 }
917
Richard Smithb5f81712018-04-30 05:25:48 +0000918 if (ConsumeLastToken) {
919 PrevTokLocation = RAngleLoc;
920 } else {
921 PrevTokLocation = TokBeforeGreaterLoc;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000922 PP.EnterToken(Tok);
Richard Smithb5f81712018-04-30 05:25:48 +0000923 Tok = Greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000924 }
Richard Smithb5f81712018-04-30 05:25:48 +0000925
Faisal Vali6a79ca12013-06-08 19:39:00 +0000926 return false;
927}
928
929
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000930/// Parses a template-id that after the template name has
Faisal Vali6a79ca12013-06-08 19:39:00 +0000931/// already been parsed.
932///
933/// This routine takes care of parsing the enclosed template argument
934/// list ('<' template-parameter-list [opt] '>') and placing the
935/// results into a form that can be transferred to semantic analysis.
936///
Faisal Vali6a79ca12013-06-08 19:39:00 +0000937/// \param ConsumeLastToken if true, then we will consume the last
938/// token that forms the template-id. Otherwise, we will leave the
939/// last token in the stream (e.g., so that it can be replaced with an
940/// annotation token).
941bool
Richard Smith9a420f92017-05-10 21:47:30 +0000942Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000943 SourceLocation &LAngleLoc,
944 TemplateArgList &TemplateArgs,
945 SourceLocation &RAngleLoc) {
946 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
947
948 // Consume the '<'.
949 LAngleLoc = ConsumeToken();
950
951 // Parse the optional template-argument-list.
952 bool Invalid = false;
953 {
954 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Artem Belevich2eeb0482018-09-21 17:46:28 +0000955 if (!Tok.isOneOf(tok::greater, tok::greatergreater,
956 tok::greatergreatergreater, tok::greaterequal,
957 tok::greatergreaterequal))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000958 Invalid = ParseTemplateArgumentList(TemplateArgs);
959
960 if (Invalid) {
961 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000962 if (ConsumeLastToken)
963 SkipUntil(tok::greater, StopAtSemi);
964 else
965 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000966 return true;
967 }
968 }
969
Douglas Gregor85f3f952015-07-07 03:57:15 +0000970 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
971 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000972}
973
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000974/// Replace the tokens that form a simple-template-id with an
Faisal Vali6a79ca12013-06-08 19:39:00 +0000975/// annotation token containing the complete template-id.
976///
977/// The first token in the stream must be the name of a template that
978/// is followed by a '<'. This routine will parse the complete
979/// simple-template-id and replace the tokens with a single annotation
980/// token with one of two different kinds: if the template-id names a
981/// type (and \p AllowTypeAnnotation is true), the annotation token is
982/// a type annotation that includes the optional nested-name-specifier
983/// (\p SS). Otherwise, the annotation token is a template-id
984/// annotation that does not include the optional
985/// nested-name-specifier.
986///
987/// \param Template the declaration of the template named by the first
988/// token (an identifier), as returned from \c Action::isTemplateName().
989///
990/// \param TNK the kind of template that \p Template
991/// refers to, as returned from \c Action::isTemplateName().
992///
993/// \param SS if non-NULL, the nested-name-specifier that precedes
994/// this template name.
995///
996/// \param TemplateKWLoc if valid, specifies that this template-id
997/// annotation was preceded by the 'template' keyword and gives the
998/// location of that keyword. If invalid (the default), then this
999/// template-id was not preceded by a 'template' keyword.
1000///
1001/// \param AllowTypeAnnotation if true (the default), then a
1002/// simple-template-id that refers to a class template, template
1003/// template parameter, or other template that produces a type will be
1004/// replaced with a type annotation token. Otherwise, the
1005/// simple-template-id is always replaced with a template-id
1006/// annotation token.
1007///
1008/// If an unrecoverable parse error occurs and no annotation token can be
1009/// formed, this function returns true.
1010///
1011bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1012 CXXScopeSpec &SS,
1013 SourceLocation TemplateKWLoc,
1014 UnqualifiedId &TemplateName,
1015 bool AllowTypeAnnotation) {
1016 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1017 assert(Template && Tok.is(tok::less) &&
1018 "Parser isn't at the beginning of a template-id");
1019
1020 // Consume the template-name.
1021 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1022
1023 // Parse the enclosed template argument list.
1024 SourceLocation LAngleLoc, RAngleLoc;
1025 TemplateArgList TemplateArgs;
Richard Smith9a420f92017-05-10 21:47:30 +00001026 bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001027 TemplateArgs,
1028 RAngleLoc);
1029
1030 if (Invalid) {
1031 // If we failed to parse the template ID but skipped ahead to a >, we're not
1032 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001033 TryConsumeToken(tok::greater);
Richard Smithb23c5e82019-05-09 03:31:27 +00001034 // FIXME: Annotate the token stream so we don't produce the same errors
1035 // again if we're doing this annotation as part of a tentative parse.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001036 return true;
1037 }
1038
1039 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1040
1041 // Build the annotation token.
1042 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Richard Smith74f02342017-01-19 21:00:13 +00001043 TypeResult Type = Actions.ActOnTemplateIdType(
Richard Smithb23c5e82019-05-09 03:31:27 +00001044 getCurScope(), SS, TemplateKWLoc, Template, TemplateName.Identifier,
Richard Smith74f02342017-01-19 21:00:13 +00001045 TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001046 if (Type.isInvalid()) {
Richard Smith74f02342017-01-19 21:00:13 +00001047 // If we failed to parse the template ID but skipped ahead to a >, we're
1048 // not going to be able to form a token annotation. Eat the '>' if
1049 // present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001050 TryConsumeToken(tok::greater);
Richard Smithb23c5e82019-05-09 03:31:27 +00001051 // FIXME: Annotate the token stream so we don't produce the same errors
1052 // again if we're doing this annotation as part of a tentative parse.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001053 return true;
1054 }
1055
1056 Tok.setKind(tok::annot_typename);
1057 setTypeAnnotation(Tok, Type.get());
1058 if (SS.isNotEmpty())
1059 Tok.setLocation(SS.getBeginLoc());
1060 else if (TemplateKWLoc.isValid())
1061 Tok.setLocation(TemplateKWLoc);
1062 else
1063 Tok.setLocation(TemplateNameLoc);
1064 } else {
1065 // Build a template-id annotation token that can be processed
1066 // later.
1067 Tok.setKind(tok::annot_template_id);
Fangrui Song6907ce22018-07-30 19:24:48 +00001068
Faisal Vali43caf672017-05-23 01:07:12 +00001069 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00001070 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
Faisal Vali43caf672017-05-23 01:07:12 +00001071 ? TemplateName.Identifier
1072 : nullptr;
1073
1074 OverloadedOperatorKind OpKind =
Faisal Vali2ab8c152017-12-30 04:15:27 +00001075 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
Faisal Vali43caf672017-05-23 01:07:12 +00001076 ? OO_None
1077 : TemplateName.OperatorFunctionId.Operator;
1078
Dimitry Andrice4f5d012017-12-18 19:46:56 +00001079 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1080 SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
Faisal Vali43caf672017-05-23 01:07:12 +00001081 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
Fangrui Song6907ce22018-07-30 19:24:48 +00001082
Faisal Vali6a79ca12013-06-08 19:39:00 +00001083 Tok.setAnnotationValue(TemplateId);
1084 if (TemplateKWLoc.isValid())
1085 Tok.setLocation(TemplateKWLoc);
1086 else
1087 Tok.setLocation(TemplateNameLoc);
1088 }
1089
1090 // Common fields for the annotation token
1091 Tok.setAnnotationEndLoc(RAngleLoc);
1092
1093 // In case the tokens were cached, have Preprocessor replace them with the
1094 // annotation token.
1095 PP.AnnotateCachedTokens(Tok);
1096 return false;
1097}
1098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001099/// Replaces a template-id annotation token with a type
Faisal Vali6a79ca12013-06-08 19:39:00 +00001100/// annotation token.
1101///
1102/// If there was a failure when forming the type from the template-id,
1103/// a type annotation token will still be created, but will have a
1104/// NULL type pointer to signify an error.
Richard Smith62559bd2017-02-01 21:36:38 +00001105///
1106/// \param IsClassName Is this template-id appearing in a context where we
1107/// know it names a class, such as in an elaborated-type-specifier or
1108/// base-specifier? ('typename' and 'template' are unneeded and disallowed
1109/// in those contexts.)
1110void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001111 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1112
1113 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1114 assert((TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00001115 TemplateId->Kind == TNK_Dependent_template_name ||
1116 TemplateId->Kind == TNK_Undeclared_template) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001117 "Only works for type and dependent templates");
1118
1119 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1120 TemplateId->NumArgs);
1121
1122 TypeResult Type
Richard Smithb23c5e82019-05-09 03:31:27 +00001123 = Actions.ActOnTemplateIdType(getCurScope(),
1124 TemplateId->SS,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001125 TemplateId->TemplateKWLoc,
1126 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00001127 TemplateId->Name,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001128 TemplateId->TemplateNameLoc,
1129 TemplateId->LAngleLoc,
1130 TemplateArgsPtr,
Richard Smith62559bd2017-02-01 21:36:38 +00001131 TemplateId->RAngleLoc,
1132 /*IsCtorOrDtorName*/false,
1133 IsClassName);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001134 // Create the new "type" annotation token.
1135 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001136 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001137 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1138 Tok.setLocation(TemplateId->SS.getBeginLoc());
1139 // End location stays the same
1140
1141 // Replace the template-id annotation token, and possible the scope-specifier
1142 // that precedes it, with the typename annotation token.
1143 PP.AnnotateCachedTokens(Tok);
1144}
1145
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001146/// Determine whether the given token can end a template argument.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001147static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001148 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001149}
1150
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001151/// Parse a C++ template template argument.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001152ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1153 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1154 !Tok.is(tok::annot_cxxscope))
1155 return ParsedTemplateArgument();
1156
1157 // C++0x [temp.arg.template]p1:
1158 // A template-argument for a template template-parameter shall be the name
1159 // of a class template or an alias template, expressed as id-expression.
Fangrui Song6907ce22018-07-30 19:24:48 +00001160 //
Faisal Vali6a79ca12013-06-08 19:39:00 +00001161 // We parse an id-expression that refers to a class template or alias
1162 // template. The grammar we parse is:
1163 //
1164 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1165 //
Fangrui Song6907ce22018-07-30 19:24:48 +00001166 // followed by a token that terminates a template argument, such as ',',
Faisal Vali6a79ca12013-06-08 19:39:00 +00001167 // '>', or (in some cases) '>>'.
1168 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001169 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001170 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001171
Faisal Vali6a79ca12013-06-08 19:39:00 +00001172 ParsedTemplateArgument Result;
1173 SourceLocation EllipsisLoc;
1174 if (SS.isSet() && Tok.is(tok::kw_template)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001175 // Parse the optional 'template' keyword following the
Faisal Vali6a79ca12013-06-08 19:39:00 +00001176 // nested-name-specifier.
1177 SourceLocation TemplateKWLoc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00001178
Faisal Vali6a79ca12013-06-08 19:39:00 +00001179 if (Tok.is(tok::identifier)) {
1180 // We appear to have a dependent template name.
1181 UnqualifiedId Name;
1182 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1183 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001184
1185 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1186
Faisal Vali6a79ca12013-06-08 19:39:00 +00001187 // If the next token signals the end of a template argument,
1188 // then we have a dependent template name that could be a template
1189 // template argument.
1190 TemplateTy Template;
1191 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001192 Actions.ActOnDependentTemplateName(
1193 getCurScope(), SS, TemplateKWLoc, Name,
1194 /*ObjectType=*/nullptr,
1195 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001196 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1197 }
1198 } else if (Tok.is(tok::identifier)) {
1199 // We may have a (non-dependent) template name.
1200 TemplateTy Template;
1201 UnqualifiedId Name;
1202 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1203 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001204
1205 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001206
1207 if (isEndOfTemplateArgument(Tok)) {
1208 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001209 TemplateNameKind TNK = Actions.isTemplateName(
1210 getCurScope(), SS,
1211 /*hasTemplateKeyword=*/false, Name,
1212 /*ObjectType=*/nullptr,
1213 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001214 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1215 // We have an id-expression that refers to a class template or
Fangrui Song6907ce22018-07-30 19:24:48 +00001216 // (C++0x) alias template.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001217 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1218 }
1219 }
1220 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001221
Faisal Vali6a79ca12013-06-08 19:39:00 +00001222 // If this is a pack expansion, build it as such.
1223 if (EllipsisLoc.isValid() && !Result.isInvalid())
1224 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001225
Faisal Vali6a79ca12013-06-08 19:39:00 +00001226 return Result;
1227}
1228
1229/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1230///
1231/// template-argument: [C++ 14.2]
1232/// constant-expression
1233/// type-id
1234/// id-expression
1235ParsedTemplateArgument Parser::ParseTemplateArgument() {
1236 // C++ [temp.arg]p2:
1237 // In a template-argument, an ambiguity between a type-id and an
1238 // expression is resolved to a type-id, regardless of the form of
1239 // the corresponding template-parameter.
1240 //
Faisal Vali56f1de42017-05-20 19:58:04 +00001241 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1242 // up and annotate an identifier as an id-expression during disambiguation,
1243 // so enter the appropriate context for a constant expression template
1244 // argument before trying to disambiguate.
1245
1246 EnterExpressionEvaluationContext EnterConstantEvaluated(
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00001247 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1248 /*LambdaContextDecl=*/nullptr,
1249 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001250 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001251 TypeResult TypeArg = ParseTypeName(
Richard Smith77a9c602018-02-28 03:02:23 +00001252 /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
1253 return Actions.ActOnTemplateTypeArgument(TypeArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001254 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001255
Faisal Vali6a79ca12013-06-08 19:39:00 +00001256 // Try to parse a template template argument.
1257 {
1258 TentativeParsingAction TPA(*this);
1259
1260 ParsedTemplateArgument TemplateTemplateArgument
1261 = ParseTemplateTemplateArgument();
1262 if (!TemplateTemplateArgument.isInvalid()) {
1263 TPA.Commit();
1264 return TemplateTemplateArgument;
1265 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001266
Faisal Vali6a79ca12013-06-08 19:39:00 +00001267 // Revert this tentative parse to parse a non-type template argument.
1268 TPA.Revert();
1269 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001270
1271 // Parse a non-type template argument.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001272 SourceLocation Loc = Tok.getLocation();
Faisal Vali56f1de42017-05-20 19:58:04 +00001273 ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001274 if (ExprArg.isInvalid() || !ExprArg.get())
1275 return ParsedTemplateArgument();
1276
Fangrui Song6907ce22018-07-30 19:24:48 +00001277 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001278 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001279}
1280
Faisal Vali6a79ca12013-06-08 19:39:00 +00001281/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1282/// (C++ [temp.names]). Returns true if there was an error.
1283///
1284/// template-argument-list: [C++ 14.2]
1285/// template-argument
1286/// template-argument-list ',' template-argument
1287bool
1288Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001289
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001290 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001291
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001292 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001293 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001294 SourceLocation EllipsisLoc;
1295 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001296 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001297
1298 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001299 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001300 return true;
1301 }
1302
1303 // Save this template argument.
1304 TemplateArgs.push_back(Arg);
Fangrui Song6907ce22018-07-30 19:24:48 +00001305
Faisal Vali6a79ca12013-06-08 19:39:00 +00001306 // If the next token is a comma, consume it and keep reading
1307 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001308 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001309
1310 return false;
1311}
1312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001313/// Parse a C++ explicit template instantiation
Faisal Vali6a79ca12013-06-08 19:39:00 +00001314/// (C++ [temp.explicit]).
1315///
1316/// explicit-instantiation:
1317/// 'extern' [opt] 'template' declaration
1318///
1319/// Note that the 'extern' is a GNU extension and C++11 feature.
Faisal Vali421b2d12017-12-29 05:41:00 +00001320Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001321 SourceLocation ExternLoc,
1322 SourceLocation TemplateLoc,
1323 SourceLocation &DeclEnd,
Erich Keanec480f302018-07-12 21:09:05 +00001324 ParsedAttributes &AccessAttrs,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001325 AccessSpecifier AS) {
1326 // This isn't really required here.
1327 ParsingDeclRAIIObject
1328 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1329
Erich Keanec480f302018-07-12 21:09:05 +00001330 return ParseSingleDeclarationAfterTemplate(
1331 Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1332 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001333}
1334
1335SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1336 if (TemplateParams)
1337 return getTemplateParamsRange(TemplateParams->data(),
1338 TemplateParams->size());
1339
1340 SourceRange R(TemplateLoc);
1341 if (ExternLoc.isValid())
1342 R.setBegin(ExternLoc);
1343 return R;
1344}
1345
Richard Smithe40f2ba2013-08-07 21:41:30 +00001346void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1347 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001348}
1349
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001350/// Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001351void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001352 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001353 return;
1354
1355 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001356 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001357 // Track template parameter depth.
1358 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1359
1360 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001361 Sema::ContextRAII GlobalSavedContext(
1362 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001363
1364 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1365
Reid Kleckner229eee42018-11-27 21:20:42 +00001366 // Get the list of DeclContexts to reenter. For inline methods, we only want
1367 // to push the DeclContext of the outermost class. This matches the way the
1368 // parser normally parses bodies of inline methods when the outermost class is
1369 // complete.
1370 struct ContainingDC {
1371 ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1372 llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1373 DeclContext *getDC() { return Pair.getPointer(); }
1374 bool shouldPushDC() { return Pair.getInt(); }
1375 };
1376 SmallVector<ContainingDC, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001377 DeclContext *DD = FunD;
Reid Kleckner229eee42018-11-27 21:20:42 +00001378 DeclContext *NextContaining = Actions.getContainingDC(DD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001379 while (DD && !DD->isTranslationUnit()) {
Reid Kleckner229eee42018-11-27 21:20:42 +00001380 bool ShouldPush = DD == NextContaining;
1381 DeclContextsToReenter.push_back({DD, ShouldPush});
1382 if (ShouldPush)
1383 NextContaining = Actions.getContainingDC(DD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001384 DD = DD->getLexicalParent();
1385 }
1386
1387 // Reenter template scopes from outermost to innermost.
Reid Kleckner229eee42018-11-27 21:20:42 +00001388 for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
1389 TemplateParamScopeStack.push_back(
1390 new ParseScope(this, Scope::TemplateParamScope));
1391 unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
1392 getCurScope(), cast<Decl>(CDC.getDC()));
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001393 CurTemplateDepthTracker.addDepth(NumParamLists);
Reid Kleckner229eee42018-11-27 21:20:42 +00001394 if (CDC.shouldPushDC()) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001395 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
Reid Kleckner229eee42018-11-27 21:20:42 +00001396 Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001397 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001398 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001399
Richard Smithe40f2ba2013-08-07 21:41:30 +00001400 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001401
1402 // Append the current token at the end of the new token stream so that it
1403 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001404 LPT.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001405 PP.EnterTokenStream(LPT.Toks, true);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001406
1407 // Consume the previously pushed token.
1408 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001409 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1410 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001411
1412 // Parse the method body. Function body parsing code is similar enough
1413 // to be re-used for method bodies as well.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001414 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1415 Scope::CompoundStmtScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001416
1417 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001418 Sema::ContextRAII FunctionSavedContext(Actions,
1419 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001420
1421 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1422
1423 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001424 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001425 } else {
1426 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001427 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001428 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001429 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001430
1431 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001432 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1433 cast<FunctionTemplateDecl>(LPT.D)
1434 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001435 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001436 "TemplateParameterDepth should be greater than the depth of "
1437 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001438 ParseFunctionStatementBody(LPT.D, FnScope);
1439 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001440 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001441 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001442 }
1443
1444 // Exit scopes.
1445 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001446 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001447 TemplateParamScopeStack.rbegin();
1448 for (; I != TemplateParamScopeStack.rend(); ++I)
1449 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001450}
1451
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001452/// Lex a delayed template function for late parsing.
Faisal Vali6a79ca12013-06-08 19:39:00 +00001453void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1454 tok::TokenKind kind = Tok.getKind();
1455 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1456 // Consume everything up to (and including) the matching right brace.
1457 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1458 }
1459
1460 // If we're in a function-try-block, we need to store all the catch blocks.
1461 if (kind == tok::kw_try) {
1462 while (Tok.is(tok::kw_catch)) {
1463 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1464 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1465 }
1466 }
1467}
Richard Smithc2dead42018-06-27 01:32:04 +00001468
1469/// We've parsed something that could plausibly be intended to be a template
1470/// name (\p LHS) followed by a '<' token, and the following code can't possibly
1471/// be an expression. Determine if this is likely to be a template-id and if so,
1472/// diagnose it.
1473bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1474 TentativeParsingAction TPA(*this);
1475 // FIXME: We could look at the token sequence in a lot more detail here.
1476 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1477 StopAtSemi | StopBeforeMatch)) {
1478 TPA.Commit();
1479
1480 SourceLocation Greater;
1481 ParseGreaterThanInTemplateList(Greater, true, false);
1482 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1483 Less, Greater);
1484 return true;
1485 }
1486
1487 // There's no matching '>' token, this probably isn't supposed to be
1488 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1489 TPA.Revert();
1490 return false;
1491}
1492
1493void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1494 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1495
1496 bool DependentTemplateName = false;
1497 if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1498 DependentTemplateName))
1499 return;
1500
1501 // OK, this might be a name that the user intended to be parsed as a
1502 // template-name, followed by a '<' token. Check for some easy cases.
1503
1504 // If we have potential_template<>, then it's supposed to be a template-name.
1505 if (NextToken().is(tok::greater) ||
1506 (getLangOpts().CPlusPlus11 &&
1507 NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1508 SourceLocation Less = ConsumeToken();
1509 SourceLocation Greater;
1510 ParseGreaterThanInTemplateList(Greater, true, false);
1511 Actions.diagnoseExprIntendedAsTemplateName(
1512 getCurScope(), PotentialTemplateName, Less, Greater);
1513 // FIXME: Perform error recovery.
1514 PotentialTemplateName = ExprError();
1515 return;
1516 }
1517
1518 // If we have 'potential_template<type-id', assume it's supposed to be a
1519 // template-name if there's a matching '>' later on.
1520 {
1521 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1522 TentativeParsingAction TPA(*this);
1523 SourceLocation Less = ConsumeToken();
1524 if (isTypeIdUnambiguously() &&
1525 diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1526 TPA.Commit();
1527 // FIXME: Perform error recovery.
1528 PotentialTemplateName = ExprError();
1529 return;
1530 }
1531 TPA.Revert();
1532 }
1533
1534 // Otherwise, remember that we saw this in case we see a potentially-matching
1535 // '>' token later on.
1536 AngleBracketTracker::Priority Priority =
1537 (DependentTemplateName ? AngleBracketTracker::DependentName
1538 : AngleBracketTracker::PotentialTypo) |
1539 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1540 : AngleBracketTracker::NoSpaceBeforeLess);
1541 AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1542 Priority);
1543}
1544
1545bool Parser::checkPotentialAngleBracketDelimiter(
1546 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1547 // If a comma in an expression context is followed by a type that can be a
1548 // template argument and cannot be an expression, then this is ill-formed,
1549 // but might be intended to be part of a template-id.
1550 if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1551 diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1552 AngleBrackets.clear(*this);
1553 return true;
1554 }
1555
1556 // If a context that looks like a template-id is followed by '()', then
1557 // this is ill-formed, but might be intended to be a template-id
1558 // followed by '()'.
1559 if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1560 NextToken().is(tok::r_paren)) {
1561 Actions.diagnoseExprIntendedAsTemplateName(
1562 getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1563 OpToken.getLocation());
1564 AngleBrackets.clear(*this);
1565 return true;
1566 }
1567
1568 // After a '>' (etc), we're no longer potentially in a construct that's
1569 // intended to be treated as a template-id.
1570 if (OpToken.is(tok::greater) ||
1571 (getLangOpts().CPlusPlus11 &&
1572 OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1573 AngleBrackets.clear(*this);
1574 return false;
1575}