Bug Summary

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