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