Coverage Report

Created: 2021-08-24 07:12

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