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