Coverage Report

Created: 2020-03-31 06:27

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