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