1 | //===--- ParseExprCXX.cpp - C++ Expression 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 the Expression parsing implementation for C++. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | #include "clang/AST/ASTContext.h" |
13 | #include "clang/AST/Decl.h" |
14 | #include "clang/AST/DeclTemplate.h" |
15 | #include "clang/AST/ExprCXX.h" |
16 | #include "clang/Basic/DiagnosticParse.h" |
17 | #include "clang/Basic/PrettyStackTrace.h" |
18 | #include "clang/Basic/TemplateKinds.h" |
19 | #include "clang/Basic/TokenKinds.h" |
20 | #include "clang/Lex/LiteralSupport.h" |
21 | #include "clang/Parse/Parser.h" |
22 | #include "clang/Parse/RAIIObjectsForParser.h" |
23 | #include "clang/Sema/DeclSpec.h" |
24 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
25 | #include "clang/Sema/ParsedTemplate.h" |
26 | #include "clang/Sema/Scope.h" |
27 | #include "clang/Sema/SemaCodeCompletion.h" |
28 | #include "llvm/Support/Compiler.h" |
29 | #include "llvm/Support/ErrorHandling.h" |
30 | #include <numeric> |
31 | |
32 | using namespace clang; |
33 | |
34 | static int SelectDigraphErrorMessage(tok::TokenKind Kind) { |
35 | switch (Kind) { |
36 | // template name |
37 | case tok::unknown: return 0; |
38 | // casts |
39 | case tok::kw_addrspace_cast: return 1; |
40 | case tok::kw_const_cast: return 2; |
41 | case tok::kw_dynamic_cast: return 3; |
42 | case tok::kw_reinterpret_cast: return 4; |
43 | case tok::kw_static_cast: return 5; |
44 | default: |
45 | llvm_unreachable("Unknown type for digraph error message." ); |
46 | } |
47 | } |
48 | |
49 | bool Parser::areTokensAdjacent(const Token &First, const Token &Second) { |
50 | SourceManager &SM = PP.getSourceManager(); |
51 | SourceLocation FirstLoc = SM.getSpellingLoc(Loc: First.getLocation()); |
52 | SourceLocation FirstEnd = FirstLoc.getLocWithOffset(Offset: First.getLength()); |
53 | return FirstEnd == SM.getSpellingLoc(Loc: Second.getLocation()); |
54 | } |
55 | |
56 | // Suggest fixit for "<::" after a cast. |
57 | static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, |
58 | Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) { |
59 | // Pull '<:' and ':' off token stream. |
60 | if (!AtDigraph) |
61 | PP.Lex(Result&: DigraphToken); |
62 | PP.Lex(Result&: ColonToken); |
63 | |
64 | SourceRange Range; |
65 | Range.setBegin(DigraphToken.getLocation()); |
66 | Range.setEnd(ColonToken.getLocation()); |
67 | P.Diag(Loc: DigraphToken.getLocation(), DiagID: diag::err_missing_whitespace_digraph) |
68 | << SelectDigraphErrorMessage(Kind) |
69 | << FixItHint::CreateReplacement(RemoveRange: Range, Code: "< ::" ); |
70 | |
71 | // Update token information to reflect their change in token type. |
72 | ColonToken.setKind(tok::coloncolon); |
73 | ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(Offset: -1)); |
74 | ColonToken.setLength(2); |
75 | DigraphToken.setKind(tok::less); |
76 | DigraphToken.setLength(1); |
77 | |
78 | // Push new tokens back to token stream. |
79 | PP.EnterToken(Tok: ColonToken, /*IsReinject*/ true); |
80 | if (!AtDigraph) |
81 | PP.EnterToken(Tok: DigraphToken, /*IsReinject*/ true); |
82 | } |
83 | |
84 | void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType, |
85 | bool EnteringContext, |
86 | IdentifierInfo &II, CXXScopeSpec &SS) { |
87 | if (!Next.is(K: tok::l_square) || Next.getLength() != 2) |
88 | return; |
89 | |
90 | Token SecondToken = GetLookAheadToken(N: 2); |
91 | if (!SecondToken.is(K: tok::colon) || !areTokensAdjacent(First: Next, Second: SecondToken)) |
92 | return; |
93 | |
94 | TemplateTy Template; |
95 | UnqualifiedId TemplateName; |
96 | TemplateName.setIdentifier(Id: &II, IdLoc: Tok.getLocation()); |
97 | bool MemberOfUnknownSpecialization; |
98 | if (!Actions.isTemplateName(S: getCurScope(), SS, /*hasTemplateKeyword=*/false, |
99 | Name: TemplateName, ObjectType, EnteringContext, |
100 | Template, MemberOfUnknownSpecialization)) |
101 | return; |
102 | |
103 | FixDigraph(P&: *this, PP, DigraphToken&: Next, ColonToken&: SecondToken, Kind: tok::unknown, |
104 | /*AtDigraph*/false); |
105 | } |
106 | |
107 | bool Parser::ParseOptionalCXXScopeSpecifier( |
108 | CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, |
109 | bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename, |
110 | const IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration, |
111 | bool Disambiguation) { |
112 | assert(getLangOpts().CPlusPlus && |
113 | "Call sites of this function should be guarded by checking for C++" ); |
114 | |
115 | if (Tok.is(K: tok::annot_cxxscope)) { |
116 | assert(!LastII && "want last identifier but have already annotated scope" ); |
117 | assert(!MayBePseudoDestructor && "unexpected annot_cxxscope" ); |
118 | Actions.RestoreNestedNameSpecifierAnnotation(Annotation: Tok.getAnnotationValue(), |
119 | AnnotationRange: Tok.getAnnotationRange(), |
120 | SS); |
121 | ConsumeAnnotationToken(); |
122 | return false; |
123 | } |
124 | |
125 | // Has to happen before any "return false"s in this function. |
126 | bool CheckForDestructor = false; |
127 | if (MayBePseudoDestructor && *MayBePseudoDestructor) { |
128 | CheckForDestructor = true; |
129 | *MayBePseudoDestructor = false; |
130 | } |
131 | |
132 | if (LastII) |
133 | *LastII = nullptr; |
134 | |
135 | bool HasScopeSpecifier = false; |
136 | |
137 | if (Tok.is(K: tok::coloncolon)) { |
138 | // ::new and ::delete aren't nested-name-specifiers. |
139 | tok::TokenKind NextKind = NextToken().getKind(); |
140 | if (NextKind == tok::kw_new || NextKind == tok::kw_delete) |
141 | return false; |
142 | |
143 | if (NextKind == tok::l_brace) { |
144 | // It is invalid to have :: {, consume the scope qualifier and pretend |
145 | // like we never saw it. |
146 | Diag(Loc: ConsumeToken(), DiagID: diag::err_expected) << tok::identifier; |
147 | } else { |
148 | // '::' - Global scope qualifier. |
149 | if (Actions.ActOnCXXGlobalScopeSpecifier(CCLoc: ConsumeToken(), SS)) |
150 | return true; |
151 | |
152 | HasScopeSpecifier = true; |
153 | } |
154 | } |
155 | |
156 | if (Tok.is(K: tok::kw___super)) { |
157 | SourceLocation SuperLoc = ConsumeToken(); |
158 | if (!Tok.is(K: tok::coloncolon)) { |
159 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_coloncolon_after_super); |
160 | return true; |
161 | } |
162 | |
163 | return Actions.ActOnSuperScopeSpecifier(SuperLoc, ColonColonLoc: ConsumeToken(), SS); |
164 | } |
165 | |
166 | if (!HasScopeSpecifier && |
167 | Tok.isOneOf(Ks: tok::kw_decltype, Ks: tok::annot_decltype)) { |
168 | DeclSpec DS(AttrFactory); |
169 | SourceLocation DeclLoc = Tok.getLocation(); |
170 | SourceLocation EndLoc = ParseDecltypeSpecifier(DS); |
171 | |
172 | SourceLocation CCLoc; |
173 | // Work around a standard defect: 'decltype(auto)::' is not a |
174 | // nested-name-specifier. |
175 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto || |
176 | !TryConsumeToken(Expected: tok::coloncolon, Loc&: CCLoc)) { |
177 | AnnotateExistingDecltypeSpecifier(DS, StartLoc: DeclLoc, EndLoc); |
178 | return false; |
179 | } |
180 | |
181 | if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, ColonColonLoc: CCLoc)) |
182 | SS.SetInvalid(SourceRange(DeclLoc, CCLoc)); |
183 | |
184 | HasScopeSpecifier = true; |
185 | } |
186 | |
187 | else if (!HasScopeSpecifier && Tok.is(K: tok::identifier) && |
188 | GetLookAheadToken(N: 1).is(K: tok::ellipsis) && |
189 | GetLookAheadToken(N: 2).is(K: tok::l_square) && |
190 | !GetLookAheadToken(N: 3).is(K: tok::r_square)) { |
191 | SourceLocation Start = Tok.getLocation(); |
192 | DeclSpec DS(AttrFactory); |
193 | SourceLocation CCLoc; |
194 | SourceLocation EndLoc = ParsePackIndexingType(DS); |
195 | if (DS.getTypeSpecType() == DeclSpec::TST_error) |
196 | return false; |
197 | |
198 | QualType Type = Actions.ActOnPackIndexingType( |
199 | Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(), Loc: DS.getBeginLoc(), |
200 | EllipsisLoc: DS.getEllipsisLoc()); |
201 | |
202 | if (Type.isNull()) |
203 | return false; |
204 | |
205 | // C++ [cpp23.dcl.dcl-2]: |
206 | // Previously, T...[n] would declare a pack of function parameters. |
207 | // T...[n] is now a pack-index-specifier. [...] Valid C++ 2023 code that |
208 | // declares a pack of parameters without specifying a declarator-id |
209 | // becomes ill-formed. |
210 | // |
211 | // However, we still treat it as a pack indexing type because the use case |
212 | // is fairly rare, to ensure semantic consistency given that we have |
213 | // backported this feature to pre-C++26 modes. |
214 | if (!Tok.is(K: tok::coloncolon) && !getLangOpts().CPlusPlus26 && |
215 | getCurScope()->isFunctionDeclarationScope()) |
216 | Diag(Loc: Start, DiagID: diag::warn_pre_cxx26_ambiguous_pack_indexing_type) << Type; |
217 | |
218 | if (!TryConsumeToken(Expected: tok::coloncolon, Loc&: CCLoc)) { |
219 | AnnotateExistingIndexedTypeNamePack(T: ParsedType::make(P: Type), StartLoc: Start, |
220 | EndLoc); |
221 | return false; |
222 | } |
223 | if (Actions.ActOnCXXNestedNameSpecifierIndexedPack(SS, DS, ColonColonLoc: CCLoc, |
224 | Type: std::move(Type))) |
225 | SS.SetInvalid(SourceRange(Start, CCLoc)); |
226 | HasScopeSpecifier = true; |
227 | } |
228 | |
229 | // Preferred type might change when parsing qualifiers, we need the original. |
230 | auto SavedType = PreferredType; |
231 | while (true) { |
232 | if (HasScopeSpecifier) { |
233 | if (Tok.is(K: tok::code_completion)) { |
234 | cutOffParsing(); |
235 | // Code completion for a nested-name-specifier, where the code |
236 | // completion token follows the '::'. |
237 | Actions.CodeCompletion().CodeCompleteQualifiedId( |
238 | S: getCurScope(), SS, EnteringContext, IsUsingDeclaration: InUsingDeclaration, |
239 | BaseType: ObjectType.get(), PreferredType: SavedType.get(Tok: SS.getBeginLoc())); |
240 | // Include code completion token into the range of the scope otherwise |
241 | // when we try to annotate the scope tokens the dangling code completion |
242 | // token will cause assertion in |
243 | // Preprocessor::AnnotatePreviousCachedTokens. |
244 | SS.setEndLoc(Tok.getLocation()); |
245 | return true; |
246 | } |
247 | |
248 | // C++ [basic.lookup.classref]p5: |
249 | // If the qualified-id has the form |
250 | // |
251 | // ::class-name-or-namespace-name::... |
252 | // |
253 | // the class-name-or-namespace-name is looked up in global scope as a |
254 | // class-name or namespace-name. |
255 | // |
256 | // To implement this, we clear out the object type as soon as we've |
257 | // seen a leading '::' or part of a nested-name-specifier. |
258 | ObjectType = nullptr; |
259 | } |
260 | |
261 | // nested-name-specifier: |
262 | // nested-name-specifier 'template'[opt] simple-template-id '::' |
263 | |
264 | // Parse the optional 'template' keyword, then make sure we have |
265 | // 'identifier <' after it. |
266 | if (Tok.is(K: tok::kw_template)) { |
267 | // If we don't have a scope specifier or an object type, this isn't a |
268 | // nested-name-specifier, since they aren't allowed to start with |
269 | // 'template'. |
270 | if (!HasScopeSpecifier && !ObjectType) |
271 | break; |
272 | |
273 | TentativeParsingAction TPA(*this); |
274 | SourceLocation TemplateKWLoc = ConsumeToken(); |
275 | |
276 | UnqualifiedId TemplateName; |
277 | if (Tok.is(K: tok::identifier)) { |
278 | // Consume the identifier. |
279 | TemplateName.setIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation()); |
280 | ConsumeToken(); |
281 | } else if (Tok.is(K: tok::kw_operator)) { |
282 | // We don't need to actually parse the unqualified-id in this case, |
283 | // because a simple-template-id cannot start with 'operator', but |
284 | // go ahead and parse it anyway for consistency with the case where |
285 | // we already annotated the template-id. |
286 | if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, |
287 | Result&: TemplateName)) { |
288 | TPA.Commit(); |
289 | break; |
290 | } |
291 | |
292 | if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId && |
293 | TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) { |
294 | Diag(Loc: TemplateName.getSourceRange().getBegin(), |
295 | DiagID: diag::err_id_after_template_in_nested_name_spec) |
296 | << TemplateName.getSourceRange(); |
297 | TPA.Commit(); |
298 | break; |
299 | } |
300 | } else { |
301 | TPA.Revert(); |
302 | break; |
303 | } |
304 | |
305 | // If the next token is not '<', we have a qualified-id that refers |
306 | // to a template name, such as T::template apply, but is not a |
307 | // template-id. |
308 | if (Tok.isNot(K: tok::less)) { |
309 | TPA.Revert(); |
310 | break; |
311 | } |
312 | |
313 | // Commit to parsing the template-id. |
314 | TPA.Commit(); |
315 | TemplateTy Template; |
316 | TemplateNameKind TNK = Actions.ActOnTemplateName( |
317 | S: getCurScope(), SS, TemplateKWLoc, Name: TemplateName, ObjectType, |
318 | EnteringContext, Template, /*AllowInjectedClassName*/ true); |
319 | if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc, |
320 | TemplateName, AllowTypeAnnotation: false)) |
321 | return true; |
322 | |
323 | continue; |
324 | } |
325 | |
326 | if (Tok.is(K: tok::annot_template_id) && NextToken().is(K: tok::coloncolon)) { |
327 | // We have |
328 | // |
329 | // template-id '::' |
330 | // |
331 | // So we need to check whether the template-id is a simple-template-id of |
332 | // the right kind (it should name a type or be dependent), and then |
333 | // convert it into a type within the nested-name-specifier. |
334 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok); |
335 | if (CheckForDestructor && GetLookAheadToken(N: 2).is(K: tok::tilde)) { |
336 | *MayBePseudoDestructor = true; |
337 | return false; |
338 | } |
339 | |
340 | if (LastII) |
341 | *LastII = TemplateId->Name; |
342 | |
343 | // Consume the template-id token. |
344 | ConsumeAnnotationToken(); |
345 | |
346 | assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!" ); |
347 | SourceLocation CCLoc = ConsumeToken(); |
348 | |
349 | HasScopeSpecifier = true; |
350 | |
351 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
352 | TemplateId->NumArgs); |
353 | |
354 | if (TemplateId->isInvalid() || |
355 | Actions.ActOnCXXNestedNameSpecifier(S: getCurScope(), |
356 | SS, |
357 | TemplateKWLoc: TemplateId->TemplateKWLoc, |
358 | TemplateName: TemplateId->Template, |
359 | TemplateNameLoc: TemplateId->TemplateNameLoc, |
360 | LAngleLoc: TemplateId->LAngleLoc, |
361 | TemplateArgs: TemplateArgsPtr, |
362 | RAngleLoc: TemplateId->RAngleLoc, |
363 | CCLoc, |
364 | EnteringContext)) { |
365 | SourceLocation StartLoc |
366 | = SS.getBeginLoc().isValid()? SS.getBeginLoc() |
367 | : TemplateId->TemplateNameLoc; |
368 | SS.SetInvalid(SourceRange(StartLoc, CCLoc)); |
369 | } |
370 | |
371 | continue; |
372 | } |
373 | |
374 | switch (Tok.getKind()) { |
375 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: |
376 | #include "clang/Basic/TransformTypeTraits.def" |
377 | if (!NextToken().is(K: tok::l_paren)) { |
378 | Tok.setKind(tok::identifier); |
379 | Diag(Tok, DiagID: diag::ext_keyword_as_ident) |
380 | << Tok.getIdentifierInfo()->getName() << 0; |
381 | continue; |
382 | } |
383 | [[fallthrough]]; |
384 | default: |
385 | break; |
386 | } |
387 | |
388 | // The rest of the nested-name-specifier possibilities start with |
389 | // tok::identifier. |
390 | if (Tok.isNot(K: tok::identifier)) |
391 | break; |
392 | |
393 | IdentifierInfo &II = *Tok.getIdentifierInfo(); |
394 | |
395 | // nested-name-specifier: |
396 | // type-name '::' |
397 | // namespace-name '::' |
398 | // nested-name-specifier identifier '::' |
399 | Token Next = NextToken(); |
400 | Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(), |
401 | ObjectType); |
402 | |
403 | // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover |
404 | // and emit a fixit hint for it. |
405 | if (Next.is(K: tok::colon) && !ColonIsSacred) { |
406 | if (Actions.IsInvalidUnlessNestedName(S: getCurScope(), SS, IdInfo, |
407 | EnteringContext) && |
408 | // If the token after the colon isn't an identifier, it's still an |
409 | // error, but they probably meant something else strange so don't |
410 | // recover like this. |
411 | PP.LookAhead(N: 1).is(K: tok::identifier)) { |
412 | Diag(Tok: Next, DiagID: diag::err_unexpected_colon_in_nested_name_spec) |
413 | << FixItHint::CreateReplacement(RemoveRange: Next.getLocation(), Code: "::" ); |
414 | // Recover as if the user wrote '::'. |
415 | Next.setKind(tok::coloncolon); |
416 | } |
417 | } |
418 | |
419 | if (Next.is(K: tok::coloncolon) && GetLookAheadToken(N: 2).is(K: tok::l_brace)) { |
420 | // It is invalid to have :: {, consume the scope qualifier and pretend |
421 | // like we never saw it. |
422 | Token Identifier = Tok; // Stash away the identifier. |
423 | ConsumeToken(); // Eat the identifier, current token is now '::'. |
424 | ConsumeToken(); |
425 | Diag(Loc: getEndOfPreviousToken(), DiagID: diag::err_expected) << tok::identifier; |
426 | UnconsumeToken(Consumed&: Identifier); // Stick the identifier back. |
427 | Next = NextToken(); // Point Next at the '{' token. |
428 | } |
429 | |
430 | if (Next.is(K: tok::coloncolon)) { |
431 | if (CheckForDestructor && GetLookAheadToken(N: 2).is(K: tok::tilde)) { |
432 | *MayBePseudoDestructor = true; |
433 | return false; |
434 | } |
435 | |
436 | if (ColonIsSacred) { |
437 | const Token &Next2 = GetLookAheadToken(N: 2); |
438 | if (Next2.is(K: tok::kw_private) || Next2.is(K: tok::kw_protected) || |
439 | Next2.is(K: tok::kw_public) || Next2.is(K: tok::kw_virtual)) { |
440 | Diag(Tok: Next2, DiagID: diag::err_unexpected_token_in_nested_name_spec) |
441 | << Next2.getName() |
442 | << FixItHint::CreateReplacement(RemoveRange: Next.getLocation(), Code: ":" ); |
443 | Token ColonColon; |
444 | PP.Lex(Result&: ColonColon); |
445 | ColonColon.setKind(tok::colon); |
446 | PP.EnterToken(Tok: ColonColon, /*IsReinject*/ true); |
447 | break; |
448 | } |
449 | } |
450 | |
451 | if (LastII) |
452 | *LastII = &II; |
453 | |
454 | // We have an identifier followed by a '::'. Lookup this name |
455 | // as the name in a nested-name-specifier. |
456 | Token Identifier = Tok; |
457 | SourceLocation IdLoc = ConsumeToken(); |
458 | assert(Tok.isOneOf(tok::coloncolon, tok::colon) && |
459 | "NextToken() not working properly!" ); |
460 | Token ColonColon = Tok; |
461 | SourceLocation CCLoc = ConsumeToken(); |
462 | |
463 | bool IsCorrectedToColon = false; |
464 | bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr; |
465 | if (Actions.ActOnCXXNestedNameSpecifier( |
466 | S: getCurScope(), IdInfo, EnteringContext, SS, IsCorrectedToColon: CorrectionFlagPtr, |
467 | OnlyNamespace)) { |
468 | // Identifier is not recognized as a nested name, but we can have |
469 | // mistyped '::' instead of ':'. |
470 | if (CorrectionFlagPtr && IsCorrectedToColon) { |
471 | ColonColon.setKind(tok::colon); |
472 | PP.EnterToken(Tok, /*IsReinject*/ true); |
473 | PP.EnterToken(Tok: ColonColon, /*IsReinject*/ true); |
474 | Tok = Identifier; |
475 | break; |
476 | } |
477 | SS.SetInvalid(SourceRange(IdLoc, CCLoc)); |
478 | } |
479 | HasScopeSpecifier = true; |
480 | continue; |
481 | } |
482 | |
483 | CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS); |
484 | |
485 | // nested-name-specifier: |
486 | // type-name '<' |
487 | if (Next.is(K: tok::less)) { |
488 | |
489 | TemplateTy Template; |
490 | UnqualifiedId TemplateName; |
491 | TemplateName.setIdentifier(Id: &II, IdLoc: Tok.getLocation()); |
492 | bool MemberOfUnknownSpecialization; |
493 | if (TemplateNameKind TNK = Actions.isTemplateName( |
494 | S: getCurScope(), SS, |
495 | /*hasTemplateKeyword=*/false, Name: TemplateName, ObjectType, |
496 | EnteringContext, Template, MemberOfUnknownSpecialization, |
497 | Disambiguation)) { |
498 | // If lookup didn't find anything, we treat the name as a template-name |
499 | // anyway. C++20 requires this, and in prior language modes it improves |
500 | // error recovery. But before we commit to this, check that we actually |
501 | // have something that looks like a template-argument-list next. |
502 | if (!IsTypename && TNK == TNK_Undeclared_template && |
503 | isTemplateArgumentList(TokensToSkip: 1) == TPResult::False) |
504 | break; |
505 | |
506 | // We have found a template name, so annotate this token |
507 | // with a template-id annotation. We do not permit the |
508 | // template-id to be translated into a type annotation, |
509 | // because some clients (e.g., the parsing of class template |
510 | // specializations) still want to see the original template-id |
511 | // token, and it might not be a type at all (e.g. a concept name in a |
512 | // type-constraint). |
513 | ConsumeToken(); |
514 | if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc: SourceLocation(), |
515 | TemplateName, AllowTypeAnnotation: false)) |
516 | return true; |
517 | continue; |
518 | } |
519 | |
520 | if (MemberOfUnknownSpecialization && !Disambiguation && |
521 | (ObjectType || SS.isSet()) && |
522 | (IsTypename || isTemplateArgumentList(TokensToSkip: 1) == TPResult::True)) { |
523 | // If we had errors before, ObjectType can be dependent even without any |
524 | // templates. Do not report missing template keyword in that case. |
525 | if (!ObjectHadErrors) { |
526 | // We have something like t::getAs<T>, where getAs is a |
527 | // member of an unknown specialization. However, this will only |
528 | // parse correctly as a template, so suggest the keyword 'template' |
529 | // before 'getAs' and treat this as a dependent template name. |
530 | unsigned DiagID = diag::err_missing_dependent_template_keyword; |
531 | if (getLangOpts().MicrosoftExt) |
532 | DiagID = diag::warn_missing_dependent_template_keyword; |
533 | |
534 | Diag(Loc: Tok.getLocation(), DiagID) |
535 | << II.getName() |
536 | << FixItHint::CreateInsertion(InsertionLoc: Tok.getLocation(), Code: "template " ); |
537 | } |
538 | ConsumeToken(); |
539 | |
540 | TemplateNameKind TNK = Actions.ActOnTemplateName( |
541 | S: getCurScope(), SS, /*TemplateKWLoc=*/SourceLocation(), Name: TemplateName, |
542 | ObjectType, EnteringContext, Template, |
543 | /*AllowInjectedClassName=*/true); |
544 | if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc: SourceLocation(), |
545 | TemplateName, AllowTypeAnnotation: false)) |
546 | return true; |
547 | |
548 | continue; |
549 | } |
550 | } |
551 | |
552 | // We don't have any tokens that form the beginning of a |
553 | // nested-name-specifier, so we're done. |
554 | break; |
555 | } |
556 | |
557 | // Even if we didn't see any pieces of a nested-name-specifier, we |
558 | // still check whether there is a tilde in this position, which |
559 | // indicates a potential pseudo-destructor. |
560 | if (CheckForDestructor && !HasScopeSpecifier && Tok.is(K: tok::tilde)) |
561 | *MayBePseudoDestructor = true; |
562 | |
563 | return false; |
564 | } |
565 | |
566 | ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, |
567 | bool isAddressOfOperand, |
568 | Token &Replacement) { |
569 | ExprResult E; |
570 | |
571 | // We may have already annotated this id-expression. |
572 | switch (Tok.getKind()) { |
573 | case tok::annot_non_type: { |
574 | NamedDecl *ND = getNonTypeAnnotation(Tok); |
575 | SourceLocation Loc = ConsumeAnnotationToken(); |
576 | E = Actions.ActOnNameClassifiedAsNonType(S: getCurScope(), SS, Found: ND, NameLoc: Loc, NextToken: Tok); |
577 | break; |
578 | } |
579 | |
580 | case tok::annot_non_type_dependent: { |
581 | IdentifierInfo *II = getIdentifierAnnotation(Tok); |
582 | SourceLocation Loc = ConsumeAnnotationToken(); |
583 | |
584 | // This is only the direct operand of an & operator if it is not |
585 | // followed by a postfix-expression suffix. |
586 | if (isAddressOfOperand && isPostfixExpressionSuffixStart()) |
587 | isAddressOfOperand = false; |
588 | |
589 | E = Actions.ActOnNameClassifiedAsDependentNonType(SS, Name: II, NameLoc: Loc, |
590 | IsAddressOfOperand: isAddressOfOperand); |
591 | break; |
592 | } |
593 | |
594 | case tok::annot_non_type_undeclared: { |
595 | assert(SS.isEmpty() && |
596 | "undeclared non-type annotation should be unqualified" ); |
597 | IdentifierInfo *II = getIdentifierAnnotation(Tok); |
598 | SourceLocation Loc = ConsumeAnnotationToken(); |
599 | E = Actions.ActOnNameClassifiedAsUndeclaredNonType(Name: II, NameLoc: Loc); |
600 | break; |
601 | } |
602 | |
603 | default: |
604 | SourceLocation TemplateKWLoc; |
605 | UnqualifiedId Name; |
606 | if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr, |
607 | /*ObjectHadErrors=*/false, |
608 | /*EnteringContext=*/false, |
609 | /*AllowDestructorName=*/false, |
610 | /*AllowConstructorName=*/false, |
611 | /*AllowDeductionGuide=*/false, TemplateKWLoc: &TemplateKWLoc, Result&: Name)) |
612 | return ExprError(); |
613 | |
614 | // This is only the direct operand of an & operator if it is not |
615 | // followed by a postfix-expression suffix. |
616 | if (isAddressOfOperand && isPostfixExpressionSuffixStart()) |
617 | isAddressOfOperand = false; |
618 | |
619 | E = Actions.ActOnIdExpression( |
620 | S: getCurScope(), SS, TemplateKWLoc, Id&: Name, HasTrailingLParen: Tok.is(K: tok::l_paren), |
621 | IsAddressOfOperand: isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false, |
622 | KeywordReplacement: &Replacement); |
623 | break; |
624 | } |
625 | |
626 | // Might be a pack index expression! |
627 | E = tryParseCXXPackIndexingExpression(PackIdExpression: E); |
628 | |
629 | if (!E.isInvalid() && !E.isUnset() && Tok.is(K: tok::less)) |
630 | checkPotentialAngleBracket(PotentialTemplateName&: E); |
631 | return E; |
632 | } |
633 | |
634 | ExprResult Parser::ParseCXXPackIndexingExpression(ExprResult PackIdExpression) { |
635 | assert(Tok.is(tok::ellipsis) && NextToken().is(tok::l_square) && |
636 | "expected ...[" ); |
637 | SourceLocation EllipsisLoc = ConsumeToken(); |
638 | BalancedDelimiterTracker T(*this, tok::l_square); |
639 | T.consumeOpen(); |
640 | ExprResult IndexExpr = ParseConstantExpression(); |
641 | if (T.consumeClose() || IndexExpr.isInvalid()) |
642 | return ExprError(); |
643 | return Actions.ActOnPackIndexingExpr(S: getCurScope(), PackExpression: PackIdExpression.get(), |
644 | EllipsisLoc, LSquareLoc: T.getOpenLocation(), |
645 | IndexExpr: IndexExpr.get(), RSquareLoc: T.getCloseLocation()); |
646 | } |
647 | |
648 | ExprResult |
649 | Parser::tryParseCXXPackIndexingExpression(ExprResult PackIdExpression) { |
650 | ExprResult E = PackIdExpression; |
651 | if (!PackIdExpression.isInvalid() && !PackIdExpression.isUnset() && |
652 | Tok.is(K: tok::ellipsis) && NextToken().is(K: tok::l_square)) { |
653 | E = ParseCXXPackIndexingExpression(PackIdExpression: E); |
654 | } |
655 | return E; |
656 | } |
657 | |
658 | ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { |
659 | // qualified-id: |
660 | // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id |
661 | // '::' unqualified-id |
662 | // |
663 | CXXScopeSpec SS; |
664 | ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, |
665 | /*ObjectHasErrors=*/ObjectHadErrors: false, |
666 | /*EnteringContext=*/false); |
667 | |
668 | Token Replacement; |
669 | ExprResult Result = |
670 | tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); |
671 | if (Result.isUnset()) { |
672 | // If the ExprResult is valid but null, then typo correction suggested a |
673 | // keyword replacement that needs to be reparsed. |
674 | UnconsumeToken(Consumed&: Replacement); |
675 | Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); |
676 | } |
677 | assert(!Result.isUnset() && "Typo correction suggested a keyword replacement " |
678 | "for a previous keyword suggestion" ); |
679 | return Result; |
680 | } |
681 | |
682 | ExprResult Parser::ParseLambdaExpression() { |
683 | // Parse lambda-introducer. |
684 | LambdaIntroducer Intro; |
685 | if (ParseLambdaIntroducer(Intro)) { |
686 | SkipUntil(T: tok::r_square, Flags: StopAtSemi); |
687 | SkipUntil(T: tok::l_brace, Flags: StopAtSemi); |
688 | SkipUntil(T: tok::r_brace, Flags: StopAtSemi); |
689 | return ExprError(); |
690 | } |
691 | |
692 | return ParseLambdaExpressionAfterIntroducer(Intro); |
693 | } |
694 | |
695 | ExprResult Parser::TryParseLambdaExpression() { |
696 | assert(getLangOpts().CPlusPlus && Tok.is(tok::l_square) && |
697 | "Not at the start of a possible lambda expression." ); |
698 | |
699 | const Token Next = NextToken(); |
700 | if (Next.is(K: tok::eof)) // Nothing else to lookup here... |
701 | return ExprEmpty(); |
702 | |
703 | const Token After = GetLookAheadToken(N: 2); |
704 | // If lookahead indicates this is a lambda... |
705 | if (Next.is(K: tok::r_square) || // [] |
706 | Next.is(K: tok::equal) || // [= |
707 | (Next.is(K: tok::amp) && // [&] or [&, |
708 | After.isOneOf(Ks: tok::r_square, Ks: tok::comma)) || |
709 | (Next.is(K: tok::identifier) && // [identifier] |
710 | After.is(K: tok::r_square)) || |
711 | Next.is(K: tok::ellipsis)) { // [... |
712 | return ParseLambdaExpression(); |
713 | } |
714 | |
715 | // If lookahead indicates an ObjC message send... |
716 | // [identifier identifier |
717 | if (Next.is(K: tok::identifier) && After.is(K: tok::identifier)) |
718 | return ExprEmpty(); |
719 | |
720 | // Here, we're stuck: lambda introducers and Objective-C message sends are |
721 | // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a |
722 | // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of |
723 | // writing two routines to parse a lambda introducer, just try to parse |
724 | // a lambda introducer first, and fall back if that fails. |
725 | LambdaIntroducer Intro; |
726 | { |
727 | TentativeParsingAction TPA(*this); |
728 | LambdaIntroducerTentativeParse Tentative; |
729 | if (ParseLambdaIntroducer(Intro, Tentative: &Tentative)) { |
730 | TPA.Commit(); |
731 | return ExprError(); |
732 | } |
733 | |
734 | switch (Tentative) { |
735 | case LambdaIntroducerTentativeParse::Success: |
736 | TPA.Commit(); |
737 | break; |
738 | |
739 | case LambdaIntroducerTentativeParse::Incomplete: |
740 | // Didn't fully parse the lambda-introducer, try again with a |
741 | // non-tentative parse. |
742 | TPA.Revert(); |
743 | Intro = LambdaIntroducer(); |
744 | if (ParseLambdaIntroducer(Intro)) |
745 | return ExprError(); |
746 | break; |
747 | |
748 | case LambdaIntroducerTentativeParse::MessageSend: |
749 | case LambdaIntroducerTentativeParse::Invalid: |
750 | // Not a lambda-introducer, might be a message send. |
751 | TPA.Revert(); |
752 | return ExprEmpty(); |
753 | } |
754 | } |
755 | |
756 | return ParseLambdaExpressionAfterIntroducer(Intro); |
757 | } |
758 | |
759 | bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, |
760 | LambdaIntroducerTentativeParse *Tentative) { |
761 | if (Tentative) |
762 | *Tentative = LambdaIntroducerTentativeParse::Success; |
763 | |
764 | assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['." ); |
765 | BalancedDelimiterTracker T(*this, tok::l_square); |
766 | T.consumeOpen(); |
767 | |
768 | Intro.Range.setBegin(T.getOpenLocation()); |
769 | |
770 | bool First = true; |
771 | |
772 | // Produce a diagnostic if we're not tentatively parsing; otherwise track |
773 | // that our parse has failed. |
774 | auto Invalid = [&](llvm::function_ref<void()> Action) { |
775 | if (Tentative) { |
776 | *Tentative = LambdaIntroducerTentativeParse::Invalid; |
777 | return false; |
778 | } |
779 | Action(); |
780 | return true; |
781 | }; |
782 | |
783 | // Perform some irreversible action if this is a non-tentative parse; |
784 | // otherwise note that our actions were incomplete. |
785 | auto NonTentativeAction = [&](llvm::function_ref<void()> Action) { |
786 | if (Tentative) |
787 | *Tentative = LambdaIntroducerTentativeParse::Incomplete; |
788 | else |
789 | Action(); |
790 | }; |
791 | |
792 | // Parse capture-default. |
793 | if (Tok.is(K: tok::amp) && |
794 | (NextToken().is(K: tok::comma) || NextToken().is(K: tok::r_square))) { |
795 | Intro.Default = LCD_ByRef; |
796 | Intro.DefaultLoc = ConsumeToken(); |
797 | First = false; |
798 | if (!Tok.getIdentifierInfo()) { |
799 | // This can only be a lambda; no need for tentative parsing any more. |
800 | // '[[and]]' can still be an attribute, though. |
801 | Tentative = nullptr; |
802 | } |
803 | } else if (Tok.is(K: tok::equal)) { |
804 | Intro.Default = LCD_ByCopy; |
805 | Intro.DefaultLoc = ConsumeToken(); |
806 | First = false; |
807 | Tentative = nullptr; |
808 | } |
809 | |
810 | while (Tok.isNot(K: tok::r_square)) { |
811 | if (!First) { |
812 | if (Tok.isNot(K: tok::comma)) { |
813 | // Provide a completion for a lambda introducer here. Except |
814 | // in Objective-C, where this is Almost Surely meant to be a message |
815 | // send. In that case, fail here and let the ObjC message |
816 | // expression parser perform the completion. |
817 | if (Tok.is(K: tok::code_completion) && |
818 | !(getLangOpts().ObjC && Tentative)) { |
819 | cutOffParsing(); |
820 | Actions.CodeCompletion().CodeCompleteLambdaIntroducer( |
821 | S: getCurScope(), Intro, |
822 | /*AfterAmpersand=*/false); |
823 | break; |
824 | } |
825 | |
826 | return Invalid([&] { |
827 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_comma_or_rsquare); |
828 | }); |
829 | } |
830 | ConsumeToken(); |
831 | } |
832 | |
833 | if (Tok.is(K: tok::code_completion)) { |
834 | cutOffParsing(); |
835 | // If we're in Objective-C++ and we have a bare '[', then this is more |
836 | // likely to be a message receiver. |
837 | if (getLangOpts().ObjC && Tentative && First) |
838 | Actions.CodeCompletion().CodeCompleteObjCMessageReceiver(S: getCurScope()); |
839 | else |
840 | Actions.CodeCompletion().CodeCompleteLambdaIntroducer( |
841 | S: getCurScope(), Intro, |
842 | /*AfterAmpersand=*/false); |
843 | break; |
844 | } |
845 | |
846 | First = false; |
847 | |
848 | // Parse capture. |
849 | LambdaCaptureKind Kind = LCK_ByCopy; |
850 | LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit; |
851 | SourceLocation Loc; |
852 | IdentifierInfo *Id = nullptr; |
853 | SourceLocation EllipsisLocs[4]; |
854 | ExprResult Init; |
855 | SourceLocation LocStart = Tok.getLocation(); |
856 | |
857 | if (Tok.is(K: tok::star)) { |
858 | Loc = ConsumeToken(); |
859 | if (Tok.is(K: tok::kw_this)) { |
860 | ConsumeToken(); |
861 | Kind = LCK_StarThis; |
862 | } else { |
863 | return Invalid([&] { |
864 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_star_this_capture); |
865 | }); |
866 | } |
867 | } else if (Tok.is(K: tok::kw_this)) { |
868 | Kind = LCK_This; |
869 | Loc = ConsumeToken(); |
870 | } else if (Tok.isOneOf(Ks: tok::amp, Ks: tok::equal) && |
871 | NextToken().isOneOf(Ks: tok::comma, Ks: tok::r_square) && |
872 | Intro.Default == LCD_None) { |
873 | // We have a lone "&" or "=" which is either a misplaced capture-default |
874 | // or the start of a capture (in the "&" case) with the rest of the |
875 | // capture missing. Both are an error but a misplaced capture-default |
876 | // is more likely if we don't already have a capture default. |
877 | return Invalid( |
878 | [&] { Diag(Loc: Tok.getLocation(), DiagID: diag::err_capture_default_first); }); |
879 | } else { |
880 | TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLocs[0]); |
881 | |
882 | if (Tok.is(K: tok::amp)) { |
883 | Kind = LCK_ByRef; |
884 | ConsumeToken(); |
885 | |
886 | if (Tok.is(K: tok::code_completion)) { |
887 | cutOffParsing(); |
888 | Actions.CodeCompletion().CodeCompleteLambdaIntroducer( |
889 | S: getCurScope(), Intro, |
890 | /*AfterAmpersand=*/true); |
891 | break; |
892 | } |
893 | } |
894 | |
895 | TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLocs[1]); |
896 | |
897 | if (Tok.is(K: tok::identifier)) { |
898 | Id = Tok.getIdentifierInfo(); |
899 | Loc = ConsumeToken(); |
900 | } else if (Tok.is(K: tok::kw_this)) { |
901 | return Invalid([&] { |
902 | // FIXME: Suggest a fixit here. |
903 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_this_captured_by_reference); |
904 | }); |
905 | } else { |
906 | return Invalid([&] { |
907 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_capture); |
908 | }); |
909 | } |
910 | |
911 | TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLocs[2]); |
912 | |
913 | if (Tok.is(K: tok::l_paren)) { |
914 | BalancedDelimiterTracker Parens(*this, tok::l_paren); |
915 | Parens.consumeOpen(); |
916 | |
917 | InitKind = LambdaCaptureInitKind::DirectInit; |
918 | |
919 | ExprVector Exprs; |
920 | if (Tentative) { |
921 | Parens.skipToEnd(); |
922 | *Tentative = LambdaIntroducerTentativeParse::Incomplete; |
923 | } else if (ParseExpressionList(Exprs)) { |
924 | Parens.skipToEnd(); |
925 | Init = ExprError(); |
926 | } else { |
927 | Parens.consumeClose(); |
928 | Init = Actions.ActOnParenListExpr(L: Parens.getOpenLocation(), |
929 | R: Parens.getCloseLocation(), |
930 | Val: Exprs); |
931 | } |
932 | } else if (Tok.isOneOf(Ks: tok::l_brace, Ks: tok::equal)) { |
933 | // Each lambda init-capture forms its own full expression, which clears |
934 | // Actions.MaybeODRUseExprs. So create an expression evaluation context |
935 | // to save the necessary state, and restore it later. |
936 | EnterExpressionEvaluationContext EC( |
937 | Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
938 | |
939 | if (TryConsumeToken(Expected: tok::equal)) |
940 | InitKind = LambdaCaptureInitKind::CopyInit; |
941 | else |
942 | InitKind = LambdaCaptureInitKind::ListInit; |
943 | |
944 | if (!Tentative) { |
945 | Init = ParseInitializer(); |
946 | } else if (Tok.is(K: tok::l_brace)) { |
947 | BalancedDelimiterTracker Braces(*this, tok::l_brace); |
948 | Braces.consumeOpen(); |
949 | Braces.skipToEnd(); |
950 | *Tentative = LambdaIntroducerTentativeParse::Incomplete; |
951 | } else { |
952 | // We're disambiguating this: |
953 | // |
954 | // [..., x = expr |
955 | // |
956 | // We need to find the end of the following expression in order to |
957 | // determine whether this is an Obj-C message send's receiver, a |
958 | // C99 designator, or a lambda init-capture. |
959 | // |
960 | // Parse the expression to find where it ends, and annotate it back |
961 | // onto the tokens. We would have parsed this expression the same way |
962 | // in either case: both the RHS of an init-capture and the RHS of an |
963 | // assignment expression are parsed as an initializer-clause, and in |
964 | // neither case can anything be added to the scope between the '[' and |
965 | // here. |
966 | // |
967 | // FIXME: This is horrible. Adding a mechanism to skip an expression |
968 | // would be much cleaner. |
969 | // FIXME: If there is a ',' before the next ']' or ':', we can skip to |
970 | // that instead. (And if we see a ':' with no matching '?', we can |
971 | // classify this as an Obj-C message send.) |
972 | SourceLocation StartLoc = Tok.getLocation(); |
973 | InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true); |
974 | Init = ParseInitializer(); |
975 | |
976 | if (Tok.getLocation() != StartLoc) { |
977 | // Back out the lexing of the token after the initializer. |
978 | PP.RevertCachedTokens(N: 1); |
979 | |
980 | // Replace the consumed tokens with an appropriate annotation. |
981 | Tok.setLocation(StartLoc); |
982 | Tok.setKind(tok::annot_primary_expr); |
983 | setExprAnnotation(Tok, ER: Init); |
984 | Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation()); |
985 | PP.AnnotateCachedTokens(Tok); |
986 | |
987 | // Consume the annotated initializer. |
988 | ConsumeAnnotationToken(); |
989 | } |
990 | } |
991 | } |
992 | |
993 | TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLocs[3]); |
994 | } |
995 | |
996 | // Check if this is a message send before we act on a possible init-capture. |
997 | if (Tentative && Tok.is(K: tok::identifier) && |
998 | NextToken().isOneOf(Ks: tok::colon, Ks: tok::r_square)) { |
999 | // This can only be a message send. We're done with disambiguation. |
1000 | *Tentative = LambdaIntroducerTentativeParse::MessageSend; |
1001 | return false; |
1002 | } |
1003 | |
1004 | // Ensure that any ellipsis was in the right place. |
1005 | SourceLocation EllipsisLoc; |
1006 | if (llvm::any_of(Range&: EllipsisLocs, |
1007 | P: [](SourceLocation Loc) { return Loc.isValid(); })) { |
1008 | // The '...' should appear before the identifier in an init-capture, and |
1009 | // after the identifier otherwise. |
1010 | bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit; |
1011 | SourceLocation *ExpectedEllipsisLoc = |
1012 | !InitCapture ? &EllipsisLocs[2] : |
1013 | Kind == LCK_ByRef ? &EllipsisLocs[1] : |
1014 | &EllipsisLocs[0]; |
1015 | EllipsisLoc = *ExpectedEllipsisLoc; |
1016 | |
1017 | unsigned DiagID = 0; |
1018 | if (EllipsisLoc.isInvalid()) { |
1019 | DiagID = diag::err_lambda_capture_misplaced_ellipsis; |
1020 | for (SourceLocation Loc : EllipsisLocs) { |
1021 | if (Loc.isValid()) |
1022 | EllipsisLoc = Loc; |
1023 | } |
1024 | } else { |
1025 | unsigned NumEllipses = std::accumulate( |
1026 | first: std::begin(arr&: EllipsisLocs), last: std::end(arr&: EllipsisLocs), init: 0, |
1027 | binary_op: [](int N, SourceLocation Loc) { return N + Loc.isValid(); }); |
1028 | if (NumEllipses > 1) |
1029 | DiagID = diag::err_lambda_capture_multiple_ellipses; |
1030 | } |
1031 | if (DiagID) { |
1032 | NonTentativeAction([&] { |
1033 | // Point the diagnostic at the first misplaced ellipsis. |
1034 | SourceLocation DiagLoc; |
1035 | for (SourceLocation &Loc : EllipsisLocs) { |
1036 | if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) { |
1037 | DiagLoc = Loc; |
1038 | break; |
1039 | } |
1040 | } |
1041 | assert(DiagLoc.isValid() && "no location for diagnostic" ); |
1042 | |
1043 | // Issue the diagnostic and produce fixits showing where the ellipsis |
1044 | // should have been written. |
1045 | auto &&D = Diag(Loc: DiagLoc, DiagID); |
1046 | if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) { |
1047 | SourceLocation ExpectedLoc = |
1048 | InitCapture ? Loc |
1049 | : Lexer::getLocForEndOfToken( |
1050 | Loc, Offset: 0, SM: PP.getSourceManager(), LangOpts: getLangOpts()); |
1051 | D << InitCapture << FixItHint::CreateInsertion(InsertionLoc: ExpectedLoc, Code: "..." ); |
1052 | } |
1053 | for (SourceLocation &Loc : EllipsisLocs) { |
1054 | if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) |
1055 | D << FixItHint::CreateRemoval(RemoveRange: Loc); |
1056 | } |
1057 | }); |
1058 | } |
1059 | } |
1060 | |
1061 | // Process the init-capture initializers now rather than delaying until we |
1062 | // form the lambda-expression so that they can be handled in the context |
1063 | // enclosing the lambda-expression, rather than in the context of the |
1064 | // lambda-expression itself. |
1065 | ParsedType InitCaptureType; |
1066 | if (Init.isUsable()) { |
1067 | NonTentativeAction([&] { |
1068 | // Get the pointer and store it in an lvalue, so we can use it as an |
1069 | // out argument. |
1070 | Expr *InitExpr = Init.get(); |
1071 | // This performs any lvalue-to-rvalue conversions if necessary, which |
1072 | // can affect what gets captured in the containing decl-context. |
1073 | InitCaptureType = Actions.actOnLambdaInitCaptureInitialization( |
1074 | Loc, ByRef: Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, Init&: InitExpr); |
1075 | Init = InitExpr; |
1076 | }); |
1077 | } |
1078 | |
1079 | SourceLocation LocEnd = PrevTokLocation; |
1080 | |
1081 | Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init, |
1082 | InitCaptureType, ExplicitRange: SourceRange(LocStart, LocEnd)); |
1083 | } |
1084 | |
1085 | T.consumeClose(); |
1086 | Intro.Range.setEnd(T.getCloseLocation()); |
1087 | return false; |
1088 | } |
1089 | |
1090 | static void tryConsumeLambdaSpecifierToken(Parser &P, |
1091 | SourceLocation &MutableLoc, |
1092 | SourceLocation &StaticLoc, |
1093 | SourceLocation &ConstexprLoc, |
1094 | SourceLocation &ConstevalLoc, |
1095 | SourceLocation &DeclEndLoc) { |
1096 | assert(MutableLoc.isInvalid()); |
1097 | assert(StaticLoc.isInvalid()); |
1098 | assert(ConstexprLoc.isInvalid()); |
1099 | assert(ConstevalLoc.isInvalid()); |
1100 | // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc |
1101 | // to the final of those locations. Emit an error if we have multiple |
1102 | // copies of those keywords and recover. |
1103 | |
1104 | auto ConsumeLocation = [&P, &DeclEndLoc](SourceLocation &SpecifierLoc, |
1105 | int DiagIndex) { |
1106 | if (SpecifierLoc.isValid()) { |
1107 | P.Diag(Loc: P.getCurToken().getLocation(), |
1108 | DiagID: diag::err_lambda_decl_specifier_repeated) |
1109 | << DiagIndex |
1110 | << FixItHint::CreateRemoval(RemoveRange: P.getCurToken().getLocation()); |
1111 | } |
1112 | SpecifierLoc = P.ConsumeToken(); |
1113 | DeclEndLoc = SpecifierLoc; |
1114 | }; |
1115 | |
1116 | while (true) { |
1117 | switch (P.getCurToken().getKind()) { |
1118 | case tok::kw_mutable: |
1119 | ConsumeLocation(MutableLoc, 0); |
1120 | break; |
1121 | case tok::kw_static: |
1122 | ConsumeLocation(StaticLoc, 1); |
1123 | break; |
1124 | case tok::kw_constexpr: |
1125 | ConsumeLocation(ConstexprLoc, 2); |
1126 | break; |
1127 | case tok::kw_consteval: |
1128 | ConsumeLocation(ConstevalLoc, 3); |
1129 | break; |
1130 | default: |
1131 | return; |
1132 | } |
1133 | } |
1134 | } |
1135 | |
1136 | static void addStaticToLambdaDeclSpecifier(Parser &P, SourceLocation StaticLoc, |
1137 | DeclSpec &DS) { |
1138 | if (StaticLoc.isValid()) { |
1139 | P.Diag(Loc: StaticLoc, DiagID: !P.getLangOpts().CPlusPlus23 |
1140 | ? diag::err_static_lambda |
1141 | : diag::warn_cxx20_compat_static_lambda); |
1142 | const char *PrevSpec = nullptr; |
1143 | unsigned DiagID = 0; |
1144 | DS.SetStorageClassSpec(S&: P.getActions(), SC: DeclSpec::SCS_static, Loc: StaticLoc, |
1145 | PrevSpec, DiagID, |
1146 | Policy: P.getActions().getASTContext().getPrintingPolicy()); |
1147 | assert(PrevSpec == nullptr && DiagID == 0 && |
1148 | "Static cannot have been set previously!" ); |
1149 | } |
1150 | } |
1151 | |
1152 | static void |
1153 | addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc, |
1154 | DeclSpec &DS) { |
1155 | if (ConstexprLoc.isValid()) { |
1156 | P.Diag(Loc: ConstexprLoc, DiagID: !P.getLangOpts().CPlusPlus17 |
1157 | ? diag::ext_constexpr_on_lambda_cxx17 |
1158 | : diag::warn_cxx14_compat_constexpr_on_lambda); |
1159 | const char *PrevSpec = nullptr; |
1160 | unsigned DiagID = 0; |
1161 | DS.SetConstexprSpec(ConstexprKind: ConstexprSpecKind::Constexpr, Loc: ConstexprLoc, PrevSpec, |
1162 | DiagID); |
1163 | assert(PrevSpec == nullptr && DiagID == 0 && |
1164 | "Constexpr cannot have been set previously!" ); |
1165 | } |
1166 | } |
1167 | |
1168 | static void addConstevalToLambdaDeclSpecifier(Parser &P, |
1169 | SourceLocation ConstevalLoc, |
1170 | DeclSpec &DS) { |
1171 | if (ConstevalLoc.isValid()) { |
1172 | P.Diag(Loc: ConstevalLoc, DiagID: diag::warn_cxx20_compat_consteval); |
1173 | const char *PrevSpec = nullptr; |
1174 | unsigned DiagID = 0; |
1175 | DS.SetConstexprSpec(ConstexprKind: ConstexprSpecKind::Consteval, Loc: ConstevalLoc, PrevSpec, |
1176 | DiagID); |
1177 | if (DiagID != 0) |
1178 | P.Diag(Loc: ConstevalLoc, DiagID) << PrevSpec; |
1179 | } |
1180 | } |
1181 | |
1182 | static void DiagnoseStaticSpecifierRestrictions(Parser &P, |
1183 | SourceLocation StaticLoc, |
1184 | SourceLocation MutableLoc, |
1185 | const LambdaIntroducer &Intro) { |
1186 | if (StaticLoc.isInvalid()) |
1187 | return; |
1188 | |
1189 | // [expr.prim.lambda.general] p4 |
1190 | // The lambda-specifier-seq shall not contain both mutable and static. |
1191 | // If the lambda-specifier-seq contains static, there shall be no |
1192 | // lambda-capture. |
1193 | if (MutableLoc.isValid()) |
1194 | P.Diag(Loc: StaticLoc, DiagID: diag::err_static_mutable_lambda); |
1195 | if (Intro.hasLambdaCapture()) { |
1196 | P.Diag(Loc: StaticLoc, DiagID: diag::err_static_lambda_captures); |
1197 | } |
1198 | } |
1199 | |
1200 | ExprResult Parser::ParseLambdaExpressionAfterIntroducer( |
1201 | LambdaIntroducer &Intro) { |
1202 | SourceLocation LambdaBeginLoc = Intro.Range.getBegin(); |
1203 | if (getLangOpts().HLSL) |
1204 | Diag(Loc: LambdaBeginLoc, DiagID: diag::ext_hlsl_lambda) << /*HLSL*/ 1; |
1205 | else |
1206 | Diag(Loc: LambdaBeginLoc, DiagID: getLangOpts().CPlusPlus11 |
1207 | ? diag::warn_cxx98_compat_lambda |
1208 | : diag::ext_lambda) |
1209 | << /*C++*/ 0; |
1210 | |
1211 | PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc, |
1212 | "lambda expression parsing" ); |
1213 | |
1214 | // Parse lambda-declarator[opt]. |
1215 | DeclSpec DS(AttrFactory); |
1216 | Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::LambdaExpr); |
1217 | TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); |
1218 | |
1219 | ParseScope LambdaScope(this, Scope::LambdaScope | Scope::DeclScope | |
1220 | Scope::FunctionDeclarationScope | |
1221 | Scope::FunctionPrototypeScope); |
1222 | |
1223 | Actions.PushLambdaScope(); |
1224 | Actions.ActOnLambdaExpressionAfterIntroducer(Intro, CurContext: getCurScope()); |
1225 | |
1226 | ParsedAttributes Attributes(AttrFactory); |
1227 | if (getLangOpts().CUDA) { |
1228 | // In CUDA code, GNU attributes are allowed to appear immediately after the |
1229 | // "[...]", even if there is no "(...)" before the lambda body. |
1230 | // |
1231 | // Note that we support __noinline__ as a keyword in this mode and thus |
1232 | // it has to be separately handled. |
1233 | while (true) { |
1234 | if (Tok.is(K: tok::kw___noinline__)) { |
1235 | IdentifierInfo *AttrName = Tok.getIdentifierInfo(); |
1236 | SourceLocation AttrNameLoc = ConsumeToken(); |
1237 | Attributes.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), |
1238 | /*ArgsUnion=*/args: nullptr, |
1239 | /*numArgs=*/0, form: tok::kw___noinline__); |
1240 | } else if (Tok.is(K: tok::kw___attribute)) |
1241 | ParseGNUAttributes(Attrs&: Attributes, /*LatePArsedAttrList=*/LateAttrs: nullptr, D: &D); |
1242 | else |
1243 | break; |
1244 | } |
1245 | |
1246 | D.takeAttributes(attrs&: Attributes); |
1247 | } |
1248 | |
1249 | MultiParseScope TemplateParamScope(*this); |
1250 | if (Tok.is(K: tok::less)) { |
1251 | Diag(Tok, DiagID: getLangOpts().CPlusPlus20 |
1252 | ? diag::warn_cxx17_compat_lambda_template_parameter_list |
1253 | : diag::ext_lambda_template_parameter_list); |
1254 | |
1255 | SmallVector<NamedDecl*, 4> TemplateParams; |
1256 | SourceLocation LAngleLoc, RAngleLoc; |
1257 | if (ParseTemplateParameters(TemplateScopes&: TemplateParamScope, |
1258 | Depth: CurTemplateDepthTracker.getDepth(), |
1259 | TemplateParams, LAngleLoc, RAngleLoc)) { |
1260 | Actions.ActOnLambdaError(StartLoc: LambdaBeginLoc, CurScope: getCurScope()); |
1261 | return ExprError(); |
1262 | } |
1263 | |
1264 | if (TemplateParams.empty()) { |
1265 | Diag(Loc: RAngleLoc, |
1266 | DiagID: diag::err_lambda_template_parameter_list_empty); |
1267 | } else { |
1268 | // We increase the template depth before recursing into a requires-clause. |
1269 | // |
1270 | // This depth is used for setting up a LambdaScopeInfo (in |
1271 | // Sema::RecordParsingTemplateParameterDepth), which is used later when |
1272 | // inventing template parameters in InventTemplateParameter. |
1273 | // |
1274 | // This way, abbreviated generic lambdas could have different template |
1275 | // depths, avoiding substitution into the wrong template parameters during |
1276 | // constraint satisfaction check. |
1277 | ++CurTemplateDepthTracker; |
1278 | ExprResult RequiresClause; |
1279 | if (TryConsumeToken(Expected: tok::kw_requires)) { |
1280 | RequiresClause = |
1281 | Actions.ActOnRequiresClause(ConstraintExpr: ParseConstraintLogicalOrExpression( |
1282 | /*IsTrailingRequiresClause=*/false)); |
1283 | if (RequiresClause.isInvalid()) |
1284 | SkipUntil(Toks: {tok::l_brace, tok::l_paren}, Flags: StopAtSemi | StopBeforeMatch); |
1285 | } |
1286 | |
1287 | Actions.ActOnLambdaExplicitTemplateParameterList( |
1288 | Intro, LAngleLoc, TParams: TemplateParams, RAngleLoc, RequiresClause); |
1289 | } |
1290 | } |
1291 | |
1292 | // Implement WG21 P2173, which allows attributes immediately before the |
1293 | // lambda declarator and applies them to the corresponding function operator |
1294 | // or operator template declaration. We accept this as a conforming extension |
1295 | // in all language modes that support lambdas. |
1296 | if (isCXX11AttributeSpecifier() != |
1297 | CXX11AttributeKind::NotAttributeSpecifier) { |
1298 | Diag(Tok, DiagID: getLangOpts().CPlusPlus23 |
1299 | ? diag::warn_cxx20_compat_decl_attrs_on_lambda |
1300 | : diag::ext_decl_attrs_on_lambda) |
1301 | << Tok.getIdentifierInfo() << Tok.isRegularKeywordAttribute(); |
1302 | MaybeParseCXX11Attributes(D); |
1303 | } |
1304 | |
1305 | TypeResult TrailingReturnType; |
1306 | SourceLocation TrailingReturnTypeLoc; |
1307 | SourceLocation LParenLoc, RParenLoc; |
1308 | SourceLocation DeclEndLoc; |
1309 | bool HasParentheses = false; |
1310 | bool HasSpecifiers = false; |
1311 | SourceLocation MutableLoc; |
1312 | |
1313 | ParseScope Prototype(this, Scope::FunctionPrototypeScope | |
1314 | Scope::FunctionDeclarationScope | |
1315 | Scope::DeclScope); |
1316 | |
1317 | // Parse parameter-declaration-clause. |
1318 | SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; |
1319 | SourceLocation EllipsisLoc; |
1320 | |
1321 | if (Tok.is(K: tok::l_paren)) { |
1322 | BalancedDelimiterTracker T(*this, tok::l_paren); |
1323 | T.consumeOpen(); |
1324 | LParenLoc = T.getOpenLocation(); |
1325 | |
1326 | if (Tok.isNot(K: tok::r_paren)) { |
1327 | Actions.RecordParsingTemplateParameterDepth( |
1328 | Depth: CurTemplateDepthTracker.getOriginalDepth()); |
1329 | |
1330 | ParseParameterDeclarationClause(D, attrs&: Attributes, ParamInfo, EllipsisLoc); |
1331 | // For a generic lambda, each 'auto' within the parameter declaration |
1332 | // clause creates a template type parameter, so increment the depth. |
1333 | // If we've parsed any explicit template parameters, then the depth will |
1334 | // have already been incremented. So we make sure that at most a single |
1335 | // depth level is added. |
1336 | if (Actions.getCurGenericLambda()) |
1337 | CurTemplateDepthTracker.setAddedDepth(1); |
1338 | } |
1339 | |
1340 | T.consumeClose(); |
1341 | DeclEndLoc = RParenLoc = T.getCloseLocation(); |
1342 | HasParentheses = true; |
1343 | } |
1344 | |
1345 | HasSpecifiers = |
1346 | Tok.isOneOf(Ks: tok::kw_mutable, Ks: tok::arrow, Ks: tok::kw___attribute, |
1347 | Ks: tok::kw_constexpr, Ks: tok::kw_consteval, Ks: tok::kw_static, |
1348 | Ks: tok::kw___private, Ks: tok::kw___global, Ks: tok::kw___local, |
1349 | Ks: tok::kw___constant, Ks: tok::kw___generic, Ks: tok::kw_groupshared, |
1350 | Ks: tok::kw_requires, Ks: tok::kw_noexcept) || |
1351 | Tok.isRegularKeywordAttribute() || |
1352 | (Tok.is(K: tok::l_square) && NextToken().is(K: tok::l_square)); |
1353 | |
1354 | if (HasSpecifiers && !HasParentheses && !getLangOpts().CPlusPlus23) { |
1355 | // It's common to forget that one needs '()' before 'mutable', an |
1356 | // attribute specifier, the result type, or the requires clause. Deal with |
1357 | // this. |
1358 | Diag(Tok, DiagID: diag::ext_lambda_missing_parens) |
1359 | << FixItHint::CreateInsertion(InsertionLoc: Tok.getLocation(), Code: "() " ); |
1360 | } |
1361 | |
1362 | if (HasParentheses || HasSpecifiers) { |
1363 | // GNU-style attributes must be parsed before the mutable specifier to |
1364 | // be compatible with GCC. MSVC-style attributes must be parsed before |
1365 | // the mutable specifier to be compatible with MSVC. |
1366 | MaybeParseAttributes(WhichAttrKinds: PAKM_GNU | PAKM_Declspec, Attrs&: Attributes); |
1367 | // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update |
1368 | // the DeclEndLoc. |
1369 | SourceLocation ConstexprLoc; |
1370 | SourceLocation ConstevalLoc; |
1371 | SourceLocation StaticLoc; |
1372 | |
1373 | tryConsumeLambdaSpecifierToken(P&: *this, MutableLoc, StaticLoc, ConstexprLoc, |
1374 | ConstevalLoc, DeclEndLoc); |
1375 | |
1376 | DiagnoseStaticSpecifierRestrictions(P&: *this, StaticLoc, MutableLoc, Intro); |
1377 | |
1378 | addStaticToLambdaDeclSpecifier(P&: *this, StaticLoc, DS); |
1379 | addConstexprToLambdaDeclSpecifier(P&: *this, ConstexprLoc, DS); |
1380 | addConstevalToLambdaDeclSpecifier(P&: *this, ConstevalLoc, DS); |
1381 | } |
1382 | |
1383 | Actions.ActOnLambdaClosureParameters(LambdaScope: getCurScope(), ParamInfo); |
1384 | |
1385 | if (!HasParentheses) |
1386 | Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc); |
1387 | |
1388 | if (HasSpecifiers || HasParentheses) { |
1389 | // Parse exception-specification[opt]. |
1390 | ExceptionSpecificationType ESpecType = EST_None; |
1391 | SourceRange ESpecRange; |
1392 | SmallVector<ParsedType, 2> DynamicExceptions; |
1393 | SmallVector<SourceRange, 2> DynamicExceptionRanges; |
1394 | ExprResult NoexceptExpr; |
1395 | CachedTokens *ExceptionSpecTokens; |
1396 | |
1397 | ESpecType = tryParseExceptionSpecification( |
1398 | /*Delayed=*/false, SpecificationRange&: ESpecRange, DynamicExceptions, |
1399 | DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens); |
1400 | |
1401 | if (ESpecType != EST_None) |
1402 | DeclEndLoc = ESpecRange.getEnd(); |
1403 | |
1404 | // Parse attribute-specifier[opt]. |
1405 | if (MaybeParseCXX11Attributes(Attrs&: Attributes)) |
1406 | DeclEndLoc = Attributes.Range.getEnd(); |
1407 | |
1408 | // Parse OpenCL addr space attribute. |
1409 | if (Tok.isOneOf(Ks: tok::kw___private, Ks: tok::kw___global, Ks: tok::kw___local, |
1410 | Ks: tok::kw___constant, Ks: tok::kw___generic)) { |
1411 | ParseOpenCLQualifiers(Attrs&: DS.getAttributes()); |
1412 | ConsumeToken(); |
1413 | } |
1414 | |
1415 | SourceLocation FunLocalRangeEnd = DeclEndLoc; |
1416 | |
1417 | // Parse trailing-return-type[opt]. |
1418 | if (Tok.is(K: tok::arrow)) { |
1419 | FunLocalRangeEnd = Tok.getLocation(); |
1420 | SourceRange Range; |
1421 | TrailingReturnType = |
1422 | ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false); |
1423 | TrailingReturnTypeLoc = Range.getBegin(); |
1424 | if (Range.getEnd().isValid()) |
1425 | DeclEndLoc = Range.getEnd(); |
1426 | } |
1427 | |
1428 | SourceLocation NoLoc; |
1429 | D.AddTypeInfo(TI: DeclaratorChunk::getFunction( |
1430 | /*HasProto=*/true, |
1431 | /*IsAmbiguous=*/false, LParenLoc, Params: ParamInfo.data(), |
1432 | NumParams: ParamInfo.size(), EllipsisLoc, RParenLoc, |
1433 | /*RefQualifierIsLvalueRef=*/true, |
1434 | /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType, |
1435 | ESpecRange, Exceptions: DynamicExceptions.data(), |
1436 | ExceptionRanges: DynamicExceptionRanges.data(), NumExceptions: DynamicExceptions.size(), |
1437 | NoexceptExpr: NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr, |
1438 | /*ExceptionSpecTokens*/ nullptr, |
1439 | /*DeclsInPrototype=*/{}, LocalRangeBegin: LParenLoc, LocalRangeEnd: FunLocalRangeEnd, TheDeclarator&: D, |
1440 | TrailingReturnType, TrailingReturnTypeLoc, MethodQualifiers: &DS), |
1441 | attrs: std::move(Attributes), EndLoc: DeclEndLoc); |
1442 | |
1443 | // We have called ActOnLambdaClosureQualifiers for parentheses-less cases |
1444 | // above. |
1445 | if (HasParentheses) |
1446 | Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc); |
1447 | |
1448 | if (HasParentheses && Tok.is(K: tok::kw_requires)) |
1449 | ParseTrailingRequiresClause(D); |
1450 | } |
1451 | |
1452 | // Emit a warning if we see a CUDA host/device/global attribute |
1453 | // after '(...)'. nvcc doesn't accept this. |
1454 | if (getLangOpts().CUDA) { |
1455 | for (const ParsedAttr &A : Attributes) |
1456 | if (A.getKind() == ParsedAttr::AT_CUDADevice || |
1457 | A.getKind() == ParsedAttr::AT_CUDAHost || |
1458 | A.getKind() == ParsedAttr::AT_CUDAGlobal) |
1459 | Diag(Loc: A.getLoc(), DiagID: diag::warn_cuda_attr_lambda_position) |
1460 | << A.getAttrName()->getName(); |
1461 | } |
1462 | |
1463 | Prototype.Exit(); |
1464 | |
1465 | // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using |
1466 | // it. |
1467 | unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope | |
1468 | Scope::CompoundStmtScope; |
1469 | ParseScope BodyScope(this, ScopeFlags); |
1470 | |
1471 | Actions.ActOnStartOfLambdaDefinition(Intro, ParamInfo&: D, DS); |
1472 | |
1473 | // Parse compound-statement. |
1474 | if (!Tok.is(K: tok::l_brace)) { |
1475 | Diag(Tok, DiagID: diag::err_expected_lambda_body); |
1476 | Actions.ActOnLambdaError(StartLoc: LambdaBeginLoc, CurScope: getCurScope()); |
1477 | return ExprError(); |
1478 | } |
1479 | |
1480 | StmtResult Stmt(ParseCompoundStatementBody()); |
1481 | BodyScope.Exit(); |
1482 | TemplateParamScope.Exit(); |
1483 | LambdaScope.Exit(); |
1484 | |
1485 | if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid() && |
1486 | !D.isInvalidType()) |
1487 | return Actions.ActOnLambdaExpr(StartLoc: LambdaBeginLoc, Body: Stmt.get()); |
1488 | |
1489 | Actions.ActOnLambdaError(StartLoc: LambdaBeginLoc, CurScope: getCurScope()); |
1490 | return ExprError(); |
1491 | } |
1492 | |
1493 | ExprResult Parser::ParseCXXCasts() { |
1494 | tok::TokenKind Kind = Tok.getKind(); |
1495 | const char *CastName = nullptr; // For error messages |
1496 | |
1497 | switch (Kind) { |
1498 | default: llvm_unreachable("Unknown C++ cast!" ); |
1499 | case tok::kw_addrspace_cast: CastName = "addrspace_cast" ; break; |
1500 | case tok::kw_const_cast: CastName = "const_cast" ; break; |
1501 | case tok::kw_dynamic_cast: CastName = "dynamic_cast" ; break; |
1502 | case tok::kw_reinterpret_cast: CastName = "reinterpret_cast" ; break; |
1503 | case tok::kw_static_cast: CastName = "static_cast" ; break; |
1504 | } |
1505 | |
1506 | SourceLocation OpLoc = ConsumeToken(); |
1507 | SourceLocation LAngleBracketLoc = Tok.getLocation(); |
1508 | |
1509 | // Check for "<::" which is parsed as "[:". If found, fix token stream, |
1510 | // diagnose error, suggest fix, and recover parsing. |
1511 | if (Tok.is(K: tok::l_square) && Tok.getLength() == 2) { |
1512 | Token Next = NextToken(); |
1513 | if (Next.is(K: tok::colon) && areTokensAdjacent(First: Tok, Second: Next)) |
1514 | FixDigraph(P&: *this, PP, DigraphToken&: Tok, ColonToken&: Next, Kind, /*AtDigraph*/true); |
1515 | } |
1516 | |
1517 | if (ExpectAndConsume(ExpectedTok: tok::less, Diag: diag::err_expected_less_after, DiagMsg: CastName)) |
1518 | return ExprError(); |
1519 | |
1520 | // Parse the common declaration-specifiers piece. |
1521 | DeclSpec DS(AttrFactory); |
1522 | ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS: AS_none, |
1523 | DSC: DeclSpecContext::DSC_type_specifier); |
1524 | |
1525 | // Parse the abstract-declarator, if present. |
1526 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
1527 | DeclaratorContext::TypeName); |
1528 | ParseDeclarator(D&: DeclaratorInfo); |
1529 | |
1530 | SourceLocation RAngleBracketLoc = Tok.getLocation(); |
1531 | |
1532 | if (ExpectAndConsume(ExpectedTok: tok::greater)) |
1533 | return ExprError(Diag(Loc: LAngleBracketLoc, DiagID: diag::note_matching) << tok::less); |
1534 | |
1535 | BalancedDelimiterTracker T(*this, tok::l_paren); |
1536 | |
1537 | if (T.expectAndConsume(DiagID: diag::err_expected_lparen_after, Msg: CastName)) |
1538 | return ExprError(); |
1539 | |
1540 | ExprResult Result = ParseExpression(); |
1541 | |
1542 | // Match the ')'. |
1543 | T.consumeClose(); |
1544 | |
1545 | if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType()) |
1546 | Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, |
1547 | LAngleBracketLoc, D&: DeclaratorInfo, |
1548 | RAngleBracketLoc, |
1549 | LParenLoc: T.getOpenLocation(), E: Result.get(), |
1550 | RParenLoc: T.getCloseLocation()); |
1551 | |
1552 | return Result; |
1553 | } |
1554 | |
1555 | ExprResult Parser::ParseCXXTypeid() { |
1556 | assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!" ); |
1557 | |
1558 | SourceLocation OpLoc = ConsumeToken(); |
1559 | SourceLocation LParenLoc, RParenLoc; |
1560 | BalancedDelimiterTracker T(*this, tok::l_paren); |
1561 | |
1562 | // typeid expressions are always parenthesized. |
1563 | if (T.expectAndConsume(DiagID: diag::err_expected_lparen_after, Msg: "typeid" )) |
1564 | return ExprError(); |
1565 | LParenLoc = T.getOpenLocation(); |
1566 | |
1567 | ExprResult Result; |
1568 | |
1569 | // C++0x [expr.typeid]p3: |
1570 | // When typeid is applied to an expression other than an lvalue of a |
1571 | // polymorphic class type [...] The expression is an unevaluated |
1572 | // operand (Clause 5). |
1573 | // |
1574 | // Note that we can't tell whether the expression is an lvalue of a |
1575 | // polymorphic class type until after we've parsed the expression; we |
1576 | // speculatively assume the subexpression is unevaluated, and fix it up |
1577 | // later. |
1578 | // |
1579 | // We enter the unevaluated context before trying to determine whether we |
1580 | // have a type-id, because the tentative parse logic will try to resolve |
1581 | // names, and must treat them as unevaluated. |
1582 | EnterExpressionEvaluationContext Unevaluated( |
1583 | Actions, Sema::ExpressionEvaluationContext::Unevaluated, |
1584 | Sema::ReuseLambdaContextDecl); |
1585 | |
1586 | if (isTypeIdInParens()) { |
1587 | TypeResult Ty = ParseTypeName(); |
1588 | |
1589 | // Match the ')'. |
1590 | T.consumeClose(); |
1591 | RParenLoc = T.getCloseLocation(); |
1592 | if (Ty.isInvalid() || RParenLoc.isInvalid()) |
1593 | return ExprError(); |
1594 | |
1595 | Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, |
1596 | TyOrExpr: Ty.get().getAsOpaquePtr(), RParenLoc); |
1597 | } else { |
1598 | Result = ParseExpression(); |
1599 | |
1600 | // Match the ')'. |
1601 | if (Result.isInvalid()) |
1602 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
1603 | else { |
1604 | T.consumeClose(); |
1605 | RParenLoc = T.getCloseLocation(); |
1606 | if (RParenLoc.isInvalid()) |
1607 | return ExprError(); |
1608 | |
1609 | Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, |
1610 | TyOrExpr: Result.get(), RParenLoc); |
1611 | } |
1612 | } |
1613 | |
1614 | return Result; |
1615 | } |
1616 | |
1617 | ExprResult Parser::ParseCXXUuidof() { |
1618 | assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!" ); |
1619 | |
1620 | SourceLocation OpLoc = ConsumeToken(); |
1621 | BalancedDelimiterTracker T(*this, tok::l_paren); |
1622 | |
1623 | // __uuidof expressions are always parenthesized. |
1624 | if (T.expectAndConsume(DiagID: diag::err_expected_lparen_after, Msg: "__uuidof" )) |
1625 | return ExprError(); |
1626 | |
1627 | ExprResult Result; |
1628 | |
1629 | if (isTypeIdInParens()) { |
1630 | TypeResult Ty = ParseTypeName(); |
1631 | |
1632 | // Match the ')'. |
1633 | T.consumeClose(); |
1634 | |
1635 | if (Ty.isInvalid()) |
1636 | return ExprError(); |
1637 | |
1638 | Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc: T.getOpenLocation(), /*isType=*/true, |
1639 | TyOrExpr: Ty.get().getAsOpaquePtr(), |
1640 | RParenLoc: T.getCloseLocation()); |
1641 | } else { |
1642 | EnterExpressionEvaluationContext Unevaluated( |
1643 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); |
1644 | Result = ParseExpression(); |
1645 | |
1646 | // Match the ')'. |
1647 | if (Result.isInvalid()) |
1648 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
1649 | else { |
1650 | T.consumeClose(); |
1651 | |
1652 | Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc: T.getOpenLocation(), |
1653 | /*isType=*/false, |
1654 | TyOrExpr: Result.get(), RParenLoc: T.getCloseLocation()); |
1655 | } |
1656 | } |
1657 | |
1658 | return Result; |
1659 | } |
1660 | |
1661 | ExprResult |
1662 | Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, |
1663 | tok::TokenKind OpKind, |
1664 | CXXScopeSpec &SS, |
1665 | ParsedType ObjectType) { |
1666 | // If the last component of the (optional) nested-name-specifier is |
1667 | // template[opt] simple-template-id, it has already been annotated. |
1668 | UnqualifiedId FirstTypeName; |
1669 | SourceLocation CCLoc; |
1670 | if (Tok.is(K: tok::identifier)) { |
1671 | FirstTypeName.setIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation()); |
1672 | ConsumeToken(); |
1673 | assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail" ); |
1674 | CCLoc = ConsumeToken(); |
1675 | } else if (Tok.is(K: tok::annot_template_id)) { |
1676 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok); |
1677 | // FIXME: Carry on and build an AST representation for tooling. |
1678 | if (TemplateId->isInvalid()) |
1679 | return ExprError(); |
1680 | FirstTypeName.setTemplateId(TemplateId); |
1681 | ConsumeAnnotationToken(); |
1682 | assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail" ); |
1683 | CCLoc = ConsumeToken(); |
1684 | } else { |
1685 | assert(SS.isEmpty() && "missing last component of nested name specifier" ); |
1686 | FirstTypeName.setIdentifier(Id: nullptr, IdLoc: SourceLocation()); |
1687 | } |
1688 | |
1689 | // Parse the tilde. |
1690 | assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail" ); |
1691 | SourceLocation TildeLoc = ConsumeToken(); |
1692 | |
1693 | if (Tok.is(K: tok::kw_decltype) && !FirstTypeName.isValid()) { |
1694 | DeclSpec DS(AttrFactory); |
1695 | ParseDecltypeSpecifier(DS); |
1696 | if (DS.getTypeSpecType() == TST_error) |
1697 | return ExprError(); |
1698 | return Actions.ActOnPseudoDestructorExpr(S: getCurScope(), Base, OpLoc, OpKind, |
1699 | TildeLoc, DS); |
1700 | } |
1701 | |
1702 | if (!Tok.is(K: tok::identifier)) { |
1703 | Diag(Tok, DiagID: diag::err_destructor_tilde_identifier); |
1704 | return ExprError(); |
1705 | } |
1706 | |
1707 | // pack-index-specifier |
1708 | if (GetLookAheadToken(N: 1).is(K: tok::ellipsis) && |
1709 | GetLookAheadToken(N: 2).is(K: tok::l_square)) { |
1710 | DeclSpec DS(AttrFactory); |
1711 | ParsePackIndexingType(DS); |
1712 | return Actions.ActOnPseudoDestructorExpr(S: getCurScope(), Base, OpLoc, OpKind, |
1713 | TildeLoc, DS); |
1714 | } |
1715 | |
1716 | // Parse the second type. |
1717 | UnqualifiedId SecondTypeName; |
1718 | IdentifierInfo *Name = Tok.getIdentifierInfo(); |
1719 | SourceLocation NameLoc = ConsumeToken(); |
1720 | SecondTypeName.setIdentifier(Id: Name, IdLoc: NameLoc); |
1721 | |
1722 | // If there is a '<', the second type name is a template-id. Parse |
1723 | // it as such. |
1724 | // |
1725 | // FIXME: This is not a context in which a '<' is assumed to start a template |
1726 | // argument list. This affects examples such as |
1727 | // void f(auto *p) { p->~X<int>(); } |
1728 | // ... but there's no ambiguity, and nowhere to write 'template' in such an |
1729 | // example, so we accept it anyway. |
1730 | if (Tok.is(K: tok::less) && |
1731 | ParseUnqualifiedIdTemplateId( |
1732 | SS, ObjectType, ObjectHadErrors: Base && Base->containsErrors(), TemplateKWLoc: SourceLocation(), |
1733 | Name, NameLoc, EnteringContext: false, Id&: SecondTypeName, |
1734 | /*AssumeTemplateId=*/true)) |
1735 | return ExprError(); |
1736 | |
1737 | return Actions.ActOnPseudoDestructorExpr(S: getCurScope(), Base, OpLoc, OpKind, |
1738 | SS, FirstTypeName, CCLoc, TildeLoc, |
1739 | SecondTypeName); |
1740 | } |
1741 | |
1742 | ExprResult Parser::ParseCXXBoolLiteral() { |
1743 | tok::TokenKind Kind = Tok.getKind(); |
1744 | return Actions.ActOnCXXBoolLiteral(OpLoc: ConsumeToken(), Kind); |
1745 | } |
1746 | |
1747 | ExprResult Parser::ParseThrowExpression() { |
1748 | assert(Tok.is(tok::kw_throw) && "Not throw!" ); |
1749 | SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. |
1750 | |
1751 | // If the current token isn't the start of an assignment-expression, |
1752 | // then the expression is not present. This handles things like: |
1753 | // "C ? throw : (void)42", which is crazy but legal. |
1754 | switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. |
1755 | case tok::semi: |
1756 | case tok::r_paren: |
1757 | case tok::r_square: |
1758 | case tok::r_brace: |
1759 | case tok::colon: |
1760 | case tok::comma: |
1761 | return Actions.ActOnCXXThrow(S: getCurScope(), OpLoc: ThrowLoc, expr: nullptr); |
1762 | |
1763 | default: |
1764 | ExprResult Expr(ParseAssignmentExpression()); |
1765 | if (Expr.isInvalid()) return Expr; |
1766 | return Actions.ActOnCXXThrow(S: getCurScope(), OpLoc: ThrowLoc, expr: Expr.get()); |
1767 | } |
1768 | } |
1769 | |
1770 | ExprResult Parser::ParseCoyieldExpression() { |
1771 | assert(Tok.is(tok::kw_co_yield) && "Not co_yield!" ); |
1772 | |
1773 | SourceLocation Loc = ConsumeToken(); |
1774 | ExprResult Expr = Tok.is(K: tok::l_brace) ? ParseBraceInitializer() |
1775 | : ParseAssignmentExpression(); |
1776 | if (!Expr.isInvalid()) |
1777 | Expr = Actions.ActOnCoyieldExpr(S: getCurScope(), KwLoc: Loc, E: Expr.get()); |
1778 | return Expr; |
1779 | } |
1780 | |
1781 | ExprResult Parser::ParseCXXThis() { |
1782 | assert(Tok.is(tok::kw_this) && "Not 'this'!" ); |
1783 | SourceLocation ThisLoc = ConsumeToken(); |
1784 | return Actions.ActOnCXXThis(Loc: ThisLoc); |
1785 | } |
1786 | |
1787 | ExprResult |
1788 | Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { |
1789 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
1790 | DeclaratorContext::FunctionalCast); |
1791 | ParsedType TypeRep = Actions.ActOnTypeName(D&: DeclaratorInfo).get(); |
1792 | |
1793 | assert((Tok.is(tok::l_paren) || |
1794 | (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) |
1795 | && "Expected '(' or '{'!" ); |
1796 | |
1797 | if (Tok.is(K: tok::l_brace)) { |
1798 | PreferredType.enterTypeCast(Tok: Tok.getLocation(), CastType: TypeRep.get()); |
1799 | ExprResult Init = ParseBraceInitializer(); |
1800 | if (Init.isInvalid()) |
1801 | return Init; |
1802 | Expr *InitList = Init.get(); |
1803 | return Actions.ActOnCXXTypeConstructExpr( |
1804 | TypeRep, LParenOrBraceLoc: InitList->getBeginLoc(), Exprs: MultiExprArg(&InitList, 1), |
1805 | RParenOrBraceLoc: InitList->getEndLoc(), /*ListInitialization=*/true); |
1806 | } else { |
1807 | BalancedDelimiterTracker T(*this, tok::l_paren); |
1808 | T.consumeOpen(); |
1809 | |
1810 | PreferredType.enterTypeCast(Tok: Tok.getLocation(), CastType: TypeRep.get()); |
1811 | |
1812 | ExprVector Exprs; |
1813 | |
1814 | auto RunSignatureHelp = [&]() { |
1815 | QualType PreferredType; |
1816 | if (TypeRep) |
1817 | PreferredType = |
1818 | Actions.CodeCompletion().ProduceConstructorSignatureHelp( |
1819 | Type: TypeRep.get()->getCanonicalTypeInternal(), Loc: DS.getEndLoc(), |
1820 | Args: Exprs, OpenParLoc: T.getOpenLocation(), /*Braced=*/false); |
1821 | CalledSignatureHelp = true; |
1822 | return PreferredType; |
1823 | }; |
1824 | |
1825 | if (Tok.isNot(K: tok::r_paren)) { |
1826 | if (ParseExpressionList(Exprs, ExpressionStarts: [&] { |
1827 | PreferredType.enterFunctionArgument(Tok: Tok.getLocation(), |
1828 | ComputeType: RunSignatureHelp); |
1829 | })) { |
1830 | if (PP.isCodeCompletionReached() && !CalledSignatureHelp) |
1831 | RunSignatureHelp(); |
1832 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
1833 | return ExprError(); |
1834 | } |
1835 | } |
1836 | |
1837 | // Match the ')'. |
1838 | T.consumeClose(); |
1839 | |
1840 | // TypeRep could be null, if it references an invalid typedef. |
1841 | if (!TypeRep) |
1842 | return ExprError(); |
1843 | |
1844 | return Actions.ActOnCXXTypeConstructExpr(TypeRep, LParenOrBraceLoc: T.getOpenLocation(), |
1845 | Exprs, RParenOrBraceLoc: T.getCloseLocation(), |
1846 | /*ListInitialization=*/false); |
1847 | } |
1848 | } |
1849 | |
1850 | Parser::DeclGroupPtrTy |
1851 | Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context, |
1852 | ParsedAttributes &Attrs) { |
1853 | assert(Tok.is(tok::kw_using) && "Expected using" ); |
1854 | assert((Context == DeclaratorContext::ForInit || |
1855 | Context == DeclaratorContext::SelectionInit) && |
1856 | "Unexpected Declarator Context" ); |
1857 | DeclGroupPtrTy DG; |
1858 | SourceLocation DeclStart = ConsumeToken(), DeclEnd; |
1859 | |
1860 | DG = ParseUsingDeclaration(Context, TemplateInfo: {}, UsingLoc: DeclStart, DeclEnd, Attrs, AS: AS_none); |
1861 | if (!DG) |
1862 | return DG; |
1863 | |
1864 | Diag(Loc: DeclStart, DiagID: !getLangOpts().CPlusPlus23 |
1865 | ? diag::ext_alias_in_init_statement |
1866 | : diag::warn_cxx20_alias_in_init_statement) |
1867 | << SourceRange(DeclStart, DeclEnd); |
1868 | |
1869 | return DG; |
1870 | } |
1871 | |
1872 | Sema::ConditionResult |
1873 | Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, |
1874 | Sema::ConditionKind CK, bool MissingOK, |
1875 | ForRangeInfo *FRI, bool EnterForConditionScope) { |
1876 | // Helper to ensure we always enter a continue/break scope if requested. |
1877 | struct ForConditionScopeRAII { |
1878 | Scope *S; |
1879 | void enter(bool IsConditionVariable) { |
1880 | if (S) { |
1881 | S->AddFlags(Flags: Scope::BreakScope | Scope::ContinueScope); |
1882 | S->setIsConditionVarScope(IsConditionVariable); |
1883 | } |
1884 | } |
1885 | ~ForConditionScopeRAII() { |
1886 | if (S) |
1887 | S->setIsConditionVarScope(false); |
1888 | } |
1889 | } ForConditionScope{.S: EnterForConditionScope ? getCurScope() : nullptr}; |
1890 | |
1891 | ParenBraceBracketBalancer BalancerRAIIObj(*this); |
1892 | PreferredType.enterCondition(S&: Actions, Tok: Tok.getLocation()); |
1893 | |
1894 | if (Tok.is(K: tok::code_completion)) { |
1895 | cutOffParsing(); |
1896 | Actions.CodeCompletion().CodeCompleteOrdinaryName( |
1897 | S: getCurScope(), CompletionContext: SemaCodeCompletion::PCC_Condition); |
1898 | return Sema::ConditionError(); |
1899 | } |
1900 | |
1901 | ParsedAttributes attrs(AttrFactory); |
1902 | MaybeParseCXX11Attributes(Attrs&: attrs); |
1903 | |
1904 | const auto WarnOnInit = [this, &CK] { |
1905 | Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus17 |
1906 | ? diag::warn_cxx14_compat_init_statement |
1907 | : diag::ext_init_statement) |
1908 | << (CK == Sema::ConditionKind::Switch); |
1909 | }; |
1910 | |
1911 | // Determine what kind of thing we have. |
1912 | switch (isCXXConditionDeclarationOrInitStatement(CanBeInitStmt: InitStmt, CanBeForRangeDecl: FRI)) { |
1913 | case ConditionOrInitStatement::Expression: { |
1914 | // If this is a for loop, we're entering its condition. |
1915 | ForConditionScope.enter(/*IsConditionVariable=*/false); |
1916 | |
1917 | ProhibitAttributes(Attrs&: attrs); |
1918 | |
1919 | // We can have an empty expression here. |
1920 | // if (; true); |
1921 | if (InitStmt && Tok.is(K: tok::semi)) { |
1922 | WarnOnInit(); |
1923 | SourceLocation SemiLoc = Tok.getLocation(); |
1924 | if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) { |
1925 | Diag(Loc: SemiLoc, DiagID: diag::warn_empty_init_statement) |
1926 | << (CK == Sema::ConditionKind::Switch) |
1927 | << FixItHint::CreateRemoval(RemoveRange: SemiLoc); |
1928 | } |
1929 | ConsumeToken(); |
1930 | *InitStmt = Actions.ActOnNullStmt(SemiLoc); |
1931 | return ParseCXXCondition(InitStmt: nullptr, Loc, CK, MissingOK); |
1932 | } |
1933 | |
1934 | ExprResult Expr = [&] { |
1935 | EnterExpressionEvaluationContext Eval( |
1936 | Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated, |
1937 | /*LambdaContextDecl=*/nullptr, |
1938 | /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_Other, |
1939 | /*ShouldEnter=*/CK == Sema::ConditionKind::ConstexprIf); |
1940 | // Parse the expression. |
1941 | return ParseExpression(); // expression |
1942 | }(); |
1943 | |
1944 | if (Expr.isInvalid()) |
1945 | return Sema::ConditionError(); |
1946 | |
1947 | if (InitStmt && Tok.is(K: tok::semi)) { |
1948 | WarnOnInit(); |
1949 | *InitStmt = Actions.ActOnExprStmt(Arg: Expr.get()); |
1950 | ConsumeToken(); |
1951 | return ParseCXXCondition(InitStmt: nullptr, Loc, CK, MissingOK); |
1952 | } |
1953 | |
1954 | return Actions.ActOnCondition(S: getCurScope(), Loc, SubExpr: Expr.get(), CK, |
1955 | MissingOK); |
1956 | } |
1957 | |
1958 | case ConditionOrInitStatement::InitStmtDecl: { |
1959 | WarnOnInit(); |
1960 | DeclGroupPtrTy DG; |
1961 | SourceLocation DeclStart = Tok.getLocation(), DeclEnd; |
1962 | if (Tok.is(K: tok::kw_using)) |
1963 | DG = ParseAliasDeclarationInInitStatement( |
1964 | Context: DeclaratorContext::SelectionInit, Attrs&: attrs); |
1965 | else { |
1966 | ParsedAttributes DeclSpecAttrs(AttrFactory); |
1967 | DG = ParseSimpleDeclaration(Context: DeclaratorContext::SelectionInit, DeclEnd, |
1968 | DeclAttrs&: attrs, DeclSpecAttrs, /*RequireSemi=*/true); |
1969 | } |
1970 | *InitStmt = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: DeclEnd); |
1971 | return ParseCXXCondition(InitStmt: nullptr, Loc, CK, MissingOK); |
1972 | } |
1973 | |
1974 | case ConditionOrInitStatement::ForRangeDecl: { |
1975 | // This is 'for (init-stmt; for-range-decl : range-expr)'. |
1976 | // We're not actually in a for loop yet, so 'break' and 'continue' aren't |
1977 | // permitted here. |
1978 | assert(FRI && "should not parse a for range declaration here" ); |
1979 | SourceLocation DeclStart = Tok.getLocation(), DeclEnd; |
1980 | ParsedAttributes DeclSpecAttrs(AttrFactory); |
1981 | DeclGroupPtrTy DG = ParseSimpleDeclaration( |
1982 | Context: DeclaratorContext::ForInit, DeclEnd, DeclAttrs&: attrs, DeclSpecAttrs, RequireSemi: false, FRI); |
1983 | FRI->LoopVar = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: Tok.getLocation()); |
1984 | return Sema::ConditionResult(); |
1985 | } |
1986 | |
1987 | case ConditionOrInitStatement::ConditionDecl: |
1988 | case ConditionOrInitStatement::Error: |
1989 | break; |
1990 | } |
1991 | |
1992 | // If this is a for loop, we're entering its condition. |
1993 | ForConditionScope.enter(/*IsConditionVariable=*/true); |
1994 | |
1995 | // type-specifier-seq |
1996 | DeclSpec DS(AttrFactory); |
1997 | ParseSpecifierQualifierList(DS, AS: AS_none, DSC: DeclSpecContext::DSC_condition); |
1998 | |
1999 | // declarator |
2000 | Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition); |
2001 | ParseDeclarator(D&: DeclaratorInfo); |
2002 | |
2003 | // simple-asm-expr[opt] |
2004 | if (Tok.is(K: tok::kw_asm)) { |
2005 | SourceLocation Loc; |
2006 | ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, EndLoc: &Loc)); |
2007 | if (AsmLabel.isInvalid()) { |
2008 | SkipUntil(T: tok::semi, Flags: StopAtSemi); |
2009 | return Sema::ConditionError(); |
2010 | } |
2011 | DeclaratorInfo.setAsmLabel(AsmLabel.get()); |
2012 | DeclaratorInfo.SetRangeEnd(Loc); |
2013 | } |
2014 | |
2015 | // If attributes are present, parse them. |
2016 | MaybeParseGNUAttributes(D&: DeclaratorInfo); |
2017 | |
2018 | // Type-check the declaration itself. |
2019 | DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(S: getCurScope(), |
2020 | D&: DeclaratorInfo); |
2021 | if (Dcl.isInvalid()) |
2022 | return Sema::ConditionError(); |
2023 | Decl *DeclOut = Dcl.get(); |
2024 | |
2025 | // '=' assignment-expression |
2026 | // If a '==' or '+=' is found, suggest a fixit to '='. |
2027 | bool CopyInitialization = isTokenEqualOrEqualTypo(); |
2028 | if (CopyInitialization) |
2029 | ConsumeToken(); |
2030 | |
2031 | ExprResult InitExpr = ExprError(); |
2032 | if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace)) { |
2033 | Diag(Loc: Tok.getLocation(), |
2034 | DiagID: diag::warn_cxx98_compat_generalized_initializer_lists); |
2035 | InitExpr = ParseBraceInitializer(); |
2036 | } else if (CopyInitialization) { |
2037 | PreferredType.enterVariableInit(Tok: Tok.getLocation(), D: DeclOut); |
2038 | InitExpr = ParseAssignmentExpression(); |
2039 | } else if (Tok.is(K: tok::l_paren)) { |
2040 | // This was probably an attempt to initialize the variable. |
2041 | SourceLocation LParen = ConsumeParen(), RParen = LParen; |
2042 | if (SkipUntil(T: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch)) |
2043 | RParen = ConsumeParen(); |
2044 | Diag(Loc: DeclOut->getLocation(), |
2045 | DiagID: diag::err_expected_init_in_condition_lparen) |
2046 | << SourceRange(LParen, RParen); |
2047 | } else { |
2048 | Diag(Loc: DeclOut->getLocation(), DiagID: diag::err_expected_init_in_condition); |
2049 | } |
2050 | |
2051 | if (!InitExpr.isInvalid()) |
2052 | Actions.AddInitializerToDecl(dcl: DeclOut, init: InitExpr.get(), DirectInit: !CopyInitialization); |
2053 | else |
2054 | Actions.ActOnInitializerError(Dcl: DeclOut); |
2055 | |
2056 | Actions.FinalizeDeclaration(D: DeclOut); |
2057 | return Actions.ActOnConditionVariable(ConditionVar: DeclOut, StmtLoc: Loc, CK); |
2058 | } |
2059 | |
2060 | void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { |
2061 | DS.SetRangeStart(Tok.getLocation()); |
2062 | const char *PrevSpec; |
2063 | unsigned DiagID; |
2064 | SourceLocation Loc = Tok.getLocation(); |
2065 | const clang::PrintingPolicy &Policy = |
2066 | Actions.getASTContext().getPrintingPolicy(); |
2067 | |
2068 | switch (Tok.getKind()) { |
2069 | case tok::identifier: // foo::bar |
2070 | case tok::coloncolon: // ::foo::bar |
2071 | llvm_unreachable("Annotation token should already be formed!" ); |
2072 | default: |
2073 | llvm_unreachable("Not a simple-type-specifier token!" ); |
2074 | |
2075 | // type-name |
2076 | case tok::annot_typename: { |
2077 | DS.SetTypeSpecType(T: DeclSpec::TST_typename, Loc, PrevSpec, DiagID, |
2078 | Rep: getTypeAnnotation(Tok), Policy); |
2079 | DS.SetRangeEnd(Tok.getAnnotationEndLoc()); |
2080 | ConsumeAnnotationToken(); |
2081 | DS.Finish(S&: Actions, Policy); |
2082 | return; |
2083 | } |
2084 | |
2085 | case tok::kw__ExtInt: |
2086 | case tok::kw__BitInt: { |
2087 | DiagnoseBitIntUse(Tok); |
2088 | ExprResult ER = ParseExtIntegerArgument(); |
2089 | if (ER.isInvalid()) |
2090 | DS.SetTypeSpecError(); |
2091 | else |
2092 | DS.SetBitIntType(KWLoc: Loc, BitWidth: ER.get(), PrevSpec, DiagID, Policy); |
2093 | |
2094 | // Do this here because we have already consumed the close paren. |
2095 | DS.SetRangeEnd(PrevTokLocation); |
2096 | DS.Finish(S&: Actions, Policy); |
2097 | return; |
2098 | } |
2099 | |
2100 | // builtin types |
2101 | case tok::kw_short: |
2102 | DS.SetTypeSpecWidth(W: TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID, |
2103 | Policy); |
2104 | break; |
2105 | case tok::kw_long: |
2106 | DS.SetTypeSpecWidth(W: TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID, |
2107 | Policy); |
2108 | break; |
2109 | case tok::kw___int64: |
2110 | DS.SetTypeSpecWidth(W: TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID, |
2111 | Policy); |
2112 | break; |
2113 | case tok::kw_signed: |
2114 | DS.SetTypeSpecSign(S: TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID); |
2115 | break; |
2116 | case tok::kw_unsigned: |
2117 | DS.SetTypeSpecSign(S: TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID); |
2118 | break; |
2119 | case tok::kw_void: |
2120 | DS.SetTypeSpecType(T: DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy); |
2121 | break; |
2122 | case tok::kw_auto: |
2123 | DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy); |
2124 | break; |
2125 | case tok::kw_char: |
2126 | DS.SetTypeSpecType(T: DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy); |
2127 | break; |
2128 | case tok::kw_int: |
2129 | DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy); |
2130 | break; |
2131 | case tok::kw___int128: |
2132 | DS.SetTypeSpecType(T: DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy); |
2133 | break; |
2134 | case tok::kw___bf16: |
2135 | DS.SetTypeSpecType(T: DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy); |
2136 | break; |
2137 | case tok::kw_half: |
2138 | DS.SetTypeSpecType(T: DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy); |
2139 | break; |
2140 | case tok::kw_float: |
2141 | DS.SetTypeSpecType(T: DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy); |
2142 | break; |
2143 | case tok::kw_double: |
2144 | DS.SetTypeSpecType(T: DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy); |
2145 | break; |
2146 | case tok::kw__Float16: |
2147 | DS.SetTypeSpecType(T: DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy); |
2148 | break; |
2149 | case tok::kw___float128: |
2150 | DS.SetTypeSpecType(T: DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy); |
2151 | break; |
2152 | case tok::kw___ibm128: |
2153 | DS.SetTypeSpecType(T: DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy); |
2154 | break; |
2155 | case tok::kw_wchar_t: |
2156 | DS.SetTypeSpecType(T: DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy); |
2157 | break; |
2158 | case tok::kw_char8_t: |
2159 | DS.SetTypeSpecType(T: DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy); |
2160 | break; |
2161 | case tok::kw_char16_t: |
2162 | DS.SetTypeSpecType(T: DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy); |
2163 | break; |
2164 | case tok::kw_char32_t: |
2165 | DS.SetTypeSpecType(T: DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy); |
2166 | break; |
2167 | case tok::kw_bool: |
2168 | DS.SetTypeSpecType(T: DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy); |
2169 | break; |
2170 | case tok::kw__Accum: |
2171 | DS.SetTypeSpecType(T: DeclSpec::TST_accum, Loc, PrevSpec, DiagID, Policy); |
2172 | break; |
2173 | case tok::kw__Fract: |
2174 | DS.SetTypeSpecType(T: DeclSpec::TST_fract, Loc, PrevSpec, DiagID, Policy); |
2175 | break; |
2176 | case tok::kw__Sat: |
2177 | DS.SetTypeSpecSat(Loc, PrevSpec, DiagID); |
2178 | break; |
2179 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ |
2180 | case tok::kw_##ImgType##_t: \ |
2181 | DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \ |
2182 | Policy); \ |
2183 | break; |
2184 | #include "clang/Basic/OpenCLImageTypes.def" |
2185 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \ |
2186 | case tok::kw_##Name: \ |
2187 | DS.SetTypeSpecType(DeclSpec::TST_##Name, Loc, PrevSpec, DiagID, Policy); \ |
2188 | break; |
2189 | #include "clang/Basic/HLSLIntangibleTypes.def" |
2190 | |
2191 | case tok::annot_decltype: |
2192 | case tok::kw_decltype: |
2193 | DS.SetRangeEnd(ParseDecltypeSpecifier(DS)); |
2194 | return DS.Finish(S&: Actions, Policy); |
2195 | |
2196 | case tok::annot_pack_indexing_type: |
2197 | DS.SetRangeEnd(ParsePackIndexingType(DS)); |
2198 | return DS.Finish(S&: Actions, Policy); |
2199 | |
2200 | // GNU typeof support. |
2201 | case tok::kw_typeof: |
2202 | ParseTypeofSpecifier(DS); |
2203 | DS.Finish(S&: Actions, Policy); |
2204 | return; |
2205 | } |
2206 | ConsumeAnyToken(); |
2207 | DS.SetRangeEnd(PrevTokLocation); |
2208 | DS.Finish(S&: Actions, Policy); |
2209 | } |
2210 | |
2211 | bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) { |
2212 | ParseSpecifierQualifierList(DS, AS: AS_none, |
2213 | DSC: getDeclSpecContextFromDeclaratorContext(Context)); |
2214 | DS.Finish(S&: Actions, Policy: Actions.getASTContext().getPrintingPolicy()); |
2215 | return false; |
2216 | } |
2217 | |
2218 | bool Parser::ParseUnqualifiedIdTemplateId( |
2219 | CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, |
2220 | SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, |
2221 | bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) { |
2222 | assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id" ); |
2223 | |
2224 | TemplateTy Template; |
2225 | TemplateNameKind TNK = TNK_Non_template; |
2226 | switch (Id.getKind()) { |
2227 | case UnqualifiedIdKind::IK_Identifier: |
2228 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
2229 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
2230 | if (AssumeTemplateId) { |
2231 | // We defer the injected-class-name checks until we've found whether |
2232 | // this template-id is used to form a nested-name-specifier or not. |
2233 | TNK = Actions.ActOnTemplateName(S: getCurScope(), SS, TemplateKWLoc, Name: Id, |
2234 | ObjectType, EnteringContext, Template, |
2235 | /*AllowInjectedClassName*/ true); |
2236 | } else { |
2237 | bool MemberOfUnknownSpecialization; |
2238 | TNK = Actions.isTemplateName(S: getCurScope(), SS, |
2239 | hasTemplateKeyword: TemplateKWLoc.isValid(), Name: Id, |
2240 | ObjectType, EnteringContext, Template, |
2241 | MemberOfUnknownSpecialization); |
2242 | // If lookup found nothing but we're assuming that this is a template |
2243 | // name, double-check that makes sense syntactically before committing |
2244 | // to it. |
2245 | if (TNK == TNK_Undeclared_template && |
2246 | isTemplateArgumentList(TokensToSkip: 0) == TPResult::False) |
2247 | return false; |
2248 | |
2249 | if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && |
2250 | ObjectType && isTemplateArgumentList(TokensToSkip: 0) == TPResult::True) { |
2251 | // If we had errors before, ObjectType can be dependent even without any |
2252 | // templates, do not report missing template keyword in that case. |
2253 | if (!ObjectHadErrors) { |
2254 | // We have something like t->getAs<T>(), where getAs is a |
2255 | // member of an unknown specialization. However, this will only |
2256 | // parse correctly as a template, so suggest the keyword 'template' |
2257 | // before 'getAs' and treat this as a dependent template name. |
2258 | std::string Name; |
2259 | if (Id.getKind() == UnqualifiedIdKind::IK_Identifier) |
2260 | Name = std::string(Id.Identifier->getName()); |
2261 | else { |
2262 | Name = "operator " ; |
2263 | if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) |
2264 | Name += getOperatorSpelling(Operator: Id.OperatorFunctionId.Operator); |
2265 | else |
2266 | Name += Id.Identifier->getName(); |
2267 | } |
2268 | Diag(Loc: Id.StartLocation, DiagID: diag::err_missing_dependent_template_keyword) |
2269 | << Name |
2270 | << FixItHint::CreateInsertion(InsertionLoc: Id.StartLocation, Code: "template " ); |
2271 | } |
2272 | TNK = Actions.ActOnTemplateName( |
2273 | S: getCurScope(), SS, TemplateKWLoc, Name: Id, ObjectType, EnteringContext, |
2274 | Template, /*AllowInjectedClassName*/ true); |
2275 | } else if (TNK == TNK_Non_template) { |
2276 | return false; |
2277 | } |
2278 | } |
2279 | break; |
2280 | |
2281 | case UnqualifiedIdKind::IK_ConstructorName: { |
2282 | UnqualifiedId TemplateName; |
2283 | bool MemberOfUnknownSpecialization; |
2284 | TemplateName.setIdentifier(Id: Name, IdLoc: NameLoc); |
2285 | TNK = Actions.isTemplateName(S: getCurScope(), SS, hasTemplateKeyword: TemplateKWLoc.isValid(), |
2286 | Name: TemplateName, ObjectType, |
2287 | EnteringContext, Template, |
2288 | MemberOfUnknownSpecialization); |
2289 | if (TNK == TNK_Non_template) |
2290 | return false; |
2291 | break; |
2292 | } |
2293 | |
2294 | case UnqualifiedIdKind::IK_DestructorName: { |
2295 | UnqualifiedId TemplateName; |
2296 | bool MemberOfUnknownSpecialization; |
2297 | TemplateName.setIdentifier(Id: Name, IdLoc: NameLoc); |
2298 | if (ObjectType) { |
2299 | TNK = Actions.ActOnTemplateName( |
2300 | S: getCurScope(), SS, TemplateKWLoc, Name: TemplateName, ObjectType, |
2301 | EnteringContext, Template, /*AllowInjectedClassName*/ true); |
2302 | } else { |
2303 | TNK = Actions.isTemplateName(S: getCurScope(), SS, hasTemplateKeyword: TemplateKWLoc.isValid(), |
2304 | Name: TemplateName, ObjectType, |
2305 | EnteringContext, Template, |
2306 | MemberOfUnknownSpecialization); |
2307 | |
2308 | if (TNK == TNK_Non_template && !Id.DestructorName.get()) { |
2309 | Diag(Loc: NameLoc, DiagID: diag::err_destructor_template_id) |
2310 | << Name << SS.getRange(); |
2311 | // Carry on to parse the template arguments before bailing out. |
2312 | } |
2313 | } |
2314 | break; |
2315 | } |
2316 | |
2317 | default: |
2318 | return false; |
2319 | } |
2320 | |
2321 | // Parse the enclosed template argument list. |
2322 | SourceLocation LAngleLoc, RAngleLoc; |
2323 | TemplateArgList TemplateArgs; |
2324 | if (ParseTemplateIdAfterTemplateName(ConsumeLastToken: true, LAngleLoc, TemplateArgs, RAngleLoc, |
2325 | NameHint: Template)) |
2326 | return true; |
2327 | |
2328 | // If this is a non-template, we already issued a diagnostic. |
2329 | if (TNK == TNK_Non_template) |
2330 | return true; |
2331 | |
2332 | if (Id.getKind() == UnqualifiedIdKind::IK_Identifier || |
2333 | Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId || |
2334 | Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) { |
2335 | // Form a parsed representation of the template-id to be stored in the |
2336 | // UnqualifiedId. |
2337 | |
2338 | // FIXME: Store name for literal operator too. |
2339 | const IdentifierInfo *TemplateII = |
2340 | Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier |
2341 | : nullptr; |
2342 | OverloadedOperatorKind OpKind = |
2343 | Id.getKind() == UnqualifiedIdKind::IK_Identifier |
2344 | ? OO_None |
2345 | : Id.OperatorFunctionId.Operator; |
2346 | |
2347 | TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create( |
2348 | TemplateKWLoc, TemplateNameLoc: Id.StartLocation, Name: TemplateII, OperatorKind: OpKind, OpaqueTemplateName: Template, TemplateKind: TNK, |
2349 | LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, CleanupList&: TemplateIds); |
2350 | |
2351 | Id.setTemplateId(TemplateId); |
2352 | return false; |
2353 | } |
2354 | |
2355 | // Bundle the template arguments together. |
2356 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs); |
2357 | |
2358 | // Constructor and destructor names. |
2359 | TypeResult Type = Actions.ActOnTemplateIdType( |
2360 | S: getCurScope(), SS, TemplateKWLoc, Template, TemplateII: Name, TemplateIILoc: NameLoc, LAngleLoc, |
2361 | TemplateArgs: TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true); |
2362 | if (Type.isInvalid()) |
2363 | return true; |
2364 | |
2365 | if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName) |
2366 | Id.setConstructorName(ClassType: Type.get(), ClassNameLoc: NameLoc, EndLoc: RAngleLoc); |
2367 | else |
2368 | Id.setDestructorName(TildeLoc: Id.StartLocation, ClassType: Type.get(), EndLoc: RAngleLoc); |
2369 | |
2370 | return false; |
2371 | } |
2372 | |
2373 | bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, |
2374 | ParsedType ObjectType, |
2375 | UnqualifiedId &Result) { |
2376 | assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword" ); |
2377 | |
2378 | // Consume the 'operator' keyword. |
2379 | SourceLocation KeywordLoc = ConsumeToken(); |
2380 | |
2381 | // Determine what kind of operator name we have. |
2382 | unsigned SymbolIdx = 0; |
2383 | SourceLocation SymbolLocations[3]; |
2384 | OverloadedOperatorKind Op = OO_None; |
2385 | switch (Tok.getKind()) { |
2386 | case tok::kw_new: |
2387 | case tok::kw_delete: { |
2388 | bool isNew = Tok.getKind() == tok::kw_new; |
2389 | // Consume the 'new' or 'delete'. |
2390 | SymbolLocations[SymbolIdx++] = ConsumeToken(); |
2391 | // Check for array new/delete. |
2392 | if (Tok.is(K: tok::l_square) && |
2393 | (!getLangOpts().CPlusPlus11 || NextToken().isNot(K: tok::l_square))) { |
2394 | // Consume the '[' and ']'. |
2395 | BalancedDelimiterTracker T(*this, tok::l_square); |
2396 | T.consumeOpen(); |
2397 | T.consumeClose(); |
2398 | if (T.getCloseLocation().isInvalid()) |
2399 | return true; |
2400 | |
2401 | SymbolLocations[SymbolIdx++] = T.getOpenLocation(); |
2402 | SymbolLocations[SymbolIdx++] = T.getCloseLocation(); |
2403 | Op = isNew? OO_Array_New : OO_Array_Delete; |
2404 | } else { |
2405 | Op = isNew? OO_New : OO_Delete; |
2406 | } |
2407 | break; |
2408 | } |
2409 | |
2410 | #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ |
2411 | case tok::Token: \ |
2412 | SymbolLocations[SymbolIdx++] = ConsumeToken(); \ |
2413 | Op = OO_##Name; \ |
2414 | break; |
2415 | #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) |
2416 | #include "clang/Basic/OperatorKinds.def" |
2417 | |
2418 | case tok::l_paren: { |
2419 | // Consume the '(' and ')'. |
2420 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2421 | T.consumeOpen(); |
2422 | T.consumeClose(); |
2423 | if (T.getCloseLocation().isInvalid()) |
2424 | return true; |
2425 | |
2426 | SymbolLocations[SymbolIdx++] = T.getOpenLocation(); |
2427 | SymbolLocations[SymbolIdx++] = T.getCloseLocation(); |
2428 | Op = OO_Call; |
2429 | break; |
2430 | } |
2431 | |
2432 | case tok::l_square: { |
2433 | // Consume the '[' and ']'. |
2434 | BalancedDelimiterTracker T(*this, tok::l_square); |
2435 | T.consumeOpen(); |
2436 | T.consumeClose(); |
2437 | if (T.getCloseLocation().isInvalid()) |
2438 | return true; |
2439 | |
2440 | SymbolLocations[SymbolIdx++] = T.getOpenLocation(); |
2441 | SymbolLocations[SymbolIdx++] = T.getCloseLocation(); |
2442 | Op = OO_Subscript; |
2443 | break; |
2444 | } |
2445 | |
2446 | case tok::code_completion: { |
2447 | // Don't try to parse any further. |
2448 | cutOffParsing(); |
2449 | // Code completion for the operator name. |
2450 | Actions.CodeCompletion().CodeCompleteOperatorName(S: getCurScope()); |
2451 | return true; |
2452 | } |
2453 | |
2454 | default: |
2455 | break; |
2456 | } |
2457 | |
2458 | if (Op != OO_None) { |
2459 | // We have parsed an operator-function-id. |
2460 | Result.setOperatorFunctionId(OperatorLoc: KeywordLoc, Op, SymbolLocations); |
2461 | return false; |
2462 | } |
2463 | |
2464 | // Parse a literal-operator-id. |
2465 | // |
2466 | // literal-operator-id: C++11 [over.literal] |
2467 | // operator string-literal identifier |
2468 | // operator user-defined-string-literal |
2469 | |
2470 | if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) { |
2471 | Diag(Loc: Tok.getLocation(), DiagID: diag::warn_cxx98_compat_literal_operator); |
2472 | |
2473 | SourceLocation DiagLoc; |
2474 | unsigned DiagId = 0; |
2475 | |
2476 | // We're past translation phase 6, so perform string literal concatenation |
2477 | // before checking for "". |
2478 | SmallVector<Token, 4> Toks; |
2479 | SmallVector<SourceLocation, 4> TokLocs; |
2480 | while (isTokenStringLiteral()) { |
2481 | if (!Tok.is(K: tok::string_literal) && !DiagId) { |
2482 | // C++11 [over.literal]p1: |
2483 | // The string-literal or user-defined-string-literal in a |
2484 | // literal-operator-id shall have no encoding-prefix [...]. |
2485 | DiagLoc = Tok.getLocation(); |
2486 | DiagId = diag::err_literal_operator_string_prefix; |
2487 | } |
2488 | Toks.push_back(Elt: Tok); |
2489 | TokLocs.push_back(Elt: ConsumeStringToken()); |
2490 | } |
2491 | |
2492 | StringLiteralParser Literal(Toks, PP); |
2493 | if (Literal.hadError) |
2494 | return true; |
2495 | |
2496 | // Grab the literal operator's suffix, which will be either the next token |
2497 | // or a ud-suffix from the string literal. |
2498 | bool IsUDSuffix = !Literal.getUDSuffix().empty(); |
2499 | IdentifierInfo *II = nullptr; |
2500 | SourceLocation SuffixLoc; |
2501 | if (IsUDSuffix) { |
2502 | II = &PP.getIdentifierTable().get(Name: Literal.getUDSuffix()); |
2503 | SuffixLoc = |
2504 | Lexer::AdvanceToTokenCharacter(TokStart: TokLocs[Literal.getUDSuffixToken()], |
2505 | Characters: Literal.getUDSuffixOffset(), |
2506 | SM: PP.getSourceManager(), LangOpts: getLangOpts()); |
2507 | } else if (Tok.is(K: tok::identifier)) { |
2508 | II = Tok.getIdentifierInfo(); |
2509 | SuffixLoc = ConsumeToken(); |
2510 | TokLocs.push_back(Elt: SuffixLoc); |
2511 | } else { |
2512 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected) << tok::identifier; |
2513 | return true; |
2514 | } |
2515 | |
2516 | // The string literal must be empty. |
2517 | if (!Literal.GetString().empty() || Literal.Pascal) { |
2518 | // C++11 [over.literal]p1: |
2519 | // The string-literal or user-defined-string-literal in a |
2520 | // literal-operator-id shall [...] contain no characters |
2521 | // other than the implicit terminating '\0'. |
2522 | DiagLoc = TokLocs.front(); |
2523 | DiagId = diag::err_literal_operator_string_not_empty; |
2524 | } |
2525 | |
2526 | if (DiagId) { |
2527 | // This isn't a valid literal-operator-id, but we think we know |
2528 | // what the user meant. Tell them what they should have written. |
2529 | SmallString<32> Str; |
2530 | Str += "\"\"" ; |
2531 | Str += II->getName(); |
2532 | Diag(Loc: DiagLoc, DiagID: DiagId) << FixItHint::CreateReplacement( |
2533 | RemoveRange: SourceRange(TokLocs.front(), TokLocs.back()), Code: Str); |
2534 | } |
2535 | |
2536 | Result.setLiteralOperatorId(Id: II, OpLoc: KeywordLoc, IdLoc: SuffixLoc); |
2537 | |
2538 | return Actions.checkLiteralOperatorId(SS, Id: Result, IsUDSuffix); |
2539 | } |
2540 | |
2541 | // Parse a conversion-function-id. |
2542 | // |
2543 | // conversion-function-id: [C++ 12.3.2] |
2544 | // operator conversion-type-id |
2545 | // |
2546 | // conversion-type-id: |
2547 | // type-specifier-seq conversion-declarator[opt] |
2548 | // |
2549 | // conversion-declarator: |
2550 | // ptr-operator conversion-declarator[opt] |
2551 | |
2552 | // Parse the type-specifier-seq. |
2553 | DeclSpec DS(AttrFactory); |
2554 | if (ParseCXXTypeSpecifierSeq( |
2555 | DS, Context: DeclaratorContext::ConversionId)) // FIXME: ObjectType? |
2556 | return true; |
2557 | |
2558 | // Parse the conversion-declarator, which is merely a sequence of |
2559 | // ptr-operators. |
2560 | Declarator D(DS, ParsedAttributesView::none(), |
2561 | DeclaratorContext::ConversionId); |
2562 | ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr); |
2563 | |
2564 | // Finish up the type. |
2565 | TypeResult Ty = Actions.ActOnTypeName(D); |
2566 | if (Ty.isInvalid()) |
2567 | return true; |
2568 | |
2569 | // Note that this is a conversion-function-id. |
2570 | Result.setConversionFunctionId(OperatorLoc: KeywordLoc, Ty: Ty.get(), |
2571 | EndLoc: D.getSourceRange().getEnd()); |
2572 | return false; |
2573 | } |
2574 | |
2575 | bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, |
2576 | bool ObjectHadErrors, bool EnteringContext, |
2577 | bool AllowDestructorName, |
2578 | bool AllowConstructorName, |
2579 | bool AllowDeductionGuide, |
2580 | SourceLocation *TemplateKWLoc, |
2581 | UnqualifiedId &Result) { |
2582 | if (TemplateKWLoc) |
2583 | *TemplateKWLoc = SourceLocation(); |
2584 | |
2585 | // Handle 'A::template B'. This is for template-ids which have not |
2586 | // already been annotated by ParseOptionalCXXScopeSpecifier(). |
2587 | bool TemplateSpecified = false; |
2588 | if (Tok.is(K: tok::kw_template)) { |
2589 | if (TemplateKWLoc && (ObjectType || SS.isSet())) { |
2590 | TemplateSpecified = true; |
2591 | *TemplateKWLoc = ConsumeToken(); |
2592 | } else { |
2593 | SourceLocation TemplateLoc = ConsumeToken(); |
2594 | Diag(Loc: TemplateLoc, DiagID: diag::err_unexpected_template_in_unqualified_id) |
2595 | << FixItHint::CreateRemoval(RemoveRange: TemplateLoc); |
2596 | } |
2597 | } |
2598 | |
2599 | // unqualified-id: |
2600 | // identifier |
2601 | // template-id (when it hasn't already been annotated) |
2602 | if (Tok.is(K: tok::identifier)) { |
2603 | ParseIdentifier: |
2604 | // Consume the identifier. |
2605 | IdentifierInfo *Id = Tok.getIdentifierInfo(); |
2606 | SourceLocation IdLoc = ConsumeToken(); |
2607 | |
2608 | if (!getLangOpts().CPlusPlus) { |
2609 | // If we're not in C++, only identifiers matter. Record the |
2610 | // identifier and return. |
2611 | Result.setIdentifier(Id, IdLoc); |
2612 | return false; |
2613 | } |
2614 | |
2615 | ParsedTemplateTy TemplateName; |
2616 | if (AllowConstructorName && |
2617 | Actions.isCurrentClassName(II: *Id, S: getCurScope(), SS: &SS)) { |
2618 | // We have parsed a constructor name. |
2619 | ParsedType Ty = Actions.getConstructorName(II: *Id, NameLoc: IdLoc, S: getCurScope(), SS, |
2620 | EnteringContext); |
2621 | if (!Ty) |
2622 | return true; |
2623 | Result.setConstructorName(ClassType: Ty, ClassNameLoc: IdLoc, EndLoc: IdLoc); |
2624 | } else if (getLangOpts().CPlusPlus17 && AllowDeductionGuide && |
2625 | SS.isEmpty() && |
2626 | Actions.isDeductionGuideName(S: getCurScope(), Name: *Id, NameLoc: IdLoc, SS, |
2627 | Template: &TemplateName)) { |
2628 | // We have parsed a template-name naming a deduction guide. |
2629 | Result.setDeductionGuideName(Template: TemplateName, TemplateLoc: IdLoc); |
2630 | } else { |
2631 | // We have parsed an identifier. |
2632 | Result.setIdentifier(Id, IdLoc); |
2633 | } |
2634 | |
2635 | // If the next token is a '<', we may have a template. |
2636 | TemplateTy Template; |
2637 | if (Tok.is(K: tok::less)) |
2638 | return ParseUnqualifiedIdTemplateId( |
2639 | SS, ObjectType, ObjectHadErrors, |
2640 | TemplateKWLoc: TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Name: Id, NameLoc: IdLoc, |
2641 | EnteringContext, Id&: Result, AssumeTemplateId: TemplateSpecified); |
2642 | |
2643 | if (TemplateSpecified) { |
2644 | TemplateNameKind TNK = |
2645 | Actions.ActOnTemplateName(S: getCurScope(), SS, TemplateKWLoc: *TemplateKWLoc, Name: Result, |
2646 | ObjectType, EnteringContext, Template, |
2647 | /*AllowInjectedClassName=*/true); |
2648 | if (TNK == TNK_Non_template) |
2649 | return true; |
2650 | |
2651 | // C++2c [tem.names]p6 |
2652 | // A name prefixed by the keyword template shall be followed by a template |
2653 | // argument list or refer to a class template or an alias template. |
2654 | if ((TNK == TNK_Function_template || TNK == TNK_Dependent_template_name || |
2655 | TNK == TNK_Var_template) && |
2656 | !Tok.is(K: tok::less)) |
2657 | Diag(Loc: IdLoc, DiagID: diag::missing_template_arg_list_after_template_kw); |
2658 | } |
2659 | return false; |
2660 | } |
2661 | |
2662 | // unqualified-id: |
2663 | // template-id (already parsed and annotated) |
2664 | if (Tok.is(K: tok::annot_template_id)) { |
2665 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok); |
2666 | |
2667 | // FIXME: Consider passing invalid template-ids on to callers; they may |
2668 | // be able to recover better than we can. |
2669 | if (TemplateId->isInvalid()) { |
2670 | ConsumeAnnotationToken(); |
2671 | return true; |
2672 | } |
2673 | |
2674 | // If the template-name names the current class, then this is a constructor |
2675 | if (AllowConstructorName && TemplateId->Name && |
2676 | Actions.isCurrentClassName(II: *TemplateId->Name, S: getCurScope(), SS: &SS)) { |
2677 | if (SS.isSet()) { |
2678 | // C++ [class.qual]p2 specifies that a qualified template-name |
2679 | // is taken as the constructor name where a constructor can be |
2680 | // declared. Thus, the template arguments are extraneous, so |
2681 | // complain about them and remove them entirely. |
2682 | Diag(Loc: TemplateId->TemplateNameLoc, |
2683 | DiagID: diag::err_out_of_line_constructor_template_id) |
2684 | << TemplateId->Name |
2685 | << FixItHint::CreateRemoval( |
2686 | RemoveRange: SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); |
2687 | ParsedType Ty = Actions.getConstructorName( |
2688 | II: *TemplateId->Name, NameLoc: TemplateId->TemplateNameLoc, S: getCurScope(), SS, |
2689 | EnteringContext); |
2690 | if (!Ty) |
2691 | return true; |
2692 | Result.setConstructorName(ClassType: Ty, ClassNameLoc: TemplateId->TemplateNameLoc, |
2693 | EndLoc: TemplateId->RAngleLoc); |
2694 | ConsumeAnnotationToken(); |
2695 | return false; |
2696 | } |
2697 | |
2698 | Result.setConstructorTemplateId(TemplateId); |
2699 | ConsumeAnnotationToken(); |
2700 | return false; |
2701 | } |
2702 | |
2703 | // We have already parsed a template-id; consume the annotation token as |
2704 | // our unqualified-id. |
2705 | Result.setTemplateId(TemplateId); |
2706 | SourceLocation TemplateLoc = TemplateId->TemplateKWLoc; |
2707 | if (TemplateLoc.isValid()) { |
2708 | if (TemplateKWLoc && (ObjectType || SS.isSet())) |
2709 | *TemplateKWLoc = TemplateLoc; |
2710 | else |
2711 | Diag(Loc: TemplateLoc, DiagID: diag::err_unexpected_template_in_unqualified_id) |
2712 | << FixItHint::CreateRemoval(RemoveRange: TemplateLoc); |
2713 | } |
2714 | ConsumeAnnotationToken(); |
2715 | return false; |
2716 | } |
2717 | |
2718 | // unqualified-id: |
2719 | // operator-function-id |
2720 | // conversion-function-id |
2721 | if (Tok.is(K: tok::kw_operator)) { |
2722 | if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) |
2723 | return true; |
2724 | |
2725 | // If we have an operator-function-id or a literal-operator-id and the next |
2726 | // token is a '<', we may have a |
2727 | // |
2728 | // template-id: |
2729 | // operator-function-id < template-argument-list[opt] > |
2730 | TemplateTy Template; |
2731 | if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId || |
2732 | Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) && |
2733 | Tok.is(K: tok::less)) |
2734 | return ParseUnqualifiedIdTemplateId( |
2735 | SS, ObjectType, ObjectHadErrors, |
2736 | TemplateKWLoc: TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Name: nullptr, |
2737 | NameLoc: SourceLocation(), EnteringContext, Id&: Result, AssumeTemplateId: TemplateSpecified); |
2738 | else if (TemplateSpecified && |
2739 | Actions.ActOnTemplateName( |
2740 | S: getCurScope(), SS, TemplateKWLoc: *TemplateKWLoc, Name: Result, ObjectType, |
2741 | EnteringContext, Template, |
2742 | /*AllowInjectedClassName*/ true) == TNK_Non_template) |
2743 | return true; |
2744 | |
2745 | return false; |
2746 | } |
2747 | |
2748 | if (getLangOpts().CPlusPlus && |
2749 | (AllowDestructorName || SS.isSet()) && Tok.is(K: tok::tilde)) { |
2750 | // C++ [expr.unary.op]p10: |
2751 | // There is an ambiguity in the unary-expression ~X(), where X is a |
2752 | // class-name. The ambiguity is resolved in favor of treating ~ as a |
2753 | // unary complement rather than treating ~X as referring to a destructor. |
2754 | |
2755 | // Parse the '~'. |
2756 | SourceLocation TildeLoc = ConsumeToken(); |
2757 | |
2758 | if (TemplateSpecified) { |
2759 | // C++ [temp.names]p3: |
2760 | // A name prefixed by the keyword template shall be a template-id [...] |
2761 | // |
2762 | // A template-id cannot begin with a '~' token. This would never work |
2763 | // anyway: x.~A<int>() would specify that the destructor is a template, |
2764 | // not that 'A' is a template. |
2765 | // |
2766 | // FIXME: Suggest replacing the attempted destructor name with a correct |
2767 | // destructor name and recover. (This is not trivial if this would become |
2768 | // a pseudo-destructor name). |
2769 | Diag(Loc: *TemplateKWLoc, DiagID: diag::err_unexpected_template_in_destructor_name) |
2770 | << Tok.getLocation(); |
2771 | return true; |
2772 | } |
2773 | |
2774 | if (SS.isEmpty() && Tok.is(K: tok::kw_decltype)) { |
2775 | DeclSpec DS(AttrFactory); |
2776 | SourceLocation EndLoc = ParseDecltypeSpecifier(DS); |
2777 | if (ParsedType Type = |
2778 | Actions.getDestructorTypeForDecltype(DS, ObjectType)) { |
2779 | Result.setDestructorName(TildeLoc, ClassType: Type, EndLoc); |
2780 | return false; |
2781 | } |
2782 | return true; |
2783 | } |
2784 | |
2785 | // Parse the class-name. |
2786 | if (Tok.isNot(K: tok::identifier)) { |
2787 | Diag(Tok, DiagID: diag::err_destructor_tilde_identifier); |
2788 | return true; |
2789 | } |
2790 | |
2791 | // If the user wrote ~T::T, correct it to T::~T. |
2792 | DeclaratorScopeObj DeclScopeObj(*this, SS); |
2793 | if (NextToken().is(K: tok::coloncolon)) { |
2794 | // Don't let ParseOptionalCXXScopeSpecifier() "correct" |
2795 | // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`, |
2796 | // it will confuse this recovery logic. |
2797 | ColonProtectionRAIIObject ColonRAII(*this, false); |
2798 | |
2799 | if (SS.isSet()) { |
2800 | AnnotateScopeToken(SS, /*NewAnnotation*/IsNewAnnotation: true); |
2801 | SS.clear(); |
2802 | } |
2803 | if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors, |
2804 | EnteringContext)) |
2805 | return true; |
2806 | if (SS.isNotEmpty()) |
2807 | ObjectType = nullptr; |
2808 | if (Tok.isNot(K: tok::identifier) || NextToken().is(K: tok::coloncolon) || |
2809 | !SS.isSet()) { |
2810 | Diag(Loc: TildeLoc, DiagID: diag::err_destructor_tilde_scope); |
2811 | return true; |
2812 | } |
2813 | |
2814 | // Recover as if the tilde had been written before the identifier. |
2815 | Diag(Loc: TildeLoc, DiagID: diag::err_destructor_tilde_scope) |
2816 | << FixItHint::CreateRemoval(RemoveRange: TildeLoc) |
2817 | << FixItHint::CreateInsertion(InsertionLoc: Tok.getLocation(), Code: "~" ); |
2818 | |
2819 | // Temporarily enter the scope for the rest of this function. |
2820 | if (Actions.ShouldEnterDeclaratorScope(S: getCurScope(), SS)) |
2821 | DeclScopeObj.EnterDeclaratorScope(); |
2822 | } |
2823 | |
2824 | // Parse the class-name (or template-name in a simple-template-id). |
2825 | IdentifierInfo *ClassName = Tok.getIdentifierInfo(); |
2826 | SourceLocation ClassNameLoc = ConsumeToken(); |
2827 | |
2828 | if (Tok.is(K: tok::less)) { |
2829 | Result.setDestructorName(TildeLoc, ClassType: nullptr, EndLoc: ClassNameLoc); |
2830 | return ParseUnqualifiedIdTemplateId( |
2831 | SS, ObjectType, ObjectHadErrors, |
2832 | TemplateKWLoc: TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Name: ClassName, |
2833 | NameLoc: ClassNameLoc, EnteringContext, Id&: Result, AssumeTemplateId: TemplateSpecified); |
2834 | } |
2835 | |
2836 | // Note that this is a destructor name. |
2837 | ParsedType Ty = |
2838 | Actions.getDestructorName(II: *ClassName, NameLoc: ClassNameLoc, S: getCurScope(), SS, |
2839 | ObjectType, EnteringContext); |
2840 | if (!Ty) |
2841 | return true; |
2842 | |
2843 | Result.setDestructorName(TildeLoc, ClassType: Ty, EndLoc: ClassNameLoc); |
2844 | return false; |
2845 | } |
2846 | |
2847 | switch (Tok.getKind()) { |
2848 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: |
2849 | #include "clang/Basic/TransformTypeTraits.def" |
2850 | if (!NextToken().is(K: tok::l_paren)) { |
2851 | Tok.setKind(tok::identifier); |
2852 | Diag(Tok, DiagID: diag::ext_keyword_as_ident) |
2853 | << Tok.getIdentifierInfo()->getName() << 0; |
2854 | goto ParseIdentifier; |
2855 | } |
2856 | [[fallthrough]]; |
2857 | default: |
2858 | Diag(Tok, DiagID: diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; |
2859 | return true; |
2860 | } |
2861 | } |
2862 | |
2863 | ExprResult |
2864 | Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { |
2865 | assert(Tok.is(tok::kw_new) && "expected 'new' token" ); |
2866 | ConsumeToken(); // Consume 'new' |
2867 | |
2868 | // A '(' now can be a new-placement or the '(' wrapping the type-id in the |
2869 | // second form of new-expression. It can't be a new-type-id. |
2870 | |
2871 | ExprVector PlacementArgs; |
2872 | SourceLocation PlacementLParen, PlacementRParen; |
2873 | |
2874 | SourceRange TypeIdParens; |
2875 | DeclSpec DS(AttrFactory); |
2876 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
2877 | DeclaratorContext::CXXNew); |
2878 | if (Tok.is(K: tok::l_paren)) { |
2879 | // If it turns out to be a placement, we change the type location. |
2880 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2881 | T.consumeOpen(); |
2882 | PlacementLParen = T.getOpenLocation(); |
2883 | if (ParseExpressionListOrTypeId(Exprs&: PlacementArgs, D&: DeclaratorInfo)) { |
2884 | SkipUntil(T: tok::semi, Flags: StopAtSemi | StopBeforeMatch); |
2885 | return ExprError(); |
2886 | } |
2887 | |
2888 | T.consumeClose(); |
2889 | PlacementRParen = T.getCloseLocation(); |
2890 | if (PlacementRParen.isInvalid()) { |
2891 | SkipUntil(T: tok::semi, Flags: StopAtSemi | StopBeforeMatch); |
2892 | return ExprError(); |
2893 | } |
2894 | |
2895 | if (PlacementArgs.empty()) { |
2896 | // Reset the placement locations. There was no placement. |
2897 | TypeIdParens = T.getRange(); |
2898 | PlacementLParen = PlacementRParen = SourceLocation(); |
2899 | } else { |
2900 | // We still need the type. |
2901 | if (Tok.is(K: tok::l_paren)) { |
2902 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2903 | T.consumeOpen(); |
2904 | MaybeParseGNUAttributes(D&: DeclaratorInfo); |
2905 | ParseSpecifierQualifierList(DS); |
2906 | DeclaratorInfo.SetSourceRange(DS.getSourceRange()); |
2907 | ParseDeclarator(D&: DeclaratorInfo); |
2908 | T.consumeClose(); |
2909 | TypeIdParens = T.getRange(); |
2910 | } else { |
2911 | MaybeParseGNUAttributes(D&: DeclaratorInfo); |
2912 | if (ParseCXXTypeSpecifierSeq(DS)) |
2913 | DeclaratorInfo.setInvalidType(true); |
2914 | else { |
2915 | DeclaratorInfo.SetSourceRange(DS.getSourceRange()); |
2916 | ParseDeclaratorInternal(D&: DeclaratorInfo, |
2917 | DirectDeclParser: &Parser::ParseDirectNewDeclarator); |
2918 | } |
2919 | } |
2920 | } |
2921 | } else { |
2922 | // A new-type-id is a simplified type-id, where essentially the |
2923 | // direct-declarator is replaced by a direct-new-declarator. |
2924 | MaybeParseGNUAttributes(D&: DeclaratorInfo); |
2925 | if (ParseCXXTypeSpecifierSeq(DS, Context: DeclaratorContext::CXXNew)) |
2926 | DeclaratorInfo.setInvalidType(true); |
2927 | else { |
2928 | DeclaratorInfo.SetSourceRange(DS.getSourceRange()); |
2929 | ParseDeclaratorInternal(D&: DeclaratorInfo, |
2930 | DirectDeclParser: &Parser::ParseDirectNewDeclarator); |
2931 | } |
2932 | } |
2933 | if (DeclaratorInfo.isInvalidType()) { |
2934 | SkipUntil(T: tok::semi, Flags: StopAtSemi | StopBeforeMatch); |
2935 | return ExprError(); |
2936 | } |
2937 | |
2938 | ExprResult Initializer; |
2939 | |
2940 | if (Tok.is(K: tok::l_paren)) { |
2941 | SourceLocation ConstructorLParen, ConstructorRParen; |
2942 | ExprVector ConstructorArgs; |
2943 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2944 | T.consumeOpen(); |
2945 | ConstructorLParen = T.getOpenLocation(); |
2946 | if (Tok.isNot(K: tok::r_paren)) { |
2947 | auto RunSignatureHelp = [&]() { |
2948 | ParsedType TypeRep = Actions.ActOnTypeName(D&: DeclaratorInfo).get(); |
2949 | QualType PreferredType; |
2950 | // ActOnTypeName might adjust DeclaratorInfo and return a null type even |
2951 | // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on |
2952 | // `new decltype(invalid) (^)`. |
2953 | if (TypeRep) |
2954 | PreferredType = |
2955 | Actions.CodeCompletion().ProduceConstructorSignatureHelp( |
2956 | Type: TypeRep.get()->getCanonicalTypeInternal(), |
2957 | Loc: DeclaratorInfo.getEndLoc(), Args: ConstructorArgs, |
2958 | OpenParLoc: ConstructorLParen, |
2959 | /*Braced=*/false); |
2960 | CalledSignatureHelp = true; |
2961 | return PreferredType; |
2962 | }; |
2963 | if (ParseExpressionList(Exprs&: ConstructorArgs, ExpressionStarts: [&] { |
2964 | PreferredType.enterFunctionArgument(Tok: Tok.getLocation(), |
2965 | ComputeType: RunSignatureHelp); |
2966 | })) { |
2967 | if (PP.isCodeCompletionReached() && !CalledSignatureHelp) |
2968 | RunSignatureHelp(); |
2969 | SkipUntil(T: tok::semi, Flags: StopAtSemi | StopBeforeMatch); |
2970 | return ExprError(); |
2971 | } |
2972 | } |
2973 | T.consumeClose(); |
2974 | ConstructorRParen = T.getCloseLocation(); |
2975 | if (ConstructorRParen.isInvalid()) { |
2976 | SkipUntil(T: tok::semi, Flags: StopAtSemi | StopBeforeMatch); |
2977 | return ExprError(); |
2978 | } |
2979 | Initializer = Actions.ActOnParenListExpr(L: ConstructorLParen, |
2980 | R: ConstructorRParen, |
2981 | Val: ConstructorArgs); |
2982 | } else if (Tok.is(K: tok::l_brace) && getLangOpts().CPlusPlus11) { |
2983 | Diag(Loc: Tok.getLocation(), |
2984 | DiagID: diag::warn_cxx98_compat_generalized_initializer_lists); |
2985 | Initializer = ParseBraceInitializer(); |
2986 | } |
2987 | if (Initializer.isInvalid()) |
2988 | return Initializer; |
2989 | |
2990 | return Actions.ActOnCXXNew(StartLoc: Start, UseGlobal, PlacementLParen, |
2991 | PlacementArgs, PlacementRParen, |
2992 | TypeIdParens, D&: DeclaratorInfo, Initializer: Initializer.get()); |
2993 | } |
2994 | |
2995 | void Parser::ParseDirectNewDeclarator(Declarator &D) { |
2996 | // Parse the array dimensions. |
2997 | bool First = true; |
2998 | while (Tok.is(K: tok::l_square)) { |
2999 | // An array-size expression can't start with a lambda. |
3000 | if (CheckProhibitedCXX11Attribute()) |
3001 | continue; |
3002 | |
3003 | BalancedDelimiterTracker T(*this, tok::l_square); |
3004 | T.consumeOpen(); |
3005 | |
3006 | ExprResult Size = |
3007 | First ? (Tok.is(K: tok::r_square) ? ExprResult() : ParseExpression()) |
3008 | : ParseConstantExpression(); |
3009 | if (Size.isInvalid()) { |
3010 | // Recover |
3011 | SkipUntil(T: tok::r_square, Flags: StopAtSemi); |
3012 | return; |
3013 | } |
3014 | First = false; |
3015 | |
3016 | T.consumeClose(); |
3017 | |
3018 | // Attributes here appertain to the array type. C++11 [expr.new]p5. |
3019 | ParsedAttributes Attrs(AttrFactory); |
3020 | MaybeParseCXX11Attributes(Attrs); |
3021 | |
3022 | D.AddTypeInfo(TI: DeclaratorChunk::getArray(TypeQuals: 0, |
3023 | /*isStatic=*/false, /*isStar=*/false, |
3024 | NumElts: Size.get(), LBLoc: T.getOpenLocation(), |
3025 | RBLoc: T.getCloseLocation()), |
3026 | attrs: std::move(Attrs), EndLoc: T.getCloseLocation()); |
3027 | |
3028 | if (T.getCloseLocation().isInvalid()) |
3029 | return; |
3030 | } |
3031 | } |
3032 | |
3033 | bool Parser::ParseExpressionListOrTypeId( |
3034 | SmallVectorImpl<Expr*> &PlacementArgs, |
3035 | Declarator &D) { |
3036 | // The '(' was already consumed. |
3037 | if (isTypeIdInParens()) { |
3038 | ParseSpecifierQualifierList(DS&: D.getMutableDeclSpec()); |
3039 | D.SetSourceRange(D.getDeclSpec().getSourceRange()); |
3040 | ParseDeclarator(D); |
3041 | return D.isInvalidType(); |
3042 | } |
3043 | |
3044 | // It's not a type, it has to be an expression list. |
3045 | return ParseExpressionList(Exprs&: PlacementArgs); |
3046 | } |
3047 | |
3048 | ExprResult |
3049 | Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { |
3050 | assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword" ); |
3051 | ConsumeToken(); // Consume 'delete' |
3052 | |
3053 | // Array delete? |
3054 | bool ArrayDelete = false; |
3055 | if (Tok.is(K: tok::l_square) && NextToken().is(K: tok::r_square)) { |
3056 | // C++11 [expr.delete]p1: |
3057 | // Whenever the delete keyword is followed by empty square brackets, it |
3058 | // shall be interpreted as [array delete]. |
3059 | // [Footnote: A lambda expression with a lambda-introducer that consists |
3060 | // of empty square brackets can follow the delete keyword if |
3061 | // the lambda expression is enclosed in parentheses.] |
3062 | |
3063 | const Token Next = GetLookAheadToken(N: 2); |
3064 | |
3065 | // Basic lookahead to check if we have a lambda expression. |
3066 | if (Next.isOneOf(Ks: tok::l_brace, Ks: tok::less) || |
3067 | (Next.is(K: tok::l_paren) && |
3068 | (GetLookAheadToken(N: 3).is(K: tok::r_paren) || |
3069 | (GetLookAheadToken(N: 3).is(K: tok::identifier) && |
3070 | GetLookAheadToken(N: 4).is(K: tok::identifier))))) { |
3071 | TentativeParsingAction TPA(*this); |
3072 | SourceLocation LSquareLoc = Tok.getLocation(); |
3073 | SourceLocation RSquareLoc = NextToken().getLocation(); |
3074 | |
3075 | // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this |
3076 | // case. |
3077 | SkipUntil(Toks: {tok::l_brace, tok::less}, Flags: StopBeforeMatch); |
3078 | SourceLocation RBraceLoc; |
3079 | bool EmitFixIt = false; |
3080 | if (Tok.is(K: tok::l_brace)) { |
3081 | ConsumeBrace(); |
3082 | SkipUntil(T: tok::r_brace, Flags: StopBeforeMatch); |
3083 | RBraceLoc = Tok.getLocation(); |
3084 | EmitFixIt = true; |
3085 | } |
3086 | |
3087 | TPA.Revert(); |
3088 | |
3089 | if (EmitFixIt) |
3090 | Diag(Loc: Start, DiagID: diag::err_lambda_after_delete) |
3091 | << SourceRange(Start, RSquareLoc) |
3092 | << FixItHint::CreateInsertion(InsertionLoc: LSquareLoc, Code: "(" ) |
3093 | << FixItHint::CreateInsertion( |
3094 | InsertionLoc: Lexer::getLocForEndOfToken( |
3095 | Loc: RBraceLoc, Offset: 0, SM: Actions.getSourceManager(), LangOpts: getLangOpts()), |
3096 | Code: ")" ); |
3097 | else |
3098 | Diag(Loc: Start, DiagID: diag::err_lambda_after_delete) |
3099 | << SourceRange(Start, RSquareLoc); |
3100 | |
3101 | // Warn that the non-capturing lambda isn't surrounded by parentheses |
3102 | // to disambiguate it from 'delete[]'. |
3103 | ExprResult Lambda = ParseLambdaExpression(); |
3104 | if (Lambda.isInvalid()) |
3105 | return ExprError(); |
3106 | |
3107 | // Evaluate any postfix expressions used on the lambda. |
3108 | Lambda = ParsePostfixExpressionSuffix(LHS: Lambda); |
3109 | if (Lambda.isInvalid()) |
3110 | return ExprError(); |
3111 | return Actions.ActOnCXXDelete(StartLoc: Start, UseGlobal, /*ArrayForm=*/false, |
3112 | Operand: Lambda.get()); |
3113 | } |
3114 | |
3115 | ArrayDelete = true; |
3116 | BalancedDelimiterTracker T(*this, tok::l_square); |
3117 | |
3118 | T.consumeOpen(); |
3119 | T.consumeClose(); |
3120 | if (T.getCloseLocation().isInvalid()) |
3121 | return ExprError(); |
3122 | } |
3123 | |
3124 | ExprResult Operand(ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr)); |
3125 | if (Operand.isInvalid()) |
3126 | return Operand; |
3127 | |
3128 | return Actions.ActOnCXXDelete(StartLoc: Start, UseGlobal, ArrayForm: ArrayDelete, Operand: Operand.get()); |
3129 | } |
3130 | |
3131 | ExprResult Parser::ParseRequiresExpression() { |
3132 | assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword" ); |
3133 | SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires' |
3134 | |
3135 | llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls; |
3136 | BalancedDelimiterTracker Parens(*this, tok::l_paren); |
3137 | if (Tok.is(K: tok::l_paren)) { |
3138 | // requirement parameter list is present. |
3139 | ParseScope (this, Scope::FunctionPrototypeScope | |
3140 | Scope::DeclScope); |
3141 | Parens.consumeOpen(); |
3142 | if (!Tok.is(K: tok::r_paren)) { |
3143 | ParsedAttributes FirstArgAttrs(getAttrFactory()); |
3144 | SourceLocation EllipsisLoc; |
3145 | llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters; |
3146 | ParseParameterDeclarationClause(DeclaratorContext: DeclaratorContext::RequiresExpr, |
3147 | attrs&: FirstArgAttrs, ParamInfo&: LocalParameters, |
3148 | EllipsisLoc); |
3149 | if (EllipsisLoc.isValid()) |
3150 | Diag(Loc: EllipsisLoc, DiagID: diag::err_requires_expr_parameter_list_ellipsis); |
3151 | for (auto &ParamInfo : LocalParameters) |
3152 | LocalParameterDecls.push_back(Elt: cast<ParmVarDecl>(Val: ParamInfo.Param)); |
3153 | } |
3154 | Parens.consumeClose(); |
3155 | } |
3156 | |
3157 | BalancedDelimiterTracker Braces(*this, tok::l_brace); |
3158 | if (Braces.expectAndConsume()) |
3159 | return ExprError(); |
3160 | |
3161 | // Start of requirement list |
3162 | llvm::SmallVector<concepts::Requirement *, 2> Requirements; |
3163 | |
3164 | // C++2a [expr.prim.req]p2 |
3165 | // Expressions appearing within a requirement-body are unevaluated operands. |
3166 | EnterExpressionEvaluationContext Ctx( |
3167 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); |
3168 | |
3169 | ParseScope BodyScope(this, Scope::DeclScope); |
3170 | // Create a separate diagnostic pool for RequiresExprBodyDecl. |
3171 | // Dependent diagnostics are attached to this Decl and non-depenedent |
3172 | // diagnostics are surfaced after this parse. |
3173 | ParsingDeclRAIIObject ParsingBodyDecl(*this, ParsingDeclRAIIObject::NoParent); |
3174 | RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr( |
3175 | RequiresKWLoc, LocalParameters: LocalParameterDecls, BodyScope: getCurScope()); |
3176 | |
3177 | if (Tok.is(K: tok::r_brace)) { |
3178 | // Grammar does not allow an empty body. |
3179 | // requirement-body: |
3180 | // { requirement-seq } |
3181 | // requirement-seq: |
3182 | // requirement |
3183 | // requirement-seq requirement |
3184 | Diag(Tok, DiagID: diag::err_empty_requires_expr); |
3185 | // Continue anyway and produce a requires expr with no requirements. |
3186 | } else { |
3187 | while (!Tok.is(K: tok::r_brace)) { |
3188 | switch (Tok.getKind()) { |
3189 | case tok::l_brace: { |
3190 | // Compound requirement |
3191 | // C++ [expr.prim.req.compound] |
3192 | // compound-requirement: |
3193 | // '{' expression '}' 'noexcept'[opt] |
3194 | // return-type-requirement[opt] ';' |
3195 | // return-type-requirement: |
3196 | // trailing-return-type |
3197 | // '->' cv-qualifier-seq[opt] constrained-parameter |
3198 | // cv-qualifier-seq[opt] abstract-declarator[opt] |
3199 | BalancedDelimiterTracker ExprBraces(*this, tok::l_brace); |
3200 | ExprBraces.consumeOpen(); |
3201 | ExprResult Expression = ParseExpression(); |
3202 | if (!Expression.isUsable()) { |
3203 | ExprBraces.skipToEnd(); |
3204 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3205 | break; |
3206 | } |
3207 | // If there's an error consuming the closing bracket, consumeClose() |
3208 | // will handle skipping to the nearest recovery point for us. |
3209 | if (ExprBraces.consumeClose()) |
3210 | break; |
3211 | |
3212 | concepts::Requirement *Req = nullptr; |
3213 | SourceLocation NoexceptLoc; |
3214 | TryConsumeToken(Expected: tok::kw_noexcept, Loc&: NoexceptLoc); |
3215 | if (Tok.is(K: tok::semi)) { |
3216 | Req = Actions.ActOnCompoundRequirement(E: Expression.get(), NoexceptLoc); |
3217 | if (Req) |
3218 | Requirements.push_back(Elt: Req); |
3219 | break; |
3220 | } |
3221 | if (!TryConsumeToken(Expected: tok::arrow)) |
3222 | // User probably forgot the arrow, remind them and try to continue. |
3223 | Diag(Tok, DiagID: diag::err_requires_expr_missing_arrow) |
3224 | << FixItHint::CreateInsertion(InsertionLoc: Tok.getLocation(), Code: "->" ); |
3225 | // Try to parse a 'type-constraint' |
3226 | if (TryAnnotateTypeConstraint()) { |
3227 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3228 | break; |
3229 | } |
3230 | if (!isTypeConstraintAnnotation()) { |
3231 | Diag(Tok, DiagID: diag::err_requires_expr_expected_type_constraint); |
3232 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3233 | break; |
3234 | } |
3235 | CXXScopeSpec SS; |
3236 | if (Tok.is(K: tok::annot_cxxscope)) { |
3237 | Actions.RestoreNestedNameSpecifierAnnotation(Annotation: Tok.getAnnotationValue(), |
3238 | AnnotationRange: Tok.getAnnotationRange(), |
3239 | SS); |
3240 | ConsumeAnnotationToken(); |
3241 | } |
3242 | |
3243 | Req = Actions.ActOnCompoundRequirement( |
3244 | E: Expression.get(), NoexceptLoc, SS, TypeConstraint: takeTemplateIdAnnotation(tok: Tok), |
3245 | Depth: TemplateParameterDepth); |
3246 | ConsumeAnnotationToken(); |
3247 | if (Req) |
3248 | Requirements.push_back(Elt: Req); |
3249 | break; |
3250 | } |
3251 | default: { |
3252 | bool PossibleRequiresExprInSimpleRequirement = false; |
3253 | if (Tok.is(K: tok::kw_requires)) { |
3254 | auto IsNestedRequirement = [&] { |
3255 | RevertingTentativeParsingAction TPA(*this); |
3256 | ConsumeToken(); // 'requires' |
3257 | if (Tok.is(K: tok::l_brace)) |
3258 | // This is a requires expression |
3259 | // requires (T t) { |
3260 | // requires { t++; }; |
3261 | // ... ^ |
3262 | // } |
3263 | return false; |
3264 | if (Tok.is(K: tok::l_paren)) { |
3265 | // This might be the parameter list of a requires expression |
3266 | ConsumeParen(); |
3267 | auto Res = TryParseParameterDeclarationClause(); |
3268 | if (Res != TPResult::False) { |
3269 | // Skip to the closing parenthesis |
3270 | unsigned Depth = 1; |
3271 | while (Depth != 0) { |
3272 | bool FoundParen = SkipUntil(T1: tok::l_paren, T2: tok::r_paren, |
3273 | Flags: SkipUntilFlags::StopBeforeMatch); |
3274 | if (!FoundParen) |
3275 | break; |
3276 | if (Tok.is(K: tok::l_paren)) |
3277 | Depth++; |
3278 | else if (Tok.is(K: tok::r_paren)) |
3279 | Depth--; |
3280 | ConsumeAnyToken(); |
3281 | } |
3282 | // requires (T t) { |
3283 | // requires () ? |
3284 | // ... ^ |
3285 | // - OR - |
3286 | // requires (int x) ? |
3287 | // ... ^ |
3288 | // } |
3289 | if (Tok.is(K: tok::l_brace)) |
3290 | // requires (...) { |
3291 | // ^ - a requires expression as a |
3292 | // simple-requirement. |
3293 | return false; |
3294 | } |
3295 | } |
3296 | return true; |
3297 | }; |
3298 | if (IsNestedRequirement()) { |
3299 | ConsumeToken(); |
3300 | // Nested requirement |
3301 | // C++ [expr.prim.req.nested] |
3302 | // nested-requirement: |
3303 | // 'requires' constraint-expression ';' |
3304 | ExprResult ConstraintExpr = ParseConstraintExpression(); |
3305 | if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) { |
3306 | SkipUntil(T1: tok::semi, T2: tok::r_brace, |
3307 | Flags: SkipUntilFlags::StopBeforeMatch); |
3308 | break; |
3309 | } |
3310 | if (auto *Req = |
3311 | Actions.ActOnNestedRequirement(Constraint: ConstraintExpr.get())) |
3312 | Requirements.push_back(Elt: Req); |
3313 | else { |
3314 | SkipUntil(T1: tok::semi, T2: tok::r_brace, |
3315 | Flags: SkipUntilFlags::StopBeforeMatch); |
3316 | break; |
3317 | } |
3318 | break; |
3319 | } else |
3320 | PossibleRequiresExprInSimpleRequirement = true; |
3321 | } else if (Tok.is(K: tok::kw_typename)) { |
3322 | // This might be 'typename T::value_type;' (a type requirement) or |
3323 | // 'typename T::value_type{};' (a simple requirement). |
3324 | TentativeParsingAction TPA(*this); |
3325 | |
3326 | // We need to consume the typename to allow 'requires { typename a; }' |
3327 | SourceLocation TypenameKWLoc = ConsumeToken(); |
3328 | if (TryAnnotateOptionalCXXScopeToken()) { |
3329 | TPA.Commit(); |
3330 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3331 | break; |
3332 | } |
3333 | CXXScopeSpec SS; |
3334 | if (Tok.is(K: tok::annot_cxxscope)) { |
3335 | Actions.RestoreNestedNameSpecifierAnnotation( |
3336 | Annotation: Tok.getAnnotationValue(), AnnotationRange: Tok.getAnnotationRange(), SS); |
3337 | ConsumeAnnotationToken(); |
3338 | } |
3339 | |
3340 | if (Tok.isOneOf(Ks: tok::identifier, Ks: tok::annot_template_id) && |
3341 | !NextToken().isOneOf(Ks: tok::l_brace, Ks: tok::l_paren)) { |
3342 | TPA.Commit(); |
3343 | SourceLocation NameLoc = Tok.getLocation(); |
3344 | IdentifierInfo *II = nullptr; |
3345 | TemplateIdAnnotation *TemplateId = nullptr; |
3346 | if (Tok.is(K: tok::identifier)) { |
3347 | II = Tok.getIdentifierInfo(); |
3348 | ConsumeToken(); |
3349 | } else { |
3350 | TemplateId = takeTemplateIdAnnotation(tok: Tok); |
3351 | ConsumeAnnotationToken(); |
3352 | if (TemplateId->isInvalid()) |
3353 | break; |
3354 | } |
3355 | |
3356 | if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS, |
3357 | NameLoc, TypeName: II, |
3358 | TemplateId)) { |
3359 | Requirements.push_back(Elt: Req); |
3360 | } |
3361 | break; |
3362 | } |
3363 | TPA.Revert(); |
3364 | } |
3365 | // Simple requirement |
3366 | // C++ [expr.prim.req.simple] |
3367 | // simple-requirement: |
3368 | // expression ';' |
3369 | SourceLocation StartLoc = Tok.getLocation(); |
3370 | ExprResult Expression = ParseExpression(); |
3371 | if (!Expression.isUsable()) { |
3372 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3373 | break; |
3374 | } |
3375 | if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement) |
3376 | Diag(Loc: StartLoc, DiagID: diag::err_requires_expr_in_simple_requirement) |
3377 | << FixItHint::CreateInsertion(InsertionLoc: StartLoc, Code: "requires" ); |
3378 | if (auto *Req = Actions.ActOnSimpleRequirement(E: Expression.get())) |
3379 | Requirements.push_back(Elt: Req); |
3380 | else { |
3381 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3382 | break; |
3383 | } |
3384 | // User may have tried to put some compound requirement stuff here |
3385 | if (Tok.is(K: tok::kw_noexcept)) { |
3386 | Diag(Tok, DiagID: diag::err_requires_expr_simple_requirement_noexcept) |
3387 | << FixItHint::CreateInsertion(InsertionLoc: StartLoc, Code: "{" ) |
3388 | << FixItHint::CreateInsertion(InsertionLoc: Tok.getLocation(), Code: "}" ); |
3389 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3390 | break; |
3391 | } |
3392 | break; |
3393 | } |
3394 | } |
3395 | if (ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_requirement)) { |
3396 | SkipUntil(T1: tok::semi, T2: tok::r_brace, Flags: SkipUntilFlags::StopBeforeMatch); |
3397 | TryConsumeToken(Expected: tok::semi); |
3398 | break; |
3399 | } |
3400 | } |
3401 | if (Requirements.empty()) { |
3402 | // Don't emit an empty requires expr here to avoid confusing the user with |
3403 | // other diagnostics quoting an empty requires expression they never |
3404 | // wrote. |
3405 | Braces.consumeClose(); |
3406 | Actions.ActOnFinishRequiresExpr(); |
3407 | return ExprError(); |
3408 | } |
3409 | } |
3410 | Braces.consumeClose(); |
3411 | Actions.ActOnFinishRequiresExpr(); |
3412 | ParsingBodyDecl.complete(D: Body); |
3413 | return Actions.ActOnRequiresExpr( |
3414 | RequiresKWLoc, Body, LParenLoc: Parens.getOpenLocation(), LocalParameters: LocalParameterDecls, |
3415 | RParenLoc: Parens.getCloseLocation(), Requirements, ClosingBraceLoc: Braces.getCloseLocation()); |
3416 | } |
3417 | |
3418 | static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) { |
3419 | switch (kind) { |
3420 | default: llvm_unreachable("Not a known type trait" ); |
3421 | #define TYPE_TRAIT_1(Spelling, Name, Key) \ |
3422 | case tok::kw_ ## Spelling: return UTT_ ## Name; |
3423 | #define TYPE_TRAIT_2(Spelling, Name, Key) \ |
3424 | case tok::kw_ ## Spelling: return BTT_ ## Name; |
3425 | #include "clang/Basic/TokenKinds.def" |
3426 | #define TYPE_TRAIT_N(Spelling, Name, Key) \ |
3427 | case tok::kw_ ## Spelling: return TT_ ## Name; |
3428 | #include "clang/Basic/TokenKinds.def" |
3429 | } |
3430 | } |
3431 | |
3432 | static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) { |
3433 | switch (kind) { |
3434 | default: |
3435 | llvm_unreachable("Not a known array type trait" ); |
3436 | #define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \ |
3437 | case tok::kw_##Spelling: \ |
3438 | return ATT_##Name; |
3439 | #include "clang/Basic/TokenKinds.def" |
3440 | } |
3441 | } |
3442 | |
3443 | static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) { |
3444 | switch (kind) { |
3445 | default: |
3446 | llvm_unreachable("Not a known unary expression trait." ); |
3447 | #define EXPRESSION_TRAIT(Spelling, Name, Key) \ |
3448 | case tok::kw_##Spelling: \ |
3449 | return ET_##Name; |
3450 | #include "clang/Basic/TokenKinds.def" |
3451 | } |
3452 | } |
3453 | |
3454 | ExprResult Parser::ParseTypeTrait() { |
3455 | tok::TokenKind Kind = Tok.getKind(); |
3456 | |
3457 | SourceLocation Loc = ConsumeToken(); |
3458 | |
3459 | BalancedDelimiterTracker Parens(*this, tok::l_paren); |
3460 | if (Parens.expectAndConsume()) |
3461 | return ExprError(); |
3462 | |
3463 | SmallVector<ParsedType, 2> Args; |
3464 | do { |
3465 | // Parse the next type. |
3466 | TypeResult Ty = ParseTypeName(/*SourceRange=*/Range: nullptr, |
3467 | Context: getLangOpts().CPlusPlus |
3468 | ? DeclaratorContext::TemplateTypeArg |
3469 | : DeclaratorContext::TypeName); |
3470 | if (Ty.isInvalid()) { |
3471 | Parens.skipToEnd(); |
3472 | return ExprError(); |
3473 | } |
3474 | |
3475 | // Parse the ellipsis, if present. |
3476 | if (Tok.is(K: tok::ellipsis)) { |
3477 | Ty = Actions.ActOnPackExpansion(Type: Ty.get(), EllipsisLoc: ConsumeToken()); |
3478 | if (Ty.isInvalid()) { |
3479 | Parens.skipToEnd(); |
3480 | return ExprError(); |
3481 | } |
3482 | } |
3483 | |
3484 | // Add this type to the list of arguments. |
3485 | Args.push_back(Elt: Ty.get()); |
3486 | } while (TryConsumeToken(Expected: tok::comma)); |
3487 | |
3488 | if (Parens.consumeClose()) |
3489 | return ExprError(); |
3490 | |
3491 | SourceLocation EndLoc = Parens.getCloseLocation(); |
3492 | |
3493 | return Actions.ActOnTypeTrait(Kind: TypeTraitFromTokKind(kind: Kind), KWLoc: Loc, Args, RParenLoc: EndLoc); |
3494 | } |
3495 | |
3496 | ExprResult Parser::ParseArrayTypeTrait() { |
3497 | ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(kind: Tok.getKind()); |
3498 | SourceLocation Loc = ConsumeToken(); |
3499 | |
3500 | BalancedDelimiterTracker T(*this, tok::l_paren); |
3501 | if (T.expectAndConsume()) |
3502 | return ExprError(); |
3503 | |
3504 | TypeResult Ty = ParseTypeName(/*SourceRange=*/Range: nullptr, |
3505 | Context: DeclaratorContext::TemplateTypeArg); |
3506 | if (Ty.isInvalid()) { |
3507 | SkipUntil(T: tok::comma, Flags: StopAtSemi); |
3508 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3509 | return ExprError(); |
3510 | } |
3511 | |
3512 | switch (ATT) { |
3513 | case ATT_ArrayRank: { |
3514 | T.consumeClose(); |
3515 | return Actions.ActOnArrayTypeTrait(ATT, KWLoc: Loc, LhsTy: Ty.get(), DimExpr: nullptr, |
3516 | RParen: T.getCloseLocation()); |
3517 | } |
3518 | case ATT_ArrayExtent: { |
3519 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
3520 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3521 | return ExprError(); |
3522 | } |
3523 | |
3524 | ExprResult DimExpr = ParseExpression(); |
3525 | T.consumeClose(); |
3526 | |
3527 | if (DimExpr.isInvalid()) |
3528 | return ExprError(); |
3529 | |
3530 | return Actions.ActOnArrayTypeTrait(ATT, KWLoc: Loc, LhsTy: Ty.get(), DimExpr: DimExpr.get(), |
3531 | RParen: T.getCloseLocation()); |
3532 | } |
3533 | } |
3534 | llvm_unreachable("Invalid ArrayTypeTrait!" ); |
3535 | } |
3536 | |
3537 | ExprResult Parser::ParseExpressionTrait() { |
3538 | ExpressionTrait ET = ExpressionTraitFromTokKind(kind: Tok.getKind()); |
3539 | SourceLocation Loc = ConsumeToken(); |
3540 | |
3541 | BalancedDelimiterTracker T(*this, tok::l_paren); |
3542 | if (T.expectAndConsume()) |
3543 | return ExprError(); |
3544 | |
3545 | ExprResult Expr = ParseExpression(); |
3546 | |
3547 | T.consumeClose(); |
3548 | |
3549 | return Actions.ActOnExpressionTrait(OET: ET, KWLoc: Loc, Queried: Expr.get(), |
3550 | RParen: T.getCloseLocation()); |
3551 | } |
3552 | |
3553 | ExprResult |
3554 | Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, |
3555 | ParsedType &CastTy, |
3556 | BalancedDelimiterTracker &Tracker, |
3557 | ColonProtectionRAIIObject &ColonProt) { |
3558 | assert(getLangOpts().CPlusPlus && "Should only be called for C++!" ); |
3559 | assert(ExprType == ParenParseOption::CastExpr && |
3560 | "Compound literals are not ambiguous!" ); |
3561 | assert(isTypeIdInParens() && "Not a type-id!" ); |
3562 | |
3563 | ExprResult Result(true); |
3564 | CastTy = nullptr; |
3565 | |
3566 | // We need to disambiguate a very ugly part of the C++ syntax: |
3567 | // |
3568 | // (T())x; - type-id |
3569 | // (T())*x; - type-id |
3570 | // (T())/x; - expression |
3571 | // (T()); - expression |
3572 | // |
3573 | // The bad news is that we cannot use the specialized tentative parser, since |
3574 | // it can only verify that the thing inside the parens can be parsed as |
3575 | // type-id, it is not useful for determining the context past the parens. |
3576 | // |
3577 | // The good news is that the parser can disambiguate this part without |
3578 | // making any unnecessary Action calls. |
3579 | // |
3580 | // It uses a scheme similar to parsing inline methods. The parenthesized |
3581 | // tokens are cached, the context that follows is determined (possibly by |
3582 | // parsing a cast-expression), and then we re-introduce the cached tokens |
3583 | // into the token stream and parse them appropriately. |
3584 | |
3585 | ParenParseOption ParseAs; |
3586 | CachedTokens Toks; |
3587 | |
3588 | // Store the tokens of the parentheses. We will parse them after we determine |
3589 | // the context that follows them. |
3590 | if (!ConsumeAndStoreUntil(T1: tok::r_paren, Toks)) { |
3591 | // We didn't find the ')' we expected. |
3592 | Tracker.consumeClose(); |
3593 | return ExprError(); |
3594 | } |
3595 | |
3596 | if (Tok.is(K: tok::l_brace)) { |
3597 | ParseAs = ParenParseOption::CompoundLiteral; |
3598 | } else { |
3599 | bool NotCastExpr; |
3600 | if (Tok.is(K: tok::l_paren) && NextToken().is(K: tok::r_paren)) { |
3601 | NotCastExpr = true; |
3602 | } else { |
3603 | // Try parsing the cast-expression that may follow. |
3604 | // If it is not a cast-expression, NotCastExpr will be true and no token |
3605 | // will be consumed. |
3606 | ColonProt.restore(); |
3607 | Result = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr, |
3608 | isAddressOfOperand: false /*isAddressofOperand*/, NotCastExpr, |
3609 | // type-id has priority. |
3610 | isTypeCast: TypeCastState::IsTypeCast); |
3611 | } |
3612 | |
3613 | // If we parsed a cast-expression, it's really a type-id, otherwise it's |
3614 | // an expression. |
3615 | ParseAs = |
3616 | NotCastExpr ? ParenParseOption::SimpleExpr : ParenParseOption::CastExpr; |
3617 | } |
3618 | |
3619 | // Create a fake EOF to mark end of Toks buffer. |
3620 | Token AttrEnd; |
3621 | AttrEnd.startToken(); |
3622 | AttrEnd.setKind(tok::eof); |
3623 | AttrEnd.setLocation(Tok.getLocation()); |
3624 | AttrEnd.setEofData(Toks.data()); |
3625 | Toks.push_back(Elt: AttrEnd); |
3626 | |
3627 | // The current token should go after the cached tokens. |
3628 | Toks.push_back(Elt: Tok); |
3629 | // Re-enter the stored parenthesized tokens into the token stream, so we may |
3630 | // parse them now. |
3631 | PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true, |
3632 | /*IsReinject*/ true); |
3633 | // Drop the current token and bring the first cached one. It's the same token |
3634 | // as when we entered this function. |
3635 | ConsumeAnyToken(); |
3636 | |
3637 | if (ParseAs >= ParenParseOption::CompoundLiteral) { |
3638 | // Parse the type declarator. |
3639 | DeclSpec DS(AttrFactory); |
3640 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
3641 | DeclaratorContext::TypeName); |
3642 | { |
3643 | ColonProtectionRAIIObject InnerColonProtection(*this); |
3644 | ParseSpecifierQualifierList(DS); |
3645 | ParseDeclarator(D&: DeclaratorInfo); |
3646 | } |
3647 | |
3648 | // Match the ')'. |
3649 | Tracker.consumeClose(); |
3650 | ColonProt.restore(); |
3651 | |
3652 | // Consume EOF marker for Toks buffer. |
3653 | assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()); |
3654 | ConsumeAnyToken(); |
3655 | |
3656 | if (ParseAs == ParenParseOption::CompoundLiteral) { |
3657 | ExprType = ParenParseOption::CompoundLiteral; |
3658 | if (DeclaratorInfo.isInvalidType()) |
3659 | return ExprError(); |
3660 | |
3661 | TypeResult Ty = Actions.ActOnTypeName(D&: DeclaratorInfo); |
3662 | return ParseCompoundLiteralExpression(Ty: Ty.get(), |
3663 | LParenLoc: Tracker.getOpenLocation(), |
3664 | RParenLoc: Tracker.getCloseLocation()); |
3665 | } |
3666 | |
3667 | // We parsed '(' type-id ')' and the thing after it wasn't a '{'. |
3668 | assert(ParseAs == ParenParseOption::CastExpr); |
3669 | |
3670 | if (DeclaratorInfo.isInvalidType()) |
3671 | return ExprError(); |
3672 | |
3673 | // Result is what ParseCastExpression returned earlier. |
3674 | if (!Result.isInvalid()) |
3675 | Result = Actions.ActOnCastExpr(S: getCurScope(), LParenLoc: Tracker.getOpenLocation(), |
3676 | D&: DeclaratorInfo, Ty&: CastTy, |
3677 | RParenLoc: Tracker.getCloseLocation(), CastExpr: Result.get()); |
3678 | return Result; |
3679 | } |
3680 | |
3681 | // Not a compound literal, and not followed by a cast-expression. |
3682 | assert(ParseAs == ParenParseOption::SimpleExpr); |
3683 | |
3684 | ExprType = ParenParseOption::SimpleExpr; |
3685 | Result = ParseExpression(); |
3686 | if (!Result.isInvalid() && Tok.is(K: tok::r_paren)) |
3687 | Result = Actions.ActOnParenExpr(L: Tracker.getOpenLocation(), |
3688 | R: Tok.getLocation(), E: Result.get()); |
3689 | |
3690 | // Match the ')'. |
3691 | if (Result.isInvalid()) { |
3692 | while (Tok.isNot(K: tok::eof)) |
3693 | ConsumeAnyToken(); |
3694 | assert(Tok.getEofData() == AttrEnd.getEofData()); |
3695 | ConsumeAnyToken(); |
3696 | return ExprError(); |
3697 | } |
3698 | |
3699 | Tracker.consumeClose(); |
3700 | // Consume EOF marker for Toks buffer. |
3701 | assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()); |
3702 | ConsumeAnyToken(); |
3703 | return Result; |
3704 | } |
3705 | |
3706 | ExprResult Parser::ParseBuiltinBitCast() { |
3707 | SourceLocation KWLoc = ConsumeToken(); |
3708 | |
3709 | BalancedDelimiterTracker T(*this, tok::l_paren); |
3710 | if (T.expectAndConsume(DiagID: diag::err_expected_lparen_after, Msg: "__builtin_bit_cast" )) |
3711 | return ExprError(); |
3712 | |
3713 | // Parse the common declaration-specifiers piece. |
3714 | DeclSpec DS(AttrFactory); |
3715 | ParseSpecifierQualifierList(DS); |
3716 | |
3717 | // Parse the abstract-declarator, if present. |
3718 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
3719 | DeclaratorContext::TypeName); |
3720 | ParseDeclarator(D&: DeclaratorInfo); |
3721 | |
3722 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
3723 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected) << tok::comma; |
3724 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3725 | return ExprError(); |
3726 | } |
3727 | |
3728 | ExprResult Operand = ParseExpression(); |
3729 | |
3730 | if (T.consumeClose()) |
3731 | return ExprError(); |
3732 | |
3733 | if (Operand.isInvalid() || DeclaratorInfo.isInvalidType()) |
3734 | return ExprError(); |
3735 | |
3736 | return Actions.ActOnBuiltinBitCastExpr(KWLoc, Dcl&: DeclaratorInfo, Operand, |
3737 | RParenLoc: T.getCloseLocation()); |
3738 | } |
3739 | |