Bug Summary

File:build/source/clang/lib/Parse/ParseTemplate.cpp
Warning:line 1740, column 51
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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