Coverage Report

Created: 2020-11-24 06:42

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