Coverage Report

Created: 2022-01-18 06:27

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