Coverage Report

Created: 2022-01-22 13:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseCXXInlineMethods.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseCXXInlineMethods.cpp - C++ class inline methods 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 parsing for C++ class inline methods.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/AST/DeclTemplate.h"
15
#include "clang/Parse/ParseDiagnostic.h"
16
#include "clang/Parse/RAIIObjectsForParser.h"
17
#include "clang/Sema/DeclSpec.h"
18
#include "clang/Sema/Scope.h"
19
using namespace clang;
20
21
/// ParseCXXInlineMethodDef - We parsed and verified that the specified
22
/// Declarator is a well formed C++ inline method definition. Now lex its body
23
/// and store its tokens for parsing after the C++ class is complete.
24
NamedDecl *Parser::ParseCXXInlineMethodDef(
25
    AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D,
26
    const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS,
27
697k
    SourceLocation PureSpecLoc) {
28
697k
  assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
29
0
  assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
30
697k
         "Current token not a '{', ':', '=', or 'try'!");
31
32
0
  MultiTemplateParamsArg TemplateParams(
33
697k
      TemplateInfo.TemplateParams ? 
TemplateInfo.TemplateParams->data()110k
34
697k
                                  : 
nullptr587k
,
35
697k
      TemplateInfo.TemplateParams ? 
TemplateInfo.TemplateParams->size()110k
:
0587k
);
36
37
697k
  NamedDecl *FnD;
38
697k
  if (D.getDeclSpec().isFriendSpecified())
39
11.4k
    FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
40
11.4k
                                          TemplateParams);
41
686k
  else {
42
686k
    FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
43
686k
                                           TemplateParams, nullptr,
44
686k
                                           VS, ICIS_NoInit);
45
686k
    if (FnD) {
46
686k
      Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
47
686k
      if (PureSpecLoc.isValid())
48
3
        Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
49
686k
    }
50
686k
  }
51
52
697k
  if (FnD)
53
697k
    HandleMemberFunctionDeclDelays(D, FnD);
54
55
697k
  D.complete(FnD);
56
57
697k
  if (TryConsumeToken(tok::equal)) {
58
39.8k
    if (!FnD) {
59
1
      SkipUntil(tok::semi);
60
1
      return nullptr;
61
1
    }
62
63
39.8k
    bool Delete = false;
64
39.8k
    SourceLocation KWLoc;
65
39.8k
    SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
66
39.8k
    if (TryConsumeToken(tok::kw_delete, KWLoc)) {
67
16.8k
      Diag(KWLoc, getLangOpts().CPlusPlus11
68
16.8k
                      ? 
diag::warn_cxx98_compat_defaulted_deleted_function16.7k
69
16.8k
                      : 
diag::ext_defaulted_deleted_function47
)
70
16.8k
        << 1 /* deleted */;
71
16.8k
      Actions.SetDeclDeleted(FnD, KWLoc);
72
16.8k
      Delete = true;
73
16.8k
      if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
74
15.0k
        DeclAsFunction->setRangeEnd(KWEndLoc);
75
15.0k
      }
76
23.0k
    } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
77
23.0k
      Diag(KWLoc, getLangOpts().CPlusPlus11
78
23.0k
                      ? 
diag::warn_cxx98_compat_defaulted_deleted_function23.0k
79
23.0k
                      : 
diag::ext_defaulted_deleted_function9
)
80
23.0k
        << 0 /* defaulted */;
81
23.0k
      Actions.SetDeclDefaulted(FnD, KWLoc);
82
23.0k
      if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
83
23.0k
        DeclAsFunction->setRangeEnd(KWEndLoc);
84
23.0k
      }
85
23.0k
    } else {
86
0
      llvm_unreachable("function definition after = not 'delete' or 'default'");
87
0
    }
88
89
39.8k
    if (Tok.is(tok::comma)) {
90
0
      Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
91
0
        << Delete;
92
0
      SkipUntil(tok::semi);
93
39.8k
    } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
94
39.8k
                                Delete ? 
"delete"16.8k
:
"default"23.0k
)) {
95
1
      SkipUntil(tok::semi);
96
1
    }
97
98
39.8k
    return FnD;
99
39.8k
  }
100
101
658k
  if (SkipFunctionBodies && 
(399
!FnD399
||
Actions.canSkipFunctionBody(FnD)399
) &&
102
658k
      
trySkippingFunctionBody()392
) {
103
333
    Actions.ActOnSkippedFunctionBody(FnD);
104
333
    return FnD;
105
333
  }
106
107
  // In delayed template parsing mode, if we are within a class template
108
  // or if we are about to parse function member template then consume
109
  // the tokens and store them for parsing at the end of the translation unit.
110
657k
  if (getLangOpts().DelayedTemplateParsing &&
111
657k
      
D.getFunctionDefinitionKind() == FunctionDefinitionKind::Definition859
&&
112
657k
      
!D.getDeclSpec().hasConstexprSpecifier()859
&&
113
657k
      
!(839
FnD839
&&
FnD->getAsFunction()839
&&
114
839
        FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
115
657k
      
(736
(736
Actions.CurContext->isDependentContext()736
||
116
736
        
(504
TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate504
&&
117
504
         
TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization41
)) &&
118
736
       
!Actions.IsInsideALocalClassWithinATemplateFunction()269
)) {
119
120
249
    CachedTokens Toks;
121
249
    LexTemplateFunctionForLateParsing(Toks);
122
123
249
    if (FnD) {
124
249
      FunctionDecl *FD = FnD->getAsFunction();
125
249
      Actions.CheckForFunctionRedefinition(FD);
126
249
      Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
127
249
    }
128
129
249
    return FnD;
130
249
  }
131
132
  // Consume the tokens and store them for later parsing.
133
134
657k
  LexedMethod* LM = new LexedMethod(this, FnD);
135
657k
  getCurrentClass().LateParsedDeclarations.push_back(LM);
136
657k
  CachedTokens &Toks = LM->Toks;
137
138
657k
  tok::TokenKind kind = Tok.getKind();
139
  // Consume everything up to (and including) the left brace of the
140
  // function body.
141
657k
  if (ConsumeAndStoreFunctionPrologue(Toks)) {
142
    // We didn't find the left-brace we expected after the
143
    // constructor initializer.
144
145
    // If we're code-completing and the completion point was in the broken
146
    // initializer, we want to parse it even though that will fail.
147
18
    if (PP.isCodeCompletionEnabled() &&
148
18
        
llvm::any_of(Toks, [](const Token &Tok) 2
{
149
6
          return Tok.is(tok::code_completion);
150
6
        })) {
151
      // If we gave up at the completion point, the initializer list was
152
      // likely truncated, so don't eat more tokens. We'll hit some extra
153
      // errors, but they should be ignored in code completion.
154
2
      return FnD;
155
2
    }
156
157
    // We already printed an error, and it's likely impossible to recover,
158
    // so don't try to parse this method later.
159
    // Skip over the rest of the decl and back to somewhere that looks
160
    // reasonable.
161
16
    SkipMalformedDecl();
162
16
    delete getCurrentClass().LateParsedDeclarations.back();
163
16
    getCurrentClass().LateParsedDeclarations.pop_back();
164
16
    return FnD;
165
657k
  } else {
166
    // Consume everything up to (and including) the matching right brace.
167
657k
    ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
168
657k
  }
169
170
  // If we're in a function-try-block, we need to store all the catch blocks.
171
657k
  if (kind == tok::kw_try) {
172
74
    while (Tok.is(tok::kw_catch)) {
173
37
      ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
174
37
      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
175
37
    }
176
37
  }
177
178
657k
  if (FnD) {
179
657k
    FunctionDecl *FD = FnD->getAsFunction();
180
    // Track that this function will eventually have a body; Sema needs
181
    // to know this.
182
657k
    Actions.CheckForFunctionRedefinition(FD);
183
657k
    FD->setWillHaveBody(true);
184
657k
  } else {
185
    // If semantic analysis could not build a function declaration,
186
    // just throw away the late-parsed declaration.
187
30
    delete getCurrentClass().LateParsedDeclarations.back();
188
30
    getCurrentClass().LateParsedDeclarations.pop_back();
189
30
  }
190
191
657k
  return FnD;
192
657k
}
193
194
/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
195
/// specified Declarator is a well formed C++ non-static data member
196
/// declaration. Now lex its initializer and store its tokens for parsing
197
/// after the class is complete.
198
3.33k
void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
199
3.33k
  assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
200
3.33k
         "Current token not a '{' or '='!");
201
202
0
  LateParsedMemberInitializer *MI =
203
3.33k
    new LateParsedMemberInitializer(this, VarD);
204
3.33k
  getCurrentClass().LateParsedDeclarations.push_back(MI);
205
3.33k
  CachedTokens &Toks = MI->Toks;
206
207
3.33k
  tok::TokenKind kind = Tok.getKind();
208
3.33k
  if (kind == tok::equal) {
209
3.26k
    Toks.push_back(Tok);
210
3.26k
    ConsumeToken();
211
3.26k
  }
212
213
3.33k
  if (kind == tok::l_brace) {
214
    // Begin by storing the '{' token.
215
70
    Toks.push_back(Tok);
216
70
    ConsumeBrace();
217
218
    // Consume everything up to (and including) the matching right brace.
219
70
    ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
220
3.26k
  } else {
221
    // Consume everything up to (but excluding) the comma or semicolon.
222
3.26k
    ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
223
3.26k
  }
224
225
  // Store an artificial EOF token to ensure that we don't run off the end of
226
  // the initializer when we come to parse it.
227
3.33k
  Token Eof;
228
3.33k
  Eof.startToken();
229
3.33k
  Eof.setKind(tok::eof);
230
3.33k
  Eof.setLocation(Tok.getLocation());
231
3.33k
  Eof.setEofData(VarD);
232
3.33k
  Toks.push_back(Eof);
233
3.33k
}
234
235
778k
Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
236
666k
void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
237
756k
void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
238
102k
void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
239
754k
void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
240
759k
void Parser::LateParsedDeclaration::ParseLexedPragmas() {}
241
242
Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
243
6.18k
  : Self(P), Class(C) {}
244
245
6.18k
Parser::LateParsedClass::~LateParsedClass() {
246
6.18k
  Self->DeallocateParsedClasses(Class);
247
6.18k
}
248
249
6.18k
void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
250
6.18k
  Self->ParseLexedMethodDeclarations(*Class);
251
6.18k
}
252
253
6.18k
void Parser::LateParsedClass::ParseLexedMemberInitializers() {
254
6.18k
  Self->ParseLexedMemberInitializers(*Class);
255
6.18k
}
256
257
6.18k
void Parser::LateParsedClass::ParseLexedMethodDefs() {
258
6.18k
  Self->ParseLexedMethodDefs(*Class);
259
6.18k
}
260
261
6.18k
void Parser::LateParsedClass::ParseLexedAttributes() {
262
6.18k
  Self->ParseLexedAttributes(*Class);
263
6.18k
}
264
265
6.18k
void Parser::LateParsedClass::ParseLexedPragmas() {
266
6.18k
  Self->ParseLexedPragmas(*Class);
267
6.18k
}
268
269
93.7k
void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
270
93.7k
  Self->ParseLexedMethodDeclaration(*this);
271
93.7k
}
272
273
657k
void Parser::LexedMethod::ParseLexedMethodDefs() {
274
657k
  Self->ParseLexedMethodDef(*this);
275
657k
}
276
277
3.33k
void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
278
3.33k
  Self->ParseLexedMemberInitializer(*this);
279
3.33k
}
280
281
5.42k
void Parser::LateParsedAttribute::ParseLexedAttributes() {
282
5.42k
  Self->ParseLexedAttribute(*this, true, false);
283
5.42k
}
284
285
86
void Parser::LateParsedPragma::ParseLexedPragmas() {
286
86
  Self->ParseLexedPragma(*this);
287
86
}
288
289
/// Utility to re-enter a possibly-templated scope while parsing its
290
/// late-parsed components.
291
struct Parser::ReenterTemplateScopeRAII {
292
  Parser &P;
293
  MultiParseScope Scopes;
294
  TemplateParameterDepthRAII CurTemplateDepthTracker;
295
296
  ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true)
297
4.00M
      : P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) {
298
4.00M
    if (Enter) {
299
788k
      CurTemplateDepthTracker.addDepth(
300
788k
          P.ReenterTemplateScopes(Scopes, MaybeTemplated));
301
788k
    }
302
4.00M
  }
303
};
304
305
/// Utility to re-enter a class scope while parsing its late-parsed components.
306
struct Parser::ReenterClassScopeRAII : ReenterTemplateScopeRAII {
307
  ParsingClass &Class;
308
309
  ReenterClassScopeRAII(Parser &P, ParsingClass &Class)
310
      : ReenterTemplateScopeRAII(P, Class.TagOrTemplate,
311
                                 /*Enter=*/!Class.TopLevelClass),
312
3.24M
        Class(Class) {
313
    // If this is the top-level class, we're still within its scope.
314
3.24M
    if (Class.TopLevelClass)
315
3.21M
      return;
316
317
    // Re-enter the class scope itself.
318
30.9k
    Scopes.Enter(Scope::ClassScope|Scope::DeclScope);
319
30.9k
    P.Actions.ActOnStartDelayedMemberDeclarations(P.getCurScope(),
320
30.9k
                                                  Class.TagOrTemplate);
321
30.9k
  }
322
3.24M
  ~ReenterClassScopeRAII() {
323
3.24M
    if (Class.TopLevelClass)
324
3.21M
      return;
325
326
30.9k
    P.Actions.ActOnFinishDelayedMemberDeclarations(P.getCurScope(),
327
30.9k
                                                   Class.TagOrTemplate);
328
30.9k
  }
329
};
330
331
/// ParseLexedMethodDeclarations - We finished parsing the member
332
/// specification of a top (non-nested) C++ class. Now go over the
333
/// stack of method declarations with some parts for which parsing was
334
/// delayed (such as default arguments) and parse them.
335
649k
void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
336
649k
  ReenterClassScopeRAII InClassScope(*this, Class);
337
338
649k
  for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
339
766k
    LateD->ParseLexedMethodDeclarations();
340
649k
}
341
342
93.7k
void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
343
  // If this is a member template, introduce the template parameter scope.
344
93.7k
  ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method);
345
346
  // Start the delayed C++ method declaration
347
93.7k
  Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
348
349
  // Introduce the parameters into scope and parse their default
350
  // arguments.
351
93.7k
  InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope |
352
93.7k
                                       Scope::FunctionDeclarationScope |
353
93.7k
                                       Scope::DeclScope);
354
256k
  for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; 
++I162k
) {
355
162k
    auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
356
    // Introduce the parameter into scope.
357
162k
    bool HasUnparsed = Param->hasUnparsedDefaultArg();
358
162k
    Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
359
162k
    std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
360
162k
    if (Toks) {
361
65.4k
      ParenBraceBracketBalancer BalancerRAIIObj(*this);
362
363
      // Mark the end of the default argument so that we know when to stop when
364
      // we parse it later on.
365
65.4k
      Token LastDefaultArgToken = Toks->back();
366
65.4k
      Token DefArgEnd;
367
65.4k
      DefArgEnd.startToken();
368
65.4k
      DefArgEnd.setKind(tok::eof);
369
65.4k
      DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
370
65.4k
      DefArgEnd.setEofData(Param);
371
65.4k
      Toks->push_back(DefArgEnd);
372
373
      // Parse the default argument from its saved token stream.
374
65.4k
      Toks->push_back(Tok); // So that the current token doesn't get lost
375
65.4k
      PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true);
376
377
      // Consume the previously-pushed token.
378
65.4k
      ConsumeAnyToken();
379
380
      // Consume the '='.
381
65.4k
      assert(Tok.is(tok::equal) && "Default argument not starting with '='");
382
0
      SourceLocation EqualLoc = ConsumeToken();
383
384
      // The argument isn't actually potentially evaluated unless it is
385
      // used.
386
65.4k
      EnterExpressionEvaluationContext Eval(
387
65.4k
          Actions,
388
65.4k
          Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, Param);
389
390
65.4k
      ExprResult DefArgResult;
391
65.4k
      if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)65.2k
) {
392
13
        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
393
13
        DefArgResult = ParseBraceInitializer();
394
13
      } else
395
65.4k
        DefArgResult = ParseAssignmentExpression();
396
65.4k
      DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
397
65.4k
      if (DefArgResult.isInvalid()) {
398
27
        Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
399
65.3k
      } else {
400
65.3k
        if (Tok.isNot(tok::eof) || 
Tok.getEofData() != Param65.3k
) {
401
          // The last two tokens are the terminator and the saved value of
402
          // Tok; the last token in the default argument is the one before
403
          // those.
404
2
          assert(Toks->size() >= 3 && "expected a token in default arg");
405
0
          Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
406
2
            << SourceRange(Tok.getLocation(),
407
2
                           (*Toks)[Toks->size() - 3].getLocation());
408
2
        }
409
0
        Actions.ActOnParamDefaultArgument(Param, EqualLoc,
410
65.3k
                                          DefArgResult.get());
411
65.3k
      }
412
413
      // There could be leftover tokens (e.g. because of an error).
414
      // Skip through until we reach the 'end of default argument' token.
415
65.4k
      while (Tok.isNot(tok::eof))
416
7
        ConsumeAnyToken();
417
418
65.4k
      if (Tok.is(tok::eof) && Tok.getEofData() == Param)
419
65.4k
        ConsumeAnyToken();
420
97.5k
    } else if (HasUnparsed) {
421
7
      assert(Param->hasInheritedDefaultArg());
422
0
      const FunctionDecl *Old;
423
7
      if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method))
424
1
        Old =
425
1
            cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl();
426
6
      else
427
6
        Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
428
7
      if (Old) {
429
5
        ParmVarDecl *OldParam = const_cast<ParmVarDecl*>(Old->getParamDecl(I));
430
5
        assert(!OldParam->hasUnparsedDefaultArg());
431
5
        if (OldParam->hasUninstantiatedDefaultArg())
432
4
          Param->setUninstantiatedDefaultArg(
433
4
              OldParam->getUninstantiatedDefaultArg());
434
1
        else
435
1
          Param->setDefaultArg(OldParam->getInit());
436
5
      }
437
7
    }
438
162k
  }
439
440
  // Parse a delayed exception-specification, if there is one.
441
93.7k
  if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
442
33.4k
    ParenBraceBracketBalancer BalancerRAIIObj(*this);
443
444
    // Add the 'stop' token.
445
33.4k
    Token LastExceptionSpecToken = Toks->back();
446
33.4k
    Token ExceptionSpecEnd;
447
33.4k
    ExceptionSpecEnd.startToken();
448
33.4k
    ExceptionSpecEnd.setKind(tok::eof);
449
33.4k
    ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
450
33.4k
    ExceptionSpecEnd.setEofData(LM.Method);
451
33.4k
    Toks->push_back(ExceptionSpecEnd);
452
453
    // Parse the default argument from its saved token stream.
454
33.4k
    Toks->push_back(Tok); // So that the current token doesn't get lost
455
33.4k
    PP.EnterTokenStream(*Toks, true, /*IsReinject*/true);
456
457
    // Consume the previously-pushed token.
458
33.4k
    ConsumeAnyToken();
459
460
    // C++11 [expr.prim.general]p3:
461
    //   If a declaration declares a member function or member function
462
    //   template of a class X, the expression this is a prvalue of type
463
    //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
464
    //   and the end of the function-definition, member-declarator, or
465
    //   declarator.
466
33.4k
    CXXMethodDecl *Method;
467
33.4k
    if (FunctionTemplateDecl *FunTmpl
468
33.4k
          = dyn_cast<FunctionTemplateDecl>(LM.Method))
469
15.9k
      Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
470
17.4k
    else
471
17.4k
      Method = dyn_cast<CXXMethodDecl>(LM.Method);
472
473
33.4k
    Sema::CXXThisScopeRAII ThisScope(
474
33.4k
        Actions, Method ? 
Method->getParent()33.4k
:
nullptr2
,
475
33.4k
        Method ? 
Method->getMethodQualifiers()33.4k
:
Qualifiers{}2
,
476
33.4k
        Method && 
getLangOpts().CPlusPlus1133.4k
);
477
478
    // Parse the exception-specification.
479
33.4k
    SourceRange SpecificationRange;
480
33.4k
    SmallVector<ParsedType, 4> DynamicExceptions;
481
33.4k
    SmallVector<SourceRange, 4> DynamicExceptionRanges;
482
33.4k
    ExprResult NoexceptExpr;
483
33.4k
    CachedTokens *ExceptionSpecTokens;
484
485
33.4k
    ExceptionSpecificationType EST
486
33.4k
      = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
487
33.4k
                                       DynamicExceptions,
488
33.4k
                                       DynamicExceptionRanges, NoexceptExpr,
489
33.4k
                                       ExceptionSpecTokens);
490
491
33.4k
    if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
492
0
      Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
493
494
    // Attach the exception-specification to the method.
495
33.4k
    Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
496
33.4k
                                               SpecificationRange,
497
33.4k
                                               DynamicExceptions,
498
33.4k
                                               DynamicExceptionRanges,
499
33.4k
                                               NoexceptExpr.isUsable()?
500
32.0k
                                                 NoexceptExpr.get() : 
nullptr1.34k
);
501
502
    // There could be leftover tokens (e.g. because of an error).
503
    // Skip through until we reach the original token position.
504
33.4k
    while (Tok.isNot(tok::eof))
505
0
      ConsumeAnyToken();
506
507
    // Clean up the remaining EOF token.
508
33.4k
    if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
509
33.4k
      ConsumeAnyToken();
510
511
33.4k
    delete Toks;
512
33.4k
    LM.ExceptionSpecTokens = nullptr;
513
33.4k
  }
514
515
93.7k
  InFunctionTemplateScope.Scopes.Exit();
516
517
  // Finish the delayed C++ method declaration.
518
93.7k
  Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
519
93.7k
}
520
521
/// ParseLexedMethodDefs - We finished parsing the member specification of a top
522
/// (non-nested) C++ class. Now go over the stack of lexed methods that were
523
/// collected during its parsing and parse them all.
524
649k
void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
525
649k
  ReenterClassScopeRAII InClassScope(*this, Class);
526
527
649k
  for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
528
766k
    D->ParseLexedMethodDefs();
529
649k
}
530
531
657k
void Parser::ParseLexedMethodDef(LexedMethod &LM) {
532
  // If this is a member template, introduce the template parameter scope.
533
657k
  ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D);
534
535
657k
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
536
537
657k
  assert(!LM.Toks.empty() && "Empty body!");
538
0
  Token LastBodyToken = LM.Toks.back();
539
657k
  Token BodyEnd;
540
657k
  BodyEnd.startToken();
541
657k
  BodyEnd.setKind(tok::eof);
542
657k
  BodyEnd.setLocation(LastBodyToken.getEndLoc());
543
657k
  BodyEnd.setEofData(LM.D);
544
657k
  LM.Toks.push_back(BodyEnd);
545
  // Append the current token at the end of the new token stream so that it
546
  // doesn't get lost.
547
657k
  LM.Toks.push_back(Tok);
548
657k
  PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
549
550
  // Consume the previously pushed token.
551
657k
  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
552
657k
  assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
553
657k
         && "Inline method not starting with '{', ':' or 'try'");
554
555
  // Parse the method body. Function body parsing code is similar enough
556
  // to be re-used for method bodies as well.
557
0
  ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
558
657k
                               Scope::CompoundStmtScope);
559
657k
  Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
560
561
657k
  if (Tok.is(tok::kw_try)) {
562
37
    ParseFunctionTryBlock(LM.D, FnScope);
563
564
37
    while (Tok.isNot(tok::eof))
565
0
      ConsumeAnyToken();
566
567
37
    if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
568
37
      ConsumeAnyToken();
569
37
    return;
570
37
  }
571
657k
  if (Tok.is(tok::colon)) {
572
134k
    ParseConstructorInitializer(LM.D);
573
574
    // Error recovery.
575
134k
    if (!Tok.is(tok::l_brace)) {
576
29
      FnScope.Exit();
577
29
      Actions.ActOnFinishFunctionBody(LM.D, nullptr);
578
579
29
      while (Tok.isNot(tok::eof))
580
0
        ConsumeAnyToken();
581
582
29
      if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
583
2
        ConsumeAnyToken();
584
29
      return;
585
29
    }
586
134k
  } else
587
523k
    Actions.ActOnDefaultCtorInitializers(LM.D);
588
589
657k
  assert((Actions.getDiagnostics().hasErrorOccurred() ||
590
657k
          !isa<FunctionTemplateDecl>(LM.D) ||
591
657k
          cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
592
657k
            < TemplateParameterDepth) &&
593
657k
         "TemplateParameterDepth should be greater than the depth of "
594
657k
         "current template being instantiated!");
595
596
0
  ParseFunctionStatementBody(LM.D, FnScope);
597
598
657k
  while (Tok.isNot(tok::eof))
599
0
    ConsumeAnyToken();
600
601
657k
  if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
602
657k
    ConsumeAnyToken();
603
604
657k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
605
548k
    if (isa<CXXMethodDecl>(FD) ||
606
548k
        
FD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)10.3k
)
607
548k
      Actions.ActOnFinishInlineFunctionDef(FD);
608
657k
}
609
610
/// ParseLexedMemberInitializers - We finished parsing the member specification
611
/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
612
/// initializers that were collected during its parsing and parse them all.
613
649k
void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
614
649k
  ReenterClassScopeRAII InClassScope(*this, Class);
615
616
649k
  if (!Class.LateParsedDeclarations.empty()) {
617
    // C++11 [expr.prim.general]p4:
618
    //   Otherwise, if a member-declarator declares a non-static data member
619
    //  (9.2) of a class X, the expression this is a prvalue of type "pointer
620
    //  to X" within the optional brace-or-equal-initializer. It shall not
621
    //  appear elsewhere in the member-declarator.
622
    // FIXME: This should be done in ParseLexedMemberInitializer, not here.
623
147k
    Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
624
147k
                                     Qualifiers());
625
626
147k
    for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
627
766k
      D->ParseLexedMemberInitializers();
628
147k
  }
629
630
649k
  Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
631
649k
}
632
633
3.33k
void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
634
3.33k
  if (!MI.Field || 
MI.Field->isInvalidDecl()3.32k
)
635
24
    return;
636
637
3.31k
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
638
639
  // Append the current token at the end of the new token stream so that it
640
  // doesn't get lost.
641
3.31k
  MI.Toks.push_back(Tok);
642
3.31k
  PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true);
643
644
  // Consume the previously pushed token.
645
3.31k
  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
646
647
3.31k
  SourceLocation EqualLoc;
648
649
3.31k
  Actions.ActOnStartCXXInClassMemberInitializer();
650
651
3.31k
  ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
652
3.31k
                                              EqualLoc);
653
654
3.31k
  Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
655
3.31k
                                                 Init.get());
656
657
  // The next token should be our artificial terminating EOF token.
658
3.31k
  if (Tok.isNot(tok::eof)) {
659
19
    if (!Init.isInvalid()) {
660
8
      SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
661
8
      if (!EndLoc.isValid())
662
0
        EndLoc = Tok.getLocation();
663
      // No fixit; we can't recover as if there were a semicolon here.
664
8
      Diag(EndLoc, diag::err_expected_semi_decl_list);
665
8
    }
666
667
    // Consume tokens until we hit the artificial EOF.
668
46
    while (Tok.isNot(tok::eof))
669
27
      ConsumeAnyToken();
670
19
  }
671
  // Make sure this is *our* artificial EOF token.
672
3.31k
  if (Tok.getEofData() == MI.Field)
673
3.31k
    ConsumeAnyToken();
674
3.31k
}
675
676
/// Wrapper class which calls ParseLexedAttribute, after setting up the
677
/// scope appropriately.
678
649k
void Parser::ParseLexedAttributes(ParsingClass &Class) {
679
649k
  ReenterClassScopeRAII InClassScope(*this, Class);
680
681
649k
  for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
682
766k
    LateD->ParseLexedAttributes();
683
649k
}
684
685
/// Parse all attributes in LAs, and attach them to Decl D.
686
void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
687
2.80M
                                     bool EnterScope, bool OnDefinition) {
688
2.80M
  assert(LAs.parseSoon() &&
689
2.80M
         "Attribute list should be marked for immediate parsing.");
690
2.81M
  for (unsigned i = 0, ni = LAs.size(); i < ni; 
++i5.34k
) {
691
5.34k
    if (D)
692
5.33k
      LAs[i]->addDecl(D);
693
5.34k
    ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
694
5.34k
    delete LAs[i];
695
5.34k
  }
696
2.80M
  LAs.clear();
697
2.80M
}
698
699
/// Finish parsing an attribute for which parsing was delayed.
700
/// This will be called at the end of parsing a class declaration
701
/// for each LateParsedAttribute. We consume the saved tokens and
702
/// create an attribute with the arguments filled in. We add this
703
/// to the Attribute list for the decl.
704
void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
705
10.7k
                                 bool EnterScope, bool OnDefinition) {
706
  // Create a fake EOF so that attribute parsing won't go off the end of the
707
  // attribute.
708
10.7k
  Token AttrEnd;
709
10.7k
  AttrEnd.startToken();
710
10.7k
  AttrEnd.setKind(tok::eof);
711
10.7k
  AttrEnd.setLocation(Tok.getLocation());
712
10.7k
  AttrEnd.setEofData(LA.Toks.data());
713
10.7k
  LA.Toks.push_back(AttrEnd);
714
715
  // Append the current token at the end of the new token stream so that it
716
  // doesn't get lost.
717
10.7k
  LA.Toks.push_back(Tok);
718
10.7k
  PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
719
  // Consume the previously pushed token.
720
10.7k
  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
721
722
10.7k
  ParsedAttributes Attrs(AttrFactory);
723
10.7k
  SourceLocation endLoc;
724
725
10.7k
  if (LA.Decls.size() > 0) {
726
10.7k
    Decl *D = LA.Decls[0];
727
10.7k
    NamedDecl *ND  = dyn_cast<NamedDecl>(D);
728
10.7k
    RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
729
730
    // Allow 'this' within late-parsed attributes.
731
10.7k
    Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
732
10.7k
                                     ND && ND->isCXXInstanceMember());
733
734
10.7k
    if (LA.Decls.size() == 1) {
735
      // If the Decl is templatized, add template parameters to scope.
736
10.7k
      ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope);
737
738
      // If the Decl is on a function, add function parameters to the scope.
739
10.7k
      bool HasFunScope = EnterScope && 
D->isFunctionOrFunctionTemplate()6.13k
;
740
10.7k
      if (HasFunScope) {
741
5.47k
        InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
742
5.47k
                                 Scope::CompoundStmtScope);
743
5.47k
        Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
744
5.47k
      }
745
746
10.7k
      ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
747
10.7k
                            nullptr, SourceLocation(), ParsedAttr::AS_GNU,
748
10.7k
                            nullptr);
749
750
10.7k
      if (HasFunScope)
751
5.47k
        Actions.ActOnExitFunctionContext();
752
10.7k
    } else {
753
      // If there are multiple decls, then the decl cannot be within the
754
      // function scope.
755
7
      ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
756
7
                            nullptr, SourceLocation(), ParsedAttr::AS_GNU,
757
7
                            nullptr);
758
7
    }
759
10.7k
  } else {
760
8
    Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
761
8
  }
762
763
10.7k
  if (OnDefinition && 
!Attrs.empty()4.62k
&&
!Attrs.begin()->isCXX11Attribute()4.61k
&&
764
10.7k
      
Attrs.begin()->isKnownToGCC()4.61k
)
765
0
    Diag(Tok, diag::warn_attribute_on_function_definition)
766
0
      << &LA.AttrName;
767
768
21.5k
  for (unsigned i = 0, ni = LA.Decls.size(); i < ni; 
++i10.7k
)
769
10.7k
    Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
770
771
  // Due to a parsing error, we either went over the cached tokens or
772
  // there are still cached tokens left, so we skip the leftover tokens.
773
21.5k
  while (Tok.isNot(tok::eof))
774
10.7k
    ConsumeAnyToken();
775
776
10.7k
  if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
777
10.7k
    ConsumeAnyToken();
778
10.7k
}
779
780
649k
void Parser::ParseLexedPragmas(ParsingClass &Class) {
781
649k
  ReenterClassScopeRAII InClassScope(*this, Class);
782
783
649k
  for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
784
766k
    D->ParseLexedPragmas();
785
649k
}
786
787
86
void Parser::ParseLexedPragma(LateParsedPragma &LP) {
788
86
  PP.EnterToken(Tok, /*IsReinject=*/true);
789
86
  PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true,
790
86
                      /*IsReinject=*/true);
791
792
  // Consume the previously pushed token.
793
86
  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
794
86
  assert(Tok.isAnnotation() && "Expected annotation token.");
795
0
  switch (Tok.getKind()) {
796
0
  case tok::annot_attr_openmp:
797
86
  case tok::annot_pragma_openmp: {
798
86
    AccessSpecifier AS = LP.getAccessSpecifier();
799
86
    ParsedAttributesWithRange Attrs(AttrFactory);
800
86
    (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
801
86
    break;
802
0
  }
803
0
  default:
804
0
    llvm_unreachable("Unexpected token.");
805
86
  }
806
86
}
807
808
/// ConsumeAndStoreUntil - Consume and store the token at the passed token
809
/// container until the token 'T' is reached (which gets
810
/// consumed/stored too, if ConsumeFinalToken).
811
/// If StopAtSemi is true, then we will stop early at a ';' character.
812
/// Returns true if token 'T1' or 'T2' was found.
813
/// NOTE: This is a specialized version of Parser::SkipUntil.
814
bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
815
                                  CachedTokens &Toks,
816
2.47M
                                  bool StopAtSemi, bool ConsumeFinalToken) {
817
  // We always want this function to consume at least one token if the first
818
  // token isn't T and if not at EOF.
819
2.47M
  bool isFirstTokenConsumed = true;
820
11.1M
  while (true) {
821
    // If we found one of the tokens, stop and return true.
822
11.1M
    if (Tok.is(T1) || 
Tok.is(T2)8.63M
) {
823
2.47M
      if (ConsumeFinalToken) {
824
1.94M
        Toks.push_back(Tok);
825
1.94M
        ConsumeAnyToken();
826
1.94M
      }
827
2.47M
      return true;
828
2.47M
    }
829
830
8.63M
    switch (Tok.getKind()) {
831
154
    case tok::eof:
832
154
    case tok::annot_module_begin:
833
154
    case tok::annot_module_end:
834
154
    case tok::annot_module_include:
835
      // Ran out of tokens.
836
154
      return false;
837
838
989k
    case tok::l_paren:
839
      // Recursively consume properly-nested parens.
840
989k
      Toks.push_back(Tok);
841
989k
      ConsumeParen();
842
989k
      ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
843
989k
      break;
844
22.2k
    case tok::l_square:
845
      // Recursively consume properly-nested square brackets.
846
22.2k
      Toks.push_back(Tok);
847
22.2k
      ConsumeBracket();
848
22.2k
      ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
849
22.2k
      break;
850
38.8k
    case tok::l_brace:
851
      // Recursively consume properly-nested braces.
852
38.8k
      Toks.push_back(Tok);
853
38.8k
      ConsumeBrace();
854
38.8k
      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
855
38.8k
      break;
856
857
    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
858
    // Since the user wasn't looking for this token (if they were, it would
859
    // already be handled), this isn't balanced.  If there is a LHS token at a
860
    // higher level, we will assume that this matches the unbalanced token
861
    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
862
7
    case tok::r_paren:
863
7
      if (ParenCount && !isFirstTokenConsumed)
864
6
        return false;  // Matches something.
865
1
      Toks.push_back(Tok);
866
1
      ConsumeParen();
867
1
      break;
868
33
    case tok::r_square:
869
33
      if (BracketCount && 
!isFirstTokenConsumed0
)
870
0
        return false;  // Matches something.
871
33
      Toks.push_back(Tok);
872
33
      ConsumeBracket();
873
33
      break;
874
93
    case tok::r_brace:
875
93
      if (BraceCount && !isFirstTokenConsumed)
876
93
        return false;  // Matches something.
877
0
      Toks.push_back(Tok);
878
0
      ConsumeBrace();
879
0
      break;
880
881
812k
    case tok::semi:
882
812k
      if (StopAtSemi)
883
12
        return false;
884
812k
      
LLVM_FALLTHROUGH812k
;812k
885
7.58M
    default:
886
      // consume this token.
887
7.58M
      Toks.push_back(Tok);
888
7.58M
      ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
889
7.58M
      break;
890
8.63M
    }
891
8.63M
    isFirstTokenConsumed = false;
892
8.63M
  }
893
2.47M
}
894
895
/// Consume tokens and store them in the passed token container until
896
/// we've passed the try keyword and constructor initializers and have consumed
897
/// the opening brace of the function body. The opening brace will be consumed
898
/// if and only if there was no error.
899
///
900
/// \return True on error.
901
660k
bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
902
660k
  if (Tok.is(tok::kw_try)) {
903
79
    Toks.push_back(Tok);
904
79
    ConsumeToken();
905
79
  }
906
907
660k
  if (Tok.isNot(tok::colon)) {
908
    // Easy case, just a function body.
909
910
    // Grab any remaining garbage to be diagnosed later. We stop when we reach a
911
    // brace: an opening one is the function body, while a closing one probably
912
    // means we've reached the end of the class.
913
526k
    ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
914
526k
                         /*StopAtSemi=*/true,
915
526k
                         /*ConsumeFinalToken=*/false);
916
526k
    if (Tok.isNot(tok::l_brace))
917
1
      return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
918
919
526k
    Toks.push_back(Tok);
920
526k
    ConsumeBrace();
921
526k
    return false;
922
526k
  }
923
924
134k
  Toks.push_back(Tok);
925
134k
  ConsumeToken();
926
927
  // We can't reliably skip over a mem-initializer-id, because it could be
928
  // a template-id involving not-yet-declared names. Given:
929
  //
930
  //   S ( ) : a < b < c > ( e )
931
  //
932
  // 'e' might be an initializer or part of a template argument, depending
933
  // on whether 'b' is a template.
934
935
  // Track whether we might be inside a template argument. We can give
936
  // significantly better diagnostics if we know that we're not.
937
134k
  bool MightBeTemplateArgument = false;
938
939
175k
  while (true) {
940
    // Skip over the mem-initializer-id, if possible.
941
175k
    if (Tok.is(tok::kw_decltype)) {
942
12
      Toks.push_back(Tok);
943
12
      SourceLocation OpenLoc = ConsumeToken();
944
12
      if (Tok.isNot(tok::l_paren))
945
1
        return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
946
1
                 << "decltype";
947
11
      Toks.push_back(Tok);
948
11
      ConsumeParen();
949
11
      if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
950
1
        Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
951
1
        Diag(OpenLoc, diag::note_matching) << tok::l_paren;
952
1
        return true;
953
1
      }
954
11
    }
955
177k
    
do 175k
{
956
      // Walk over a component of a nested-name-specifier.
957
177k
      if (Tok.is(tok::coloncolon)) {
958
1.54k
        Toks.push_back(Tok);
959
1.54k
        ConsumeToken();
960
961
1.54k
        if (Tok.is(tok::kw_template)) {
962
2
          Toks.push_back(Tok);
963
2
          ConsumeToken();
964
2
        }
965
1.54k
      }
966
967
177k
      if (Tok.is(tok::identifier)) {
968
177k
        Toks.push_back(Tok);
969
177k
        ConsumeToken();
970
177k
      } else {
971
221
        break;
972
221
      }
973
177k
    } while (
Tok.is(tok::coloncolon)177k
);
974
975
175k
    if (Tok.is(tok::code_completion)) {
976
49
      Toks.push_back(Tok);
977
49
      ConsumeCodeCompletionToken();
978
49
      if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
979
        // Could be the start of another member initializer (the ',' has not
980
        // been written yet)
981
23
        continue;
982
23
      }
983
49
    }
984
985
175k
    if (Tok.is(tok::comma)) {
986
      // The initialization is missing, we'll diagnose it later.
987
21
      Toks.push_back(Tok);
988
21
      ConsumeToken();
989
21
      continue;
990
21
    }
991
175k
    if (Tok.is(tok::less))
992
4.54k
      MightBeTemplateArgument = true;
993
994
175k
    if (MightBeTemplateArgument) {
995
      // We may be inside a template argument list. Grab up to the start of the
996
      // next parenthesized initializer or braced-init-list. This *might* be the
997
      // initializer, or it might be a subexpression in the template argument
998
      // list.
999
      // FIXME: Count angle brackets, and clear MightBeTemplateArgument
1000
      //        if all angles are closed.
1001
4.97k
      if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
1002
4.97k
                                /*StopAtSemi=*/true,
1003
4.97k
                                /*ConsumeFinalToken=*/false)) {
1004
        // We're not just missing the initializer, we're also missing the
1005
        // function body!
1006
0
        return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
1007
0
      }
1008
170k
    } else if (Tok.isNot(tok::l_paren) && 
Tok.isNot(tok::l_brace)323
) {
1009
      // We found something weird in a mem-initializer-id.
1010
4
      if (getLangOpts().CPlusPlus11)
1011
4
        return Diag(Tok.getLocation(), diag::err_expected_either)
1012
4
               << tok::l_paren << tok::l_brace;
1013
0
      else
1014
0
        return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
1015
4
    }
1016
1017
175k
    tok::TokenKind kind = Tok.getKind();
1018
175k
    Toks.push_back(Tok);
1019
175k
    bool IsLParen = (kind == tok::l_paren);
1020
175k
    SourceLocation OpenLoc = Tok.getLocation();
1021
1022
175k
    if (IsLParen) {
1023
175k
      ConsumeParen();
1024
175k
    } else {
1025
332
      assert(kind == tok::l_brace && "Must be left paren or brace here.");
1026
0
      ConsumeBrace();
1027
      // In C++03, this has to be the start of the function body, which
1028
      // means the initializer is malformed; we'll diagnose it later.
1029
332
      if (!getLangOpts().CPlusPlus11)
1030
63
        return false;
1031
1032
269
      const Token &PreviousToken = Toks[Toks.size() - 2];
1033
269
      if (!MightBeTemplateArgument &&
1034
269
          !PreviousToken.isOneOf(tok::identifier, tok::greater,
1035
256
                                 tok::greatergreater)) {
1036
        // If the opening brace is not preceded by one of these tokens, we are
1037
        // missing the mem-initializer-id. In order to recover better, we need
1038
        // to use heuristics to determine if this '{' is most likely the
1039
        // beginning of a brace-init-list or the function body.
1040
        // Check the token after the corresponding '}'.
1041
89
        TentativeParsingAction PA(*this);
1042
89
        if (SkipUntil(tok::r_brace) &&
1043
89
            !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
1044
          // Consider there was a malformed initializer and this is the start
1045
          // of the function body. We'll diagnose it later.
1046
89
          PA.Revert();
1047
89
          return false;
1048
89
        }
1049
0
        PA.Revert();
1050
0
      }
1051
269
    }
1052
1053
    // Grab the initializer (or the subexpression of the template argument).
1054
    // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
1055
    //        if we might be inside the braces of a lambda-expression.
1056
175k
    tok::TokenKind CloseKind = IsLParen ? 
tok::r_paren175k
:
tok::r_brace180
;
1057
175k
    if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
1058
7
      Diag(Tok, diag::err_expected) << CloseKind;
1059
7
      Diag(OpenLoc, diag::note_matching) << kind;
1060
7
      return true;
1061
7
    }
1062
1063
    // Grab pack ellipsis, if present.
1064
175k
    if (Tok.is(tok::ellipsis)) {
1065
2.60k
      Toks.push_back(Tok);
1066
2.60k
      ConsumeToken();
1067
2.60k
    }
1068
1069
    // If we know we just consumed a mem-initializer, we must have ',' or '{'
1070
    // next.
1071
175k
    if (Tok.is(tok::comma)) {
1072
41.2k
      Toks.push_back(Tok);
1073
41.2k
      ConsumeToken();
1074
134k
    } else if (Tok.is(tok::l_brace)) {
1075
      // This is the function body if the ')' or '}' is immediately followed by
1076
      // a '{'. That cannot happen within a template argument, apart from the
1077
      // case where a template argument contains a compound literal:
1078
      //
1079
      //   S ( ) : a < b < c > ( d ) { }
1080
      //   // End of declaration, or still inside the template argument?
1081
      //
1082
      // ... and the case where the template argument contains a lambda:
1083
      //
1084
      //   S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
1085
      //     ( ) > ( ) { }
1086
      //
1087
      // FIXME: Disambiguate these cases. Note that the latter case is probably
1088
      //        going to be made ill-formed by core issue 1607.
1089
134k
      Toks.push_back(Tok);
1090
134k
      ConsumeBrace();
1091
134k
      return false;
1092
134k
    } else 
if (21
!MightBeTemplateArgument21
) {
1093
8
      return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
1094
8
                                                                << tok::comma;
1095
8
    }
1096
175k
  }
1097
134k
}
1098
1099
/// Consume and store tokens from the '?' to the ':' in a conditional
1100
/// expression.
1101
4
bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
1102
  // Consume '?'.
1103
4
  assert(Tok.is(tok::question));
1104
0
  Toks.push_back(Tok);
1105
4
  ConsumeToken();
1106
1107
8
  while (Tok.isNot(tok::colon)) {
1108
4
    if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
1109
4
                              /*StopAtSemi=*/true,
1110
4
                              /*ConsumeFinalToken=*/false))
1111
0
      return false;
1112
1113
    // If we found a nested conditional, consume it.
1114
4
    if (Tok.is(tok::question) && 
!ConsumeAndStoreConditional(Toks)0
)
1115
0
      return false;
1116
4
  }
1117
1118
  // Consume ':'.
1119
4
  Toks.push_back(Tok);
1120
4
  ConsumeToken();
1121
4
  return true;
1122
4
}
1123
1124
/// A tentative parsing action that can also revert token annotations.
1125
class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
1126
public:
1127
  explicit UnannotatedTentativeParsingAction(Parser &Self,
1128
                                             tok::TokenKind EndKind)
1129
84
      : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
1130
    // Stash away the old token stream, so we can restore it once the
1131
    // tentative parse is complete.
1132
84
    TentativeParsingAction Inner(Self);
1133
84
    Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
1134
84
    Inner.Revert();
1135
84
  }
1136
1137
84
  void RevertAnnotations() {
1138
84
    Revert();
1139
1140
    // Put back the original tokens.
1141
84
    Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
1142
84
    if (Toks.size()) {
1143
84
      auto Buffer = std::make_unique<Token[]>(Toks.size());
1144
84
      std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
1145
84
      Buffer[Toks.size() - 1] = Self.Tok;
1146
84
      Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true,
1147
84
                               /*IsReinject*/ true);
1148
1149
84
      Self.Tok = Toks.front();
1150
84
    }
1151
84
  }
1152
1153
private:
1154
  Parser &Self;
1155
  CachedTokens Toks;
1156
  tok::TokenKind EndKind;
1157
};
1158
1159
/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
1160
/// container until the end of the current initializer expression (either a
1161
/// default argument or an in-class initializer for a non-static data member).
1162
///
1163
/// Returns \c true if we reached the end of something initializer-shaped,
1164
/// \c false if we bailed out.
1165
bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1166
68.7k
                                        CachedInitKind CIK) {
1167
  // We always want this function to consume at least one token if not at EOF.
1168
68.7k
  bool IsFirstToken = true;
1169
1170
  // Number of possible unclosed <s we've seen so far. These might be templates,
1171
  // and might not, but if there were none of them (or we know for sure that
1172
  // we're within a template), we can avoid a tentative parse.
1173
68.7k
  unsigned AngleCount = 0;
1174
68.7k
  unsigned KnownTemplateCount = 0;
1175
1176
223k
  while (true) {
1177
223k
    switch (Tok.getKind()) {
1178
5.29k
    case tok::comma:
1179
      // If we might be in a template, perform a tentative parse to check.
1180
5.29k
      if (!AngleCount)
1181
        // Not a template argument: this is the end of the initializer.
1182
5.19k
        return true;
1183
97
      if (KnownTemplateCount)
1184
13
        goto consume_token;
1185
1186
      // We hit a comma inside angle brackets. This is the hard case. The
1187
      // rule we follow is:
1188
      //  * For a default argument, if the tokens after the comma form a
1189
      //    syntactically-valid parameter-declaration-clause, in which each
1190
      //    parameter has an initializer, then this comma ends the default
1191
      //    argument.
1192
      //  * For a default initializer, if the tokens after the comma form a
1193
      //    syntactically-valid init-declarator-list, then this comma ends
1194
      //    the default initializer.
1195
84
      {
1196
84
        UnannotatedTentativeParsingAction PA(*this,
1197
84
                                             CIK == CIK_DefaultInitializer
1198
84
                                               ? 
tok::semi36
:
tok::r_paren48
);
1199
84
        Sema::TentativeAnalysisScope Scope(Actions);
1200
1201
84
        TPResult Result = TPResult::Error;
1202
84
        ConsumeToken();
1203
84
        switch (CIK) {
1204
36
        case CIK_DefaultInitializer:
1205
36
          Result = TryParseInitDeclaratorList();
1206
          // If we parsed a complete, ambiguous init-declarator-list, this
1207
          // is only syntactically-valid if it's followed by a semicolon.
1208
36
          if (Result == TPResult::Ambiguous && 
Tok.isNot(tok::semi)21
)
1209
13
            Result = TPResult::False;
1210
36
          break;
1211
1212
48
        case CIK_DefaultArgument:
1213
48
          bool InvalidAsDeclaration = false;
1214
48
          Result = TryParseParameterDeclarationClause(
1215
48
              &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
1216
          // If this is an expression or a declaration with a missing
1217
          // 'typename', assume it's not a declaration.
1218
48
          if (Result == TPResult::Ambiguous && 
InvalidAsDeclaration0
)
1219
0
            Result = TPResult::False;
1220
48
          break;
1221
84
        }
1222
1223
        // Put the token stream back and undo any annotations we performed
1224
        // after the comma. They may reflect a different parse than the one
1225
        // we will actually perform at the end of the class.
1226
84
        PA.RevertAnnotations();
1227
1228
        // If what follows could be a declaration, it is a declaration.
1229
84
        if (Result != TPResult::False && 
Result != TPResult::Error28
)
1230
26
          return true;
1231
84
      }
1232
1233
      // Keep going. We know we're inside a template argument list now.
1234
58
      ++KnownTemplateCount;
1235
58
      goto consume_token;
1236
1237
1
    case tok::eof:
1238
1
    case tok::annot_module_begin:
1239
1
    case tok::annot_module_end:
1240
1
    case tok::annot_module_include:
1241
      // Ran out of tokens.
1242
1
      return false;
1243
1244
1.05k
    case tok::less:
1245
      // FIXME: A '<' can only start a template-id if it's preceded by an
1246
      // identifier, an operator-function-id, or a literal-operator-id.
1247
1.05k
      ++AngleCount;
1248
1.05k
      goto consume_token;
1249
1250
4
    case tok::question:
1251
      // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1252
      // that is *never* the end of the initializer. Skip to the ':'.
1253
4
      if (!ConsumeAndStoreConditional(Toks))
1254
0
        return false;
1255
4
      break;
1256
1257
4
    case tok::greatergreatergreater:
1258
0
      if (!getLangOpts().CPlusPlus11)
1259
0
        goto consume_token;
1260
0
      if (AngleCount) --AngleCount;
1261
0
      if (KnownTemplateCount) --KnownTemplateCount;
1262
0
      LLVM_FALLTHROUGH;
1263
7
    case tok::greatergreater:
1264
7
      if (!getLangOpts().CPlusPlus11)
1265
0
        goto consume_token;
1266
7
      if (AngleCount) 
--AngleCount6
;
1267
7
      if (KnownTemplateCount) 
--KnownTemplateCount6
;
1268
7
      LLVM_FALLTHROUGH;
1269
1.03k
    case tok::greater:
1270
1.03k
      if (AngleCount) 
--AngleCount1.02k
;
1271
1.03k
      if (KnownTemplateCount) 
--KnownTemplateCount65
;
1272
1.03k
      goto consume_token;
1273
1274
14
    case tok::kw_template:
1275
      // 'template' identifier '<' is known to start a template argument list,
1276
      // and can be used to disambiguate the parse.
1277
      // FIXME: Support all forms of 'template' unqualified-id '<'.
1278
14
      Toks.push_back(Tok);
1279
14
      ConsumeToken();
1280
14
      if (Tok.is(tok::identifier)) {
1281
14
        Toks.push_back(Tok);
1282
14
        ConsumeToken();
1283
14
        if (Tok.is(tok::less)) {
1284
14
          ++AngleCount;
1285
14
          ++KnownTemplateCount;
1286
14
          Toks.push_back(Tok);
1287
14
          ConsumeToken();
1288
14
        }
1289
14
      }
1290
14
      break;
1291
1292
20
    case tok::kw_operator:
1293
      // If 'operator' precedes other punctuation, that punctuation loses
1294
      // its special behavior.
1295
20
      Toks.push_back(Tok);
1296
20
      ConsumeToken();
1297
20
      switch (Tok.getKind()) {
1298
6
      case tok::comma:
1299
6
      case tok::greatergreatergreater:
1300
8
      case tok::greatergreater:
1301
14
      case tok::greater:
1302
19
      case tok::less:
1303
19
        Toks.push_back(Tok);
1304
19
        ConsumeToken();
1305
19
        break;
1306
1
      default:
1307
1
        break;
1308
20
      }
1309
20
      break;
1310
1311
7.71k
    case tok::l_paren:
1312
      // Recursively consume properly-nested parens.
1313
7.71k
      Toks.push_back(Tok);
1314
7.71k
      ConsumeParen();
1315
7.71k
      ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1316
7.71k
      break;
1317
268
    case tok::l_square:
1318
      // Recursively consume properly-nested square brackets.
1319
268
      Toks.push_back(Tok);
1320
268
      ConsumeBracket();
1321
268
      ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1322
268
      break;
1323
969
    case tok::l_brace:
1324
      // Recursively consume properly-nested braces.
1325
969
      Toks.push_back(Tok);
1326
969
      ConsumeBrace();
1327
969
      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1328
969
      break;
1329
1330
    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1331
    // Since the user wasn't looking for this token (if they were, it would
1332
    // already be handled), this isn't balanced.  If there is a LHS token at a
1333
    // higher level, we will assume that this matches the unbalanced token
1334
    // and return it.  Otherwise, this is a spurious RHS token, which we
1335
    // consume and pass on to downstream code to diagnose.
1336
60.2k
    case tok::r_paren:
1337
60.2k
      if (CIK == CIK_DefaultArgument)
1338
60.2k
        return true; // End of the default argument.
1339
6
      if (ParenCount && 
!IsFirstToken0
)
1340
0
        return false;
1341
6
      Toks.push_back(Tok);
1342
6
      ConsumeParen();
1343
6
      continue;
1344
6
    case tok::r_square:
1345
6
      if (BracketCount && 
!IsFirstToken0
)
1346
0
        return false;
1347
6
      Toks.push_back(Tok);
1348
6
      ConsumeBracket();
1349
6
      continue;
1350
6
    case tok::r_brace:
1351
6
      if (BraceCount && !IsFirstToken)
1352
3
        return false;
1353
3
      Toks.push_back(Tok);
1354
3
      ConsumeBrace();
1355
3
      continue;
1356
1357
0
    case tok::code_completion:
1358
0
      Toks.push_back(Tok);
1359
0
      ConsumeCodeCompletionToken();
1360
0
      break;
1361
1362
44
    case tok::string_literal:
1363
44
    case tok::wide_string_literal:
1364
44
    case tok::utf8_string_literal:
1365
44
    case tok::utf16_string_literal:
1366
44
    case tok::utf32_string_literal:
1367
44
      Toks.push_back(Tok);
1368
44
      ConsumeStringToken();
1369
44
      break;
1370
3.19k
    case tok::semi:
1371
3.19k
      if (CIK == CIK_DefaultInitializer)
1372
3.19k
        return true; // End of the default initializer.
1373
3.19k
      
LLVM_FALLTHROUGH0
;0
1374
144k
    default:
1375
146k
    consume_token:
1376
146k
      Toks.push_back(Tok);
1377
146k
      ConsumeToken();
1378
146k
      break;
1379
223k
    }
1380
155k
    IsFirstToken = false;
1381
155k
  }
1382
68.7k
}