Coverage Report

Created: 2020-09-15 12:33

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