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