Coverage Report

Created: 2019-07-24 05:18

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