Coverage Report

Created: 2020-02-25 14:32

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