Coverage Report

Created: 2022-05-17 06:19

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