Coverage Report

Created: 2022-07-16 07:03

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