Coverage Report

Created: 2019-07-24 05:18

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