Coverage Report

Created: 2024-01-17 10:31

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