1 //===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements parsing for C++ class inline methods.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Parse/RAIIObjectsForParser.h"
18 #include "clang/Sema/DeclSpec.h"
19 #include "clang/Sema/Scope.h"
20 using namespace clang;
22 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
23 /// Declarator is a well formed C++ inline method definition. Now lex its body
24 /// and store its tokens for parsing after the C++ class is complete.
25 NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
26 AttributeList *AccessAttrs,
28 const ParsedTemplateInfo &TemplateInfo,
29 const VirtSpecifiers& VS,
30 SourceLocation PureSpecLoc) {
31 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
32 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
33 "Current token not a '{', ':', '=', or 'try'!");
35 MultiTemplateParamsArg TemplateParams(
36 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
38 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
41 if (D.getDeclSpec().isFriendSpecified())
42 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
45 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
46 TemplateParams, nullptr,
49 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
50 if (PureSpecLoc.isValid())
51 Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
56 HandleMemberFunctionDeclDelays(D, FnD);
60 if (TryConsumeToken(tok::equal)) {
68 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
69 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
70 Diag(KWLoc, getLangOpts().CPlusPlus11
71 ? diag::warn_cxx98_compat_defaulted_deleted_function
72 : diag::ext_defaulted_deleted_function)
74 Actions.SetDeclDeleted(FnD, KWLoc);
76 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
77 DeclAsFunction->setRangeEnd(KWEndLoc);
79 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
80 Diag(KWLoc, getLangOpts().CPlusPlus11
81 ? diag::warn_cxx98_compat_defaulted_deleted_function
82 : diag::ext_defaulted_deleted_function)
84 Actions.SetDeclDefaulted(FnD, KWLoc);
85 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
86 DeclAsFunction->setRangeEnd(KWEndLoc);
89 llvm_unreachable("function definition after = not 'delete' or 'default'");
92 if (Tok.is(tok::comma)) {
93 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
96 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
97 Delete ? "delete" : "default")) {
104 if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) &&
105 trySkippingFunctionBody()) {
106 Actions.ActOnSkippedFunctionBody(FnD);
110 // In delayed template parsing mode, if we are within a class template
111 // or if we are about to parse function member template then consume
112 // the tokens and store them for parsing at the end of the translation unit.
113 if (getLangOpts().DelayedTemplateParsing &&
114 D.getFunctionDefinitionKind() == FDK_Definition &&
115 !D.getDeclSpec().isConstexprSpecified() &&
116 !(FnD && FnD->getAsFunction() &&
117 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
118 ((Actions.CurContext->isDependentContext() ||
119 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
120 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
121 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
124 LexTemplateFunctionForLateParsing(Toks);
127 FunctionDecl *FD = FnD->getAsFunction();
128 Actions.CheckForFunctionRedefinition(FD);
129 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
135 // Consume the tokens and store them for later parsing.
137 LexedMethod* LM = new LexedMethod(this, FnD);
138 getCurrentClass().LateParsedDeclarations.push_back(LM);
139 LM->TemplateScope = getCurScope()->isTemplateParamScope();
140 CachedTokens &Toks = LM->Toks;
142 tok::TokenKind kind = Tok.getKind();
143 // Consume everything up to (and including) the left brace of the
145 if (ConsumeAndStoreFunctionPrologue(Toks)) {
146 // We didn't find the left-brace we expected after the
147 // constructor initializer; we already printed an error, and it's likely
148 // impossible to recover, so don't try to parse this method later.
149 // Skip over the rest of the decl and back to somewhere that looks
152 delete getCurrentClass().LateParsedDeclarations.back();
153 getCurrentClass().LateParsedDeclarations.pop_back();
156 // Consume everything up to (and including) the matching right brace.
157 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
160 // If we're in a function-try-block, we need to store all the catch blocks.
161 if (kind == tok::kw_try) {
162 while (Tok.is(tok::kw_catch)) {
163 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
164 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
169 FunctionDecl *FD = FnD->getAsFunction();
170 // Track that this function will eventually have a body; Sema needs
172 Actions.CheckForFunctionRedefinition(FD);
173 FD->setWillHaveBody(true);
175 // If semantic analysis could not build a function declaration,
176 // just throw away the late-parsed declaration.
177 delete getCurrentClass().LateParsedDeclarations.back();
178 getCurrentClass().LateParsedDeclarations.pop_back();
184 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
185 /// specified Declarator is a well formed C++ non-static data member
186 /// declaration. Now lex its initializer and store its tokens for parsing
187 /// after the class is complete.
188 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
189 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
190 "Current token not a '{' or '='!");
192 LateParsedMemberInitializer *MI =
193 new LateParsedMemberInitializer(this, VarD);
194 getCurrentClass().LateParsedDeclarations.push_back(MI);
195 CachedTokens &Toks = MI->Toks;
197 tok::TokenKind kind = Tok.getKind();
198 if (kind == tok::equal) {
203 if (kind == tok::l_brace) {
204 // Begin by storing the '{' token.
208 // Consume everything up to (and including) the matching right brace.
209 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
211 // Consume everything up to (but excluding) the comma or semicolon.
212 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
215 // Store an artificial EOF token to ensure that we don't run off the end of
216 // the initializer when we come to parse it.
219 Eof.setKind(tok::eof);
220 Eof.setLocation(Tok.getLocation());
221 Eof.setEofData(VarD);
225 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
226 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
227 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
228 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
230 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
231 : Self(P), Class(C) {}
233 Parser::LateParsedClass::~LateParsedClass() {
234 Self->DeallocateParsedClasses(Class);
237 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
238 Self->ParseLexedMethodDeclarations(*Class);
241 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
242 Self->ParseLexedMemberInitializers(*Class);
245 void Parser::LateParsedClass::ParseLexedMethodDefs() {
246 Self->ParseLexedMethodDefs(*Class);
249 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
250 Self->ParseLexedMethodDeclaration(*this);
253 void Parser::LexedMethod::ParseLexedMethodDefs() {
254 Self->ParseLexedMethodDef(*this);
257 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
258 Self->ParseLexedMemberInitializer(*this);
261 /// ParseLexedMethodDeclarations - We finished parsing the member
262 /// specification of a top (non-nested) C++ class. Now go over the
263 /// stack of method declarations with some parts for which parsing was
264 /// delayed (such as default arguments) and parse them.
265 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
266 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
267 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
269 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
270 if (HasTemplateScope) {
271 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
272 ++CurTemplateDepthTracker;
275 // The current scope is still active if we're the top-level class.
276 // Otherwise we'll need to push and enter a new scope.
277 bool HasClassScope = !Class.TopLevelClass;
278 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
281 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
282 Class.TagOrTemplate);
284 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
285 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
289 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
290 Class.TagOrTemplate);
293 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
294 // If this is a member template, introduce the template parameter scope.
295 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
296 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
297 if (LM.TemplateScope) {
298 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
299 ++CurTemplateDepthTracker;
301 // Start the delayed C++ method declaration
302 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
304 // Introduce the parameters into scope and parse their default
306 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
307 Scope::FunctionDeclarationScope | Scope::DeclScope);
308 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
309 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
310 // Introduce the parameter into scope.
311 bool HasUnparsed = Param->hasUnparsedDefaultArg();
312 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
313 std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
315 // Mark the end of the default argument so that we know when to stop when
316 // we parse it later on.
317 Token LastDefaultArgToken = Toks->back();
319 DefArgEnd.startToken();
320 DefArgEnd.setKind(tok::eof);
321 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
322 DefArgEnd.setEofData(Param);
323 Toks->push_back(DefArgEnd);
325 // Parse the default argument from its saved token stream.
326 Toks->push_back(Tok); // So that the current token doesn't get lost
327 PP.EnterTokenStream(*Toks, true);
329 // Consume the previously-pushed token.
333 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
334 SourceLocation EqualLoc = ConsumeToken();
336 // The argument isn't actually potentially evaluated unless it is
338 EnterExpressionEvaluationContext Eval(
340 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, Param);
342 ExprResult DefArgResult;
343 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
344 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
345 DefArgResult = ParseBraceInitializer();
347 DefArgResult = ParseAssignmentExpression();
348 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
349 if (DefArgResult.isInvalid()) {
350 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
352 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
353 // The last two tokens are the terminator and the saved value of
354 // Tok; the last token in the default argument is the one before
356 assert(Toks->size() >= 3 && "expected a token in default arg");
357 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
358 << SourceRange(Tok.getLocation(),
359 (*Toks)[Toks->size() - 3].getLocation());
361 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
365 // There could be leftover tokens (e.g. because of an error).
366 // Skip through until we reach the 'end of default argument' token.
367 while (Tok.isNot(tok::eof))
370 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
372 } else if (HasUnparsed) {
373 assert(Param->hasInheritedDefaultArg());
374 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
375 ParmVarDecl *OldParam = Old->getParamDecl(I);
376 assert (!OldParam->hasUnparsedDefaultArg());
377 if (OldParam->hasUninstantiatedDefaultArg())
378 Param->setUninstantiatedDefaultArg(
379 OldParam->getUninstantiatedDefaultArg());
381 Param->setDefaultArg(OldParam->getInit());
385 // Parse a delayed exception-specification, if there is one.
386 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
387 // Add the 'stop' token.
388 Token LastExceptionSpecToken = Toks->back();
389 Token ExceptionSpecEnd;
390 ExceptionSpecEnd.startToken();
391 ExceptionSpecEnd.setKind(tok::eof);
392 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
393 ExceptionSpecEnd.setEofData(LM.Method);
394 Toks->push_back(ExceptionSpecEnd);
396 // Parse the default argument from its saved token stream.
397 Toks->push_back(Tok); // So that the current token doesn't get lost
398 PP.EnterTokenStream(*Toks, true);
400 // Consume the previously-pushed token.
403 // C++11 [expr.prim.general]p3:
404 // If a declaration declares a member function or member function
405 // template of a class X, the expression this is a prvalue of type
406 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
407 // and the end of the function-definition, member-declarator, or
409 CXXMethodDecl *Method;
410 if (FunctionTemplateDecl *FunTmpl
411 = dyn_cast<FunctionTemplateDecl>(LM.Method))
412 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
414 Method = cast<CXXMethodDecl>(LM.Method);
416 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
417 Method->getTypeQualifiers(),
418 getLangOpts().CPlusPlus11);
420 // Parse the exception-specification.
421 SourceRange SpecificationRange;
422 SmallVector<ParsedType, 4> DynamicExceptions;
423 SmallVector<SourceRange, 4> DynamicExceptionRanges;
424 ExprResult NoexceptExpr;
425 CachedTokens *ExceptionSpecTokens;
427 ExceptionSpecificationType EST
428 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
430 DynamicExceptionRanges, NoexceptExpr,
431 ExceptionSpecTokens);
433 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
434 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
436 // Attach the exception-specification to the method.
437 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
440 DynamicExceptionRanges,
441 NoexceptExpr.isUsable()?
442 NoexceptExpr.get() : nullptr);
444 // There could be leftover tokens (e.g. because of an error).
445 // Skip through until we reach the original token position.
446 while (Tok.isNot(tok::eof))
449 // Clean up the remaining EOF token.
450 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
454 LM.ExceptionSpecTokens = nullptr;
457 PrototypeScope.Exit();
459 // Finish the delayed C++ method declaration.
460 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
463 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
464 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
465 /// collected during its parsing and parse them all.
466 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
467 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
468 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
469 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
470 if (HasTemplateScope) {
471 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
472 ++CurTemplateDepthTracker;
474 bool HasClassScope = !Class.TopLevelClass;
475 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
478 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
479 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
483 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
484 // If this is a member template, introduce the template parameter scope.
485 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
486 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
487 if (LM.TemplateScope) {
488 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
489 ++CurTemplateDepthTracker;
492 assert(!LM.Toks.empty() && "Empty body!");
493 Token LastBodyToken = LM.Toks.back();
495 BodyEnd.startToken();
496 BodyEnd.setKind(tok::eof);
497 BodyEnd.setLocation(LastBodyToken.getEndLoc());
498 BodyEnd.setEofData(LM.D);
499 LM.Toks.push_back(BodyEnd);
500 // Append the current token at the end of the new token stream so that it
502 LM.Toks.push_back(Tok);
503 PP.EnterTokenStream(LM.Toks, true);
505 // Consume the previously pushed token.
506 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
507 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
508 && "Inline method not starting with '{', ':' or 'try'");
510 // Parse the method body. Function body parsing code is similar enough
511 // to be re-used for method bodies as well.
512 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
513 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
515 if (Tok.is(tok::kw_try)) {
516 ParseFunctionTryBlock(LM.D, FnScope);
518 while (Tok.isNot(tok::eof))
521 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
525 if (Tok.is(tok::colon)) {
526 ParseConstructorInitializer(LM.D);
529 if (!Tok.is(tok::l_brace)) {
531 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
533 while (Tok.isNot(tok::eof))
536 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
541 Actions.ActOnDefaultCtorInitializers(LM.D);
543 assert((Actions.getDiagnostics().hasErrorOccurred() ||
544 !isa<FunctionTemplateDecl>(LM.D) ||
545 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
546 < TemplateParameterDepth) &&
547 "TemplateParameterDepth should be greater than the depth of "
548 "current template being instantiated!");
550 ParseFunctionStatementBody(LM.D, FnScope);
552 while (Tok.isNot(tok::eof))
555 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
558 if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
559 if (isa<CXXMethodDecl>(FD) ||
560 FD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend))
561 Actions.ActOnFinishInlineFunctionDef(FD);
564 /// ParseLexedMemberInitializers - We finished parsing the member specification
565 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
566 /// initializers that were collected during its parsing and parse them all.
567 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
568 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
569 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
571 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
572 if (HasTemplateScope) {
573 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
574 ++CurTemplateDepthTracker;
576 // Set or update the scope flags.
577 bool AlreadyHasClassScope = Class.TopLevelClass;
578 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
579 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
580 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
582 if (!AlreadyHasClassScope)
583 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
584 Class.TagOrTemplate);
586 if (!Class.LateParsedDeclarations.empty()) {
587 // C++11 [expr.prim.general]p4:
588 // Otherwise, if a member-declarator declares a non-static data member
589 // (9.2) of a class X, the expression this is a prvalue of type "pointer
590 // to X" within the optional brace-or-equal-initializer. It shall not
591 // appear elsewhere in the member-declarator.
592 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
593 /*TypeQuals=*/(unsigned)0);
595 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
596 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
600 if (!AlreadyHasClassScope)
601 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
602 Class.TagOrTemplate);
604 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
607 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
608 if (!MI.Field || MI.Field->isInvalidDecl())
611 // Append the current token at the end of the new token stream so that it
613 MI.Toks.push_back(Tok);
614 PP.EnterTokenStream(MI.Toks, true);
616 // Consume the previously pushed token.
617 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
619 SourceLocation EqualLoc;
621 Actions.ActOnStartCXXInClassMemberInitializer();
623 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
626 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
629 // The next token should be our artificial terminating EOF token.
630 if (Tok.isNot(tok::eof)) {
631 if (!Init.isInvalid()) {
632 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
633 if (!EndLoc.isValid())
634 EndLoc = Tok.getLocation();
635 // No fixit; we can't recover as if there were a semicolon here.
636 Diag(EndLoc, diag::err_expected_semi_decl_list);
639 // Consume tokens until we hit the artificial EOF.
640 while (Tok.isNot(tok::eof))
643 // Make sure this is *our* artificial EOF token.
644 if (Tok.getEofData() == MI.Field)
648 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
649 /// container until the token 'T' is reached (which gets
650 /// consumed/stored too, if ConsumeFinalToken).
651 /// If StopAtSemi is true, then we will stop early at a ';' character.
652 /// Returns true if token 'T1' or 'T2' was found.
653 /// NOTE: This is a specialized version of Parser::SkipUntil.
654 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
656 bool StopAtSemi, bool ConsumeFinalToken) {
657 // We always want this function to consume at least one token if the first
658 // token isn't T and if not at EOF.
659 bool isFirstTokenConsumed = true;
661 // If we found one of the tokens, stop and return true.
662 if (Tok.is(T1) || Tok.is(T2)) {
663 if (ConsumeFinalToken) {
670 switch (Tok.getKind()) {
672 case tok::annot_module_begin:
673 case tok::annot_module_end:
674 case tok::annot_module_include:
675 // Ran out of tokens.
679 // Recursively consume properly-nested parens.
682 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
685 // Recursively consume properly-nested square brackets.
688 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
691 // Recursively consume properly-nested braces.
694 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
697 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
698 // Since the user wasn't looking for this token (if they were, it would
699 // already be handled), this isn't balanced. If there is a LHS token at a
700 // higher level, we will assume that this matches the unbalanced token
701 // and return it. Otherwise, this is a spurious RHS token, which we skip.
703 if (ParenCount && !isFirstTokenConsumed)
704 return false; // Matches something.
709 if (BracketCount && !isFirstTokenConsumed)
710 return false; // Matches something.
715 if (BraceCount && !isFirstTokenConsumed)
716 return false; // Matches something.
726 // consume this token.
728 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
731 isFirstTokenConsumed = false;
735 /// \brief Consume tokens and store them in the passed token container until
736 /// we've passed the try keyword and constructor initializers and have consumed
737 /// the opening brace of the function body. The opening brace will be consumed
738 /// if and only if there was no error.
740 /// \return True on error.
741 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
742 if (Tok.is(tok::kw_try)) {
747 if (Tok.isNot(tok::colon)) {
748 // Easy case, just a function body.
750 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
751 // brace: an opening one is the function body, while a closing one probably
752 // means we've reached the end of the class.
753 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
755 /*ConsumeFinalToken=*/false);
756 if (Tok.isNot(tok::l_brace))
757 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
767 // We can't reliably skip over a mem-initializer-id, because it could be
768 // a template-id involving not-yet-declared names. Given:
770 // S ( ) : a < b < c > ( e )
772 // 'e' might be an initializer or part of a template argument, depending
773 // on whether 'b' is a template.
775 // Track whether we might be inside a template argument. We can give
776 // significantly better diagnostics if we know that we're not.
777 bool MightBeTemplateArgument = false;
780 // Skip over the mem-initializer-id, if possible.
781 if (Tok.is(tok::kw_decltype)) {
783 SourceLocation OpenLoc = ConsumeToken();
784 if (Tok.isNot(tok::l_paren))
785 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
789 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
790 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
791 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
796 // Walk over a component of a nested-name-specifier.
797 if (Tok.is(tok::coloncolon)) {
801 if (Tok.is(tok::kw_template)) {
807 if (Tok.is(tok::identifier)) {
813 } while (Tok.is(tok::coloncolon));
815 if (Tok.is(tok::code_completion)) {
817 ConsumeCodeCompletionToken();
818 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
819 // Could be the start of another member initializer (the ',' has not
825 if (Tok.is(tok::comma)) {
826 // The initialization is missing, we'll diagnose it later.
831 if (Tok.is(tok::less))
832 MightBeTemplateArgument = true;
834 if (MightBeTemplateArgument) {
835 // We may be inside a template argument list. Grab up to the start of the
836 // next parenthesized initializer or braced-init-list. This *might* be the
837 // initializer, or it might be a subexpression in the template argument
839 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
840 // if all angles are closed.
841 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
843 /*ConsumeFinalToken=*/false)) {
844 // We're not just missing the initializer, we're also missing the
846 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
848 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
849 // We found something weird in a mem-initializer-id.
850 if (getLangOpts().CPlusPlus11)
851 return Diag(Tok.getLocation(), diag::err_expected_either)
852 << tok::l_paren << tok::l_brace;
854 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
857 tok::TokenKind kind = Tok.getKind();
859 bool IsLParen = (kind == tok::l_paren);
860 SourceLocation OpenLoc = Tok.getLocation();
865 assert(kind == tok::l_brace && "Must be left paren or brace here.");
867 // In C++03, this has to be the start of the function body, which
868 // means the initializer is malformed; we'll diagnose it later.
869 if (!getLangOpts().CPlusPlus11)
872 const Token &PreviousToken = Toks[Toks.size() - 2];
873 if (!MightBeTemplateArgument &&
874 !PreviousToken.isOneOf(tok::identifier, tok::greater,
875 tok::greatergreater)) {
876 // If the opening brace is not preceded by one of these tokens, we are
877 // missing the mem-initializer-id. In order to recover better, we need
878 // to use heuristics to determine if this '{' is most likely the
879 // beginning of a brace-init-list or the function body.
880 // Check the token after the corresponding '}'.
881 TentativeParsingAction PA(*this);
882 if (SkipUntil(tok::r_brace) &&
883 !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
884 // Consider there was a malformed initializer and this is the start
885 // of the function body. We'll diagnose it later.
893 // Grab the initializer (or the subexpression of the template argument).
894 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
895 // if we might be inside the braces of a lambda-expression.
896 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
897 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
898 Diag(Tok, diag::err_expected) << CloseKind;
899 Diag(OpenLoc, diag::note_matching) << kind;
903 // Grab pack ellipsis, if present.
904 if (Tok.is(tok::ellipsis)) {
909 // If we know we just consumed a mem-initializer, we must have ',' or '{'
911 if (Tok.is(tok::comma)) {
914 } else if (Tok.is(tok::l_brace)) {
915 // This is the function body if the ')' or '}' is immediately followed by
916 // a '{'. That cannot happen within a template argument, apart from the
917 // case where a template argument contains a compound literal:
919 // S ( ) : a < b < c > ( d ) { }
920 // // End of declaration, or still inside the template argument?
922 // ... and the case where the template argument contains a lambda:
924 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
927 // FIXME: Disambiguate these cases. Note that the latter case is probably
928 // going to be made ill-formed by core issue 1607.
932 } else if (!MightBeTemplateArgument) {
933 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
939 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
941 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
943 assert(Tok.is(tok::question));
947 while (Tok.isNot(tok::colon)) {
948 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
950 /*ConsumeFinalToken=*/false))
953 // If we found a nested conditional, consume it.
954 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
964 /// \brief A tentative parsing action that can also revert token annotations.
965 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
967 explicit UnannotatedTentativeParsingAction(Parser &Self,
968 tok::TokenKind EndKind)
969 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
970 // Stash away the old token stream, so we can restore it once the
971 // tentative parse is complete.
972 TentativeParsingAction Inner(Self);
973 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
977 void RevertAnnotations() {
980 // Put back the original tokens.
981 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
983 auto Buffer = llvm::make_unique<Token[]>(Toks.size());
984 std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
985 Buffer[Toks.size() - 1] = Self.Tok;
986 Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true);
988 Self.Tok = Toks.front();
995 tok::TokenKind EndKind;
998 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
999 /// container until the end of the current initializer expression (either a
1000 /// default argument or an in-class initializer for a non-static data member).
1002 /// Returns \c true if we reached the end of something initializer-shaped,
1003 /// \c false if we bailed out.
1004 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1005 CachedInitKind CIK) {
1006 // We always want this function to consume at least one token if not at EOF.
1007 bool IsFirstToken = true;
1009 // Number of possible unclosed <s we've seen so far. These might be templates,
1010 // and might not, but if there were none of them (or we know for sure that
1011 // we're within a template), we can avoid a tentative parse.
1012 unsigned AngleCount = 0;
1013 unsigned KnownTemplateCount = 0;
1016 switch (Tok.getKind()) {
1018 // If we might be in a template, perform a tentative parse to check.
1020 // Not a template argument: this is the end of the initializer.
1022 if (KnownTemplateCount)
1025 // We hit a comma inside angle brackets. This is the hard case. The
1026 // rule we follow is:
1027 // * For a default argument, if the tokens after the comma form a
1028 // syntactically-valid parameter-declaration-clause, in which each
1029 // parameter has an initializer, then this comma ends the default
1031 // * For a default initializer, if the tokens after the comma form a
1032 // syntactically-valid init-declarator-list, then this comma ends
1033 // the default initializer.
1035 UnannotatedTentativeParsingAction PA(*this,
1036 CIK == CIK_DefaultInitializer
1037 ? tok::semi : tok::r_paren);
1038 Sema::TentativeAnalysisScope Scope(Actions);
1040 TPResult Result = TPResult::Error;
1043 case CIK_DefaultInitializer:
1044 Result = TryParseInitDeclaratorList();
1045 // If we parsed a complete, ambiguous init-declarator-list, this
1046 // is only syntactically-valid if it's followed by a semicolon.
1047 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1048 Result = TPResult::False;
1051 case CIK_DefaultArgument:
1052 bool InvalidAsDeclaration = false;
1053 Result = TryParseParameterDeclarationClause(
1054 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
1055 // If this is an expression or a declaration with a missing
1056 // 'typename', assume it's not a declaration.
1057 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1058 Result = TPResult::False;
1062 // If what follows could be a declaration, it is a declaration.
1063 if (Result != TPResult::False && Result != TPResult::Error) {
1068 // In the uncommon case that we decide the following tokens are part
1069 // of a template argument, revert any annotations we've performed in
1070 // those tokens. We're not going to look them up until we've parsed
1071 // the rest of the class, and that might add more declarations.
1072 PA.RevertAnnotations();
1075 // Keep going. We know we're inside a template argument list now.
1076 ++KnownTemplateCount;
1080 case tok::annot_module_begin:
1081 case tok::annot_module_end:
1082 case tok::annot_module_include:
1083 // Ran out of tokens.
1087 // FIXME: A '<' can only start a template-id if it's preceded by an
1088 // identifier, an operator-function-id, or a literal-operator-id.
1093 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1094 // that is *never* the end of the initializer. Skip to the ':'.
1095 if (!ConsumeAndStoreConditional(Toks))
1099 case tok::greatergreatergreater:
1100 if (!getLangOpts().CPlusPlus11)
1102 if (AngleCount) --AngleCount;
1103 if (KnownTemplateCount) --KnownTemplateCount;
1105 case tok::greatergreater:
1106 if (!getLangOpts().CPlusPlus11)
1108 if (AngleCount) --AngleCount;
1109 if (KnownTemplateCount) --KnownTemplateCount;
1112 if (AngleCount) --AngleCount;
1113 if (KnownTemplateCount) --KnownTemplateCount;
1116 case tok::kw_template:
1117 // 'template' identifier '<' is known to start a template argument list,
1118 // and can be used to disambiguate the parse.
1119 // FIXME: Support all forms of 'template' unqualified-id '<'.
1120 Toks.push_back(Tok);
1122 if (Tok.is(tok::identifier)) {
1123 Toks.push_back(Tok);
1125 if (Tok.is(tok::less)) {
1127 ++KnownTemplateCount;
1128 Toks.push_back(Tok);
1134 case tok::kw_operator:
1135 // If 'operator' precedes other punctuation, that punctuation loses
1136 // its special behavior.
1137 Toks.push_back(Tok);
1139 switch (Tok.getKind()) {
1141 case tok::greatergreatergreater:
1142 case tok::greatergreater:
1145 Toks.push_back(Tok);
1154 // Recursively consume properly-nested parens.
1155 Toks.push_back(Tok);
1157 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1160 // Recursively consume properly-nested square brackets.
1161 Toks.push_back(Tok);
1163 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1166 // Recursively consume properly-nested braces.
1167 Toks.push_back(Tok);
1169 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1172 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1173 // Since the user wasn't looking for this token (if they were, it would
1174 // already be handled), this isn't balanced. If there is a LHS token at a
1175 // higher level, we will assume that this matches the unbalanced token
1176 // and return it. Otherwise, this is a spurious RHS token, which we
1177 // consume and pass on to downstream code to diagnose.
1179 if (CIK == CIK_DefaultArgument)
1180 return true; // End of the default argument.
1181 if (ParenCount && !IsFirstToken)
1183 Toks.push_back(Tok);
1187 if (BracketCount && !IsFirstToken)
1189 Toks.push_back(Tok);
1193 if (BraceCount && !IsFirstToken)
1195 Toks.push_back(Tok);
1199 case tok::code_completion:
1200 Toks.push_back(Tok);
1201 ConsumeCodeCompletionToken();
1204 case tok::string_literal:
1205 case tok::wide_string_literal:
1206 case tok::utf8_string_literal:
1207 case tok::utf16_string_literal:
1208 case tok::utf32_string_literal:
1209 Toks.push_back(Tok);
1210 ConsumeStringToken();
1213 if (CIK == CIK_DefaultInitializer)
1214 return true; // End of the default initializer.
1218 Toks.push_back(Tok);
1222 IsFirstToken = false;