Coverage Report

Created: 2024-01-17 10:31

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