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 "RAIIObjectsForParser.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/Parse/ParseDiagnostic.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);
55 HandleMemberFunctionDeclDelays(D, FnD);
59 if (TryConsumeToken(tok::equal)) {
67 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
68 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
69 Diag(KWLoc, getLangOpts().CPlusPlus11
70 ? diag::warn_cxx98_compat_defaulted_deleted_function
71 : diag::ext_defaulted_deleted_function)
73 Actions.SetDeclDeleted(FnD, KWLoc);
75 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
76 DeclAsFunction->setRangeEnd(KWEndLoc);
78 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
79 Diag(KWLoc, getLangOpts().CPlusPlus11
80 ? diag::warn_cxx98_compat_defaulted_deleted_function
81 : diag::ext_defaulted_deleted_function)
83 Actions.SetDeclDefaulted(FnD, KWLoc);
84 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
85 DeclAsFunction->setRangeEnd(KWEndLoc);
88 llvm_unreachable("function definition after = not 'delete' or 'default'");
91 if (Tok.is(tok::comma)) {
92 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
95 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
96 Delete ? "delete" : "default")) {
103 // In delayed template parsing mode, if we are within a class template
104 // or if we are about to parse function member template then consume
105 // the tokens and store them for parsing at the end of the translation unit.
106 if (getLangOpts().DelayedTemplateParsing &&
107 D.getFunctionDefinitionKind() == FDK_Definition &&
108 !D.getDeclSpec().isConstexprSpecified() &&
109 !(FnD && FnD->getAsFunction() &&
110 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
111 ((Actions.CurContext->isDependentContext() ||
112 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
113 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
114 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
117 LexTemplateFunctionForLateParsing(Toks);
120 FunctionDecl *FD = FnD->getAsFunction();
121 Actions.CheckForFunctionRedefinition(FD);
122 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
128 // Consume the tokens and store them for later parsing.
130 LexedMethod* LM = new LexedMethod(this, FnD);
131 getCurrentClass().LateParsedDeclarations.push_back(LM);
132 LM->TemplateScope = getCurScope()->isTemplateParamScope();
133 CachedTokens &Toks = LM->Toks;
135 tok::TokenKind kind = Tok.getKind();
136 // Consume everything up to (and including) the left brace of the
138 if (ConsumeAndStoreFunctionPrologue(Toks)) {
139 // We didn't find the left-brace we expected after the
140 // constructor initializer; we already printed an error, and it's likely
141 // impossible to recover, so don't try to parse this method later.
142 // Skip over the rest of the decl and back to somewhere that looks
145 delete getCurrentClass().LateParsedDeclarations.back();
146 getCurrentClass().LateParsedDeclarations.pop_back();
149 // Consume everything up to (and including) the matching right brace.
150 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
153 // If we're in a function-try-block, we need to store all the catch blocks.
154 if (kind == tok::kw_try) {
155 while (Tok.is(tok::kw_catch)) {
156 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
157 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
162 // If this is a friend function, mark that it's late-parsed so that
163 // it's still known to be a definition even before we attach the
164 // parsed body. Sema needs to treat friend function definitions
165 // differently during template instantiation, and it's possible for
166 // the containing class to be instantiated before all its member
167 // function definitions are parsed.
169 // If you remove this, you can remove the code that clears the flag
170 // after parsing the member.
171 if (D.getDeclSpec().isFriendSpecified()) {
172 FunctionDecl *FD = FnD->getAsFunction();
173 Actions.CheckForFunctionRedefinition(FD);
174 FD->setLateTemplateParsed(true);
177 // If semantic analysis could not build a function declaration,
178 // just throw away the late-parsed declaration.
179 delete getCurrentClass().LateParsedDeclarations.back();
180 getCurrentClass().LateParsedDeclarations.pop_back();
186 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
187 /// specified Declarator is a well formed C++ non-static data member
188 /// declaration. Now lex its initializer and store its tokens for parsing
189 /// after the class is complete.
190 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
191 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
192 "Current token not a '{' or '='!");
194 LateParsedMemberInitializer *MI =
195 new LateParsedMemberInitializer(this, VarD);
196 getCurrentClass().LateParsedDeclarations.push_back(MI);
197 CachedTokens &Toks = MI->Toks;
199 tok::TokenKind kind = Tok.getKind();
200 if (kind == tok::equal) {
205 if (kind == tok::l_brace) {
206 // Begin by storing the '{' token.
210 // Consume everything up to (and including) the matching right brace.
211 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
213 // Consume everything up to (but excluding) the comma or semicolon.
214 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
217 // Store an artificial EOF token to ensure that we don't run off the end of
218 // the initializer when we come to parse it.
221 Eof.setKind(tok::eof);
222 Eof.setLocation(Tok.getLocation());
223 Eof.setEofData(VarD);
227 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
228 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
229 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
230 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
232 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
233 : Self(P), Class(C) {}
235 Parser::LateParsedClass::~LateParsedClass() {
236 Self->DeallocateParsedClasses(Class);
239 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
240 Self->ParseLexedMethodDeclarations(*Class);
243 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
244 Self->ParseLexedMemberInitializers(*Class);
247 void Parser::LateParsedClass::ParseLexedMethodDefs() {
248 Self->ParseLexedMethodDefs(*Class);
251 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
252 Self->ParseLexedMethodDeclaration(*this);
255 void Parser::LexedMethod::ParseLexedMethodDefs() {
256 Self->ParseLexedMethodDef(*this);
259 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
260 Self->ParseLexedMemberInitializer(*this);
263 /// ParseLexedMethodDeclarations - We finished parsing the member
264 /// specification of a top (non-nested) C++ class. Now go over the
265 /// stack of method declarations with some parts for which parsing was
266 /// delayed (such as default arguments) and parse them.
267 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
268 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
269 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
271 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
272 if (HasTemplateScope) {
273 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
274 ++CurTemplateDepthTracker;
277 // The current scope is still active if we're the top-level class.
278 // Otherwise we'll need to push and enter a new scope.
279 bool HasClassScope = !Class.TopLevelClass;
280 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
283 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
284 Class.TagOrTemplate);
286 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
287 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
291 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
292 Class.TagOrTemplate);
295 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
296 // If this is a member template, introduce the template parameter scope.
297 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
298 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
299 if (LM.TemplateScope) {
300 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
301 ++CurTemplateDepthTracker;
303 // Start the delayed C++ method declaration
304 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
306 // Introduce the parameters into scope and parse their default
308 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
309 Scope::FunctionDeclarationScope | Scope::DeclScope);
310 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
311 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
312 // Introduce the parameter into scope.
313 bool HasUnparsed = Param->hasUnparsedDefaultArg();
314 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
315 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
316 // Mark the end of the default argument so that we know when to stop when
317 // we parse it later on.
318 Token LastDefaultArgToken = Toks->back();
320 DefArgEnd.startToken();
321 DefArgEnd.setKind(tok::eof);
322 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
323 DefArgEnd.setEofData(Param);
324 Toks->push_back(DefArgEnd);
326 // Parse the default argument from its saved token stream.
327 Toks->push_back(Tok); // So that the current token doesn't get lost
328 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
330 // Consume the previously-pushed token.
334 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
335 SourceLocation EqualLoc = ConsumeToken();
337 // The argument isn't actually potentially evaluated unless it is
339 EnterExpressionEvaluationContext Eval(Actions,
340 Sema::PotentiallyEvaluatedIfUsed,
343 ExprResult DefArgResult;
344 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
345 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
346 DefArgResult = ParseBraceInitializer();
348 DefArgResult = ParseAssignmentExpression();
349 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
350 if (DefArgResult.isInvalid()) {
351 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
353 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
354 // The last two tokens are the terminator and the saved value of
355 // Tok; the last token in the default argument is the one before
357 assert(Toks->size() >= 3 && "expected a token in default arg");
358 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
359 << SourceRange(Tok.getLocation(),
360 (*Toks)[Toks->size() - 3].getLocation());
362 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
366 // There could be leftover tokens (e.g. because of an error).
367 // Skip through until we reach the 'end of default argument' token.
368 while (Tok.isNot(tok::eof))
371 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
375 LM.DefaultArgs[I].Toks = nullptr;
376 } else if (HasUnparsed) {
377 assert(Param->hasInheritedDefaultArg());
378 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
379 ParmVarDecl *OldParam = Old->getParamDecl(I);
380 assert (!OldParam->hasUnparsedDefaultArg());
381 if (OldParam->hasUninstantiatedDefaultArg())
382 Param->setUninstantiatedDefaultArg(
383 Param->getUninstantiatedDefaultArg());
385 Param->setDefaultArg(OldParam->getInit());
389 // Parse a delayed exception-specification, if there is one.
390 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
391 // Add the 'stop' token.
392 Token LastExceptionSpecToken = Toks->back();
393 Token ExceptionSpecEnd;
394 ExceptionSpecEnd.startToken();
395 ExceptionSpecEnd.setKind(tok::eof);
396 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
397 ExceptionSpecEnd.setEofData(LM.Method);
398 Toks->push_back(ExceptionSpecEnd);
400 // Parse the default argument from its saved token stream.
401 Toks->push_back(Tok); // So that the current token doesn't get lost
402 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
404 // Consume the previously-pushed token.
407 // C++11 [expr.prim.general]p3:
408 // If a declaration declares a member function or member function
409 // template of a class X, the expression this is a prvalue of type
410 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
411 // and the end of the function-definition, member-declarator, or
413 CXXMethodDecl *Method;
414 if (FunctionTemplateDecl *FunTmpl
415 = dyn_cast<FunctionTemplateDecl>(LM.Method))
416 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
418 Method = cast<CXXMethodDecl>(LM.Method);
420 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
421 Method->getTypeQualifiers(),
422 getLangOpts().CPlusPlus11);
424 // Parse the exception-specification.
425 SourceRange SpecificationRange;
426 SmallVector<ParsedType, 4> DynamicExceptions;
427 SmallVector<SourceRange, 4> DynamicExceptionRanges;
428 ExprResult NoexceptExpr;
429 CachedTokens *ExceptionSpecTokens;
431 ExceptionSpecificationType EST
432 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
434 DynamicExceptionRanges, NoexceptExpr,
435 ExceptionSpecTokens);
437 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
438 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
440 // Attach the exception-specification to the method.
441 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
444 DynamicExceptionRanges,
445 NoexceptExpr.isUsable()?
446 NoexceptExpr.get() : nullptr);
448 // There could be leftover tokens (e.g. because of an error).
449 // Skip through until we reach the original token position.
450 while (Tok.isNot(tok::eof))
453 // Clean up the remaining EOF token.
454 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
458 LM.ExceptionSpecTokens = nullptr;
461 PrototypeScope.Exit();
463 // Finish the delayed C++ method declaration.
464 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
467 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
468 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
469 /// collected during its parsing and parse them all.
470 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
471 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
472 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
473 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
474 if (HasTemplateScope) {
475 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
476 ++CurTemplateDepthTracker;
478 bool HasClassScope = !Class.TopLevelClass;
479 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
482 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
483 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
487 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
488 // If this is a member template, introduce the template parameter scope.
489 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
490 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
491 if (LM.TemplateScope) {
492 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
493 ++CurTemplateDepthTracker;
496 assert(!LM.Toks.empty() && "Empty body!");
497 Token LastBodyToken = LM.Toks.back();
499 BodyEnd.startToken();
500 BodyEnd.setKind(tok::eof);
501 BodyEnd.setLocation(LastBodyToken.getEndLoc());
502 BodyEnd.setEofData(LM.D);
503 LM.Toks.push_back(BodyEnd);
504 // Append the current token at the end of the new token stream so that it
506 LM.Toks.push_back(Tok);
507 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
509 // Consume the previously pushed token.
510 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
511 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
512 && "Inline method not starting with '{', ':' or 'try'");
514 // Parse the method body. Function body parsing code is similar enough
515 // to be re-used for method bodies as well.
516 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
517 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
519 if (Tok.is(tok::kw_try)) {
520 ParseFunctionTryBlock(LM.D, FnScope);
522 while (Tok.isNot(tok::eof))
525 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
529 if (Tok.is(tok::colon)) {
530 ParseConstructorInitializer(LM.D);
533 if (!Tok.is(tok::l_brace)) {
535 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
537 while (Tok.isNot(tok::eof))
540 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
545 Actions.ActOnDefaultCtorInitializers(LM.D);
547 assert((Actions.getDiagnostics().hasErrorOccurred() ||
548 !isa<FunctionTemplateDecl>(LM.D) ||
549 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
550 < TemplateParameterDepth) &&
551 "TemplateParameterDepth should be greater than the depth of "
552 "current template being instantiated!");
554 ParseFunctionStatementBody(LM.D, FnScope);
556 // Clear the late-template-parsed bit if we set it before.
558 LM.D->getAsFunction()->setLateTemplateParsed(false);
560 while (Tok.isNot(tok::eof))
563 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
566 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
567 Actions.ActOnFinishInlineMethodDef(MD);
570 /// ParseLexedMemberInitializers - We finished parsing the member specification
571 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
572 /// initializers that were collected during its parsing and parse them all.
573 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
574 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
575 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
577 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
578 if (HasTemplateScope) {
579 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
580 ++CurTemplateDepthTracker;
582 // Set or update the scope flags.
583 bool AlreadyHasClassScope = Class.TopLevelClass;
584 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
585 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
586 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
588 if (!AlreadyHasClassScope)
589 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
590 Class.TagOrTemplate);
592 if (!Class.LateParsedDeclarations.empty()) {
593 // C++11 [expr.prim.general]p4:
594 // Otherwise, if a member-declarator declares a non-static data member
595 // (9.2) of a class X, the expression this is a prvalue of type "pointer
596 // to X" within the optional brace-or-equal-initializer. It shall not
597 // appear elsewhere in the member-declarator.
598 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
599 /*TypeQuals=*/(unsigned)0);
601 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
602 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
606 if (!AlreadyHasClassScope)
607 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
608 Class.TagOrTemplate);
610 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
613 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
614 if (!MI.Field || MI.Field->isInvalidDecl())
617 // Append the current token at the end of the new token stream so that it
619 MI.Toks.push_back(Tok);
620 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
622 // Consume the previously pushed token.
623 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
625 SourceLocation EqualLoc;
627 Actions.ActOnStartCXXInClassMemberInitializer();
629 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
632 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
635 // The next token should be our artificial terminating EOF token.
636 if (Tok.isNot(tok::eof)) {
637 if (!Init.isInvalid()) {
638 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
639 if (!EndLoc.isValid())
640 EndLoc = Tok.getLocation();
641 // No fixit; we can't recover as if there were a semicolon here.
642 Diag(EndLoc, diag::err_expected_semi_decl_list);
645 // Consume tokens until we hit the artificial EOF.
646 while (Tok.isNot(tok::eof))
649 // Make sure this is *our* artificial EOF token.
650 if (Tok.getEofData() == MI.Field)
654 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
655 /// container until the token 'T' is reached (which gets
656 /// consumed/stored too, if ConsumeFinalToken).
657 /// If StopAtSemi is true, then we will stop early at a ';' character.
658 /// Returns true if token 'T1' or 'T2' was found.
659 /// NOTE: This is a specialized version of Parser::SkipUntil.
660 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
662 bool StopAtSemi, bool ConsumeFinalToken) {
663 // We always want this function to consume at least one token if the first
664 // token isn't T and if not at EOF.
665 bool isFirstTokenConsumed = true;
667 // If we found one of the tokens, stop and return true.
668 if (Tok.is(T1) || Tok.is(T2)) {
669 if (ConsumeFinalToken) {
676 switch (Tok.getKind()) {
678 case tok::annot_module_begin:
679 case tok::annot_module_end:
680 case tok::annot_module_include:
681 // Ran out of tokens.
685 // Recursively consume properly-nested parens.
688 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
691 // Recursively consume properly-nested square brackets.
694 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
697 // Recursively consume properly-nested braces.
700 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
703 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
704 // Since the user wasn't looking for this token (if they were, it would
705 // already be handled), this isn't balanced. If there is a LHS token at a
706 // higher level, we will assume that this matches the unbalanced token
707 // and return it. Otherwise, this is a spurious RHS token, which we skip.
709 if (ParenCount && !isFirstTokenConsumed)
710 return false; // Matches something.
715 if (BracketCount && !isFirstTokenConsumed)
716 return false; // Matches something.
721 if (BraceCount && !isFirstTokenConsumed)
722 return false; // Matches something.
727 case tok::code_completion:
729 ConsumeCodeCompletionToken();
732 case tok::string_literal:
733 case tok::wide_string_literal:
734 case tok::utf8_string_literal:
735 case tok::utf16_string_literal:
736 case tok::utf32_string_literal:
738 ConsumeStringToken();
745 // consume this token.
750 isFirstTokenConsumed = false;
754 /// \brief Consume tokens and store them in the passed token container until
755 /// we've passed the try keyword and constructor initializers and have consumed
756 /// the opening brace of the function body. The opening brace will be consumed
757 /// if and only if there was no error.
759 /// \return True on error.
760 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
761 if (Tok.is(tok::kw_try)) {
766 if (Tok.isNot(tok::colon)) {
767 // Easy case, just a function body.
769 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
770 // brace: an opening one is the function body, while a closing one probably
771 // means we've reached the end of the class.
772 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
774 /*ConsumeFinalToken=*/false);
775 if (Tok.isNot(tok::l_brace))
776 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
786 // We can't reliably skip over a mem-initializer-id, because it could be
787 // a template-id involving not-yet-declared names. Given:
789 // S ( ) : a < b < c > ( e )
791 // 'e' might be an initializer or part of a template argument, depending
792 // on whether 'b' is a template.
794 // Track whether we might be inside a template argument. We can give
795 // significantly better diagnostics if we know that we're not.
796 bool MightBeTemplateArgument = false;
799 // Skip over the mem-initializer-id, if possible.
800 if (Tok.is(tok::kw_decltype)) {
802 SourceLocation OpenLoc = ConsumeToken();
803 if (Tok.isNot(tok::l_paren))
804 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
808 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
809 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
810 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
815 // Walk over a component of a nested-name-specifier.
816 if (Tok.is(tok::coloncolon)) {
820 if (Tok.is(tok::kw_template)) {
826 if (Tok.isOneOf(tok::identifier, tok::kw_template)) {
829 } else if (Tok.is(tok::code_completion)) {
831 ConsumeCodeCompletionToken();
832 // Consume the rest of the initializers permissively.
833 // FIXME: We should be able to perform code-completion here even if
834 // there isn't a subsequent '{' token.
835 MightBeTemplateArgument = true;
840 } while (Tok.is(tok::coloncolon));
842 if (Tok.is(tok::less))
843 MightBeTemplateArgument = true;
845 if (MightBeTemplateArgument) {
846 // We may be inside a template argument list. Grab up to the start of the
847 // next parenthesized initializer or braced-init-list. This *might* be the
848 // initializer, or it might be a subexpression in the template argument
850 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
851 // if all angles are closed.
852 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
854 /*ConsumeFinalToken=*/false)) {
855 // We're not just missing the initializer, we're also missing the
857 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
859 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
860 // We found something weird in a mem-initializer-id.
861 if (getLangOpts().CPlusPlus11)
862 return Diag(Tok.getLocation(), diag::err_expected_either)
863 << tok::l_paren << tok::l_brace;
865 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
868 tok::TokenKind kind = Tok.getKind();
870 bool IsLParen = (kind == tok::l_paren);
871 SourceLocation OpenLoc = Tok.getLocation();
876 assert(kind == tok::l_brace && "Must be left paren or brace here.");
878 // In C++03, this has to be the start of the function body, which
879 // means the initializer is malformed; we'll diagnose it later.
880 if (!getLangOpts().CPlusPlus11)
884 // Grab the initializer (or the subexpression of the template argument).
885 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
886 // if we might be inside the braces of a lambda-expression.
887 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
888 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
889 Diag(Tok, diag::err_expected) << CloseKind;
890 Diag(OpenLoc, diag::note_matching) << kind;
894 // Grab pack ellipsis, if present.
895 if (Tok.is(tok::ellipsis)) {
900 // If we know we just consumed a mem-initializer, we must have ',' or '{'
902 if (Tok.is(tok::comma)) {
905 } else if (Tok.is(tok::l_brace)) {
906 // This is the function body if the ')' or '}' is immediately followed by
907 // a '{'. That cannot happen within a template argument, apart from the
908 // case where a template argument contains a compound literal:
910 // S ( ) : a < b < c > ( d ) { }
911 // // End of declaration, or still inside the template argument?
913 // ... and the case where the template argument contains a lambda:
915 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
918 // FIXME: Disambiguate these cases. Note that the latter case is probably
919 // going to be made ill-formed by core issue 1607.
923 } else if (!MightBeTemplateArgument) {
924 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
930 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
932 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
934 assert(Tok.is(tok::question));
938 while (Tok.isNot(tok::colon)) {
939 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
941 /*ConsumeFinalToken=*/false))
944 // If we found a nested conditional, consume it.
945 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
955 /// \brief A tentative parsing action that can also revert token annotations.
956 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
958 explicit UnannotatedTentativeParsingAction(Parser &Self,
959 tok::TokenKind EndKind)
960 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
961 // Stash away the old token stream, so we can restore it once the
962 // tentative parse is complete.
963 TentativeParsingAction Inner(Self);
964 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
968 void RevertAnnotations() {
971 // Put back the original tokens.
972 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
974 Token *Buffer = new Token[Toks.size()];
975 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
976 Buffer[Toks.size() - 1] = Self.Tok;
977 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
979 Self.Tok = Toks.front();
986 tok::TokenKind EndKind;
989 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
990 /// container until the end of the current initializer expression (either a
991 /// default argument or an in-class initializer for a non-static data member).
993 /// Returns \c true if we reached the end of something initializer-shaped,
994 /// \c false if we bailed out.
995 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
996 CachedInitKind CIK) {
997 // We always want this function to consume at least one token if not at EOF.
998 bool IsFirstToken = true;
1000 // Number of possible unclosed <s we've seen so far. These might be templates,
1001 // and might not, but if there were none of them (or we know for sure that
1002 // we're within a template), we can avoid a tentative parse.
1003 unsigned AngleCount = 0;
1004 unsigned KnownTemplateCount = 0;
1007 switch (Tok.getKind()) {
1009 // If we might be in a template, perform a tentative parse to check.
1011 // Not a template argument: this is the end of the initializer.
1013 if (KnownTemplateCount)
1016 // We hit a comma inside angle brackets. This is the hard case. The
1017 // rule we follow is:
1018 // * For a default argument, if the tokens after the comma form a
1019 // syntactically-valid parameter-declaration-clause, in which each
1020 // parameter has an initializer, then this comma ends the default
1022 // * For a default initializer, if the tokens after the comma form a
1023 // syntactically-valid init-declarator-list, then this comma ends
1024 // the default initializer.
1026 UnannotatedTentativeParsingAction PA(*this,
1027 CIK == CIK_DefaultInitializer
1028 ? tok::semi : tok::r_paren);
1029 Sema::TentativeAnalysisScope Scope(Actions);
1031 TPResult Result = TPResult::Error;
1034 case CIK_DefaultInitializer:
1035 Result = TryParseInitDeclaratorList();
1036 // If we parsed a complete, ambiguous init-declarator-list, this
1037 // is only syntactically-valid if it's followed by a semicolon.
1038 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1039 Result = TPResult::False;
1042 case CIK_DefaultArgument:
1043 bool InvalidAsDeclaration = false;
1044 Result = TryParseParameterDeclarationClause(
1045 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
1046 // If this is an expression or a declaration with a missing
1047 // 'typename', assume it's not a declaration.
1048 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1049 Result = TPResult::False;
1053 // If what follows could be a declaration, it is a declaration.
1054 if (Result != TPResult::False && Result != TPResult::Error) {
1059 // In the uncommon case that we decide the following tokens are part
1060 // of a template argument, revert any annotations we've performed in
1061 // those tokens. We're not going to look them up until we've parsed
1062 // the rest of the class, and that might add more declarations.
1063 PA.RevertAnnotations();
1066 // Keep going. We know we're inside a template argument list now.
1067 ++KnownTemplateCount;
1071 case tok::annot_module_begin:
1072 case tok::annot_module_end:
1073 case tok::annot_module_include:
1074 // Ran out of tokens.
1078 // FIXME: A '<' can only start a template-id if it's preceded by an
1079 // identifier, an operator-function-id, or a literal-operator-id.
1084 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1085 // that is *never* the end of the initializer. Skip to the ':'.
1086 if (!ConsumeAndStoreConditional(Toks))
1090 case tok::greatergreatergreater:
1091 if (!getLangOpts().CPlusPlus11)
1093 if (AngleCount) --AngleCount;
1094 if (KnownTemplateCount) --KnownTemplateCount;
1096 case tok::greatergreater:
1097 if (!getLangOpts().CPlusPlus11)
1099 if (AngleCount) --AngleCount;
1100 if (KnownTemplateCount) --KnownTemplateCount;
1103 if (AngleCount) --AngleCount;
1104 if (KnownTemplateCount) --KnownTemplateCount;
1107 case tok::kw_template:
1108 // 'template' identifier '<' is known to start a template argument list,
1109 // and can be used to disambiguate the parse.
1110 // FIXME: Support all forms of 'template' unqualified-id '<'.
1111 Toks.push_back(Tok);
1113 if (Tok.is(tok::identifier)) {
1114 Toks.push_back(Tok);
1116 if (Tok.is(tok::less)) {
1118 ++KnownTemplateCount;
1119 Toks.push_back(Tok);
1125 case tok::kw_operator:
1126 // If 'operator' precedes other punctuation, that punctuation loses
1127 // its special behavior.
1128 Toks.push_back(Tok);
1130 switch (Tok.getKind()) {
1132 case tok::greatergreatergreater:
1133 case tok::greatergreater:
1136 Toks.push_back(Tok);
1145 // Recursively consume properly-nested parens.
1146 Toks.push_back(Tok);
1148 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1151 // Recursively consume properly-nested square brackets.
1152 Toks.push_back(Tok);
1154 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1157 // Recursively consume properly-nested braces.
1158 Toks.push_back(Tok);
1160 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1163 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1164 // Since the user wasn't looking for this token (if they were, it would
1165 // already be handled), this isn't balanced. If there is a LHS token at a
1166 // higher level, we will assume that this matches the unbalanced token
1167 // and return it. Otherwise, this is a spurious RHS token, which we
1168 // consume and pass on to downstream code to diagnose.
1170 if (CIK == CIK_DefaultArgument)
1171 return true; // End of the default argument.
1172 if (ParenCount && !IsFirstToken)
1174 Toks.push_back(Tok);
1178 if (BracketCount && !IsFirstToken)
1180 Toks.push_back(Tok);
1184 if (BraceCount && !IsFirstToken)
1186 Toks.push_back(Tok);
1190 case tok::code_completion:
1191 Toks.push_back(Tok);
1192 ConsumeCodeCompletionToken();
1195 case tok::string_literal:
1196 case tok::wide_string_literal:
1197 case tok::utf8_string_literal:
1198 case tok::utf16_string_literal:
1199 case tok::utf32_string_literal:
1200 Toks.push_back(Tok);
1201 ConsumeStringToken();
1204 if (CIK == CIK_DefaultInitializer)
1205 return true; // End of the default initializer.
1209 Toks.push_back(Tok);
1213 IsFirstToken = false;