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 /// Get the FunctionDecl for a function or function template decl.
23 static FunctionDecl *getFunctionDecl(Decl *D) {
24 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(D))
26 return cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
29 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
30 /// Declarator is a well formed C++ inline method definition. Now lex its body
31 /// and store its tokens for parsing after the C++ class is complete.
32 NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
33 AttributeList *AccessAttrs,
35 const ParsedTemplateInfo &TemplateInfo,
36 const VirtSpecifiers& VS,
37 FunctionDefinitionKind DefinitionKind,
39 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
40 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
41 Tok.is(tok::equal)) &&
42 "Current token not a '{', ':', '=', or 'try'!");
44 MultiTemplateParamsArg TemplateParams(
45 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
46 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
49 D.setFunctionDefinitionKind(DefinitionKind);
50 if (D.getDeclSpec().isFriendSpecified())
51 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
54 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
58 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
59 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
61 Actions.AddInitializerToDecl(FnD, Init.get(), false,
62 TypeSpecContainsAuto);
64 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
68 HandleMemberFunctionDeclDelays(D, FnD);
72 if (Tok.is(tok::equal)) {
82 if (Tok.is(tok::kw_delete)) {
83 Diag(Tok, getLangOpts().CPlusPlus11 ?
84 diag::warn_cxx98_compat_deleted_function :
85 diag::ext_deleted_function);
87 KWLoc = ConsumeToken();
88 Actions.SetDeclDeleted(FnD, KWLoc);
90 } else if (Tok.is(tok::kw_default)) {
91 Diag(Tok, getLangOpts().CPlusPlus11 ?
92 diag::warn_cxx98_compat_defaulted_function :
93 diag::ext_defaulted_function);
95 KWLoc = ConsumeToken();
96 Actions.SetDeclDefaulted(FnD, KWLoc);
98 llvm_unreachable("function definition after = not 'delete' or 'default'");
101 if (Tok.is(tok::comma)) {
102 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
104 SkipUntil(tok::semi);
106 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
107 Delete ? "delete" : "default", tok::semi);
113 // In delayed template parsing mode, if we are within a class template
114 // or if we are about to parse function member template then consume
115 // the tokens and store them for parsing at the end of the translation unit.
116 if (getLangOpts().DelayedTemplateParsing &&
117 DefinitionKind == FDK_Definition &&
118 !D.getDeclSpec().isConstexprSpecified() &&
119 !(FnD && getFunctionDecl(FnD) &&
120 getFunctionDecl(FnD)->getResultType()->getContainedAutoType()) &&
121 ((Actions.CurContext->isDependentContext() ||
122 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
123 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
124 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
127 LexTemplateFunctionForLateParsing(Toks);
130 FunctionDecl *FD = getFunctionDecl(FnD);
131 Actions.CheckForFunctionRedefinition(FD);
132 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
138 // Consume the tokens and store them for later parsing.
140 LexedMethod* LM = new LexedMethod(this, FnD);
141 getCurrentClass().LateParsedDeclarations.push_back(LM);
142 LM->TemplateScope = getCurScope()->isTemplateParamScope();
143 CachedTokens &Toks = LM->Toks;
145 tok::TokenKind kind = Tok.getKind();
146 // Consume everything up to (and including) the left brace of the
148 if (ConsumeAndStoreFunctionPrologue(Toks)) {
149 // We didn't find the left-brace we expected after the
150 // constructor initializer; we already printed an error, and it's likely
151 // impossible to recover, so don't try to parse this method later.
152 // Skip over the rest of the decl and back to somewhere that looks
155 delete getCurrentClass().LateParsedDeclarations.back();
156 getCurrentClass().LateParsedDeclarations.pop_back();
159 // Consume everything up to (and including) the matching right brace.
160 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
163 // If we're in a function-try-block, we need to store all the catch blocks.
164 if (kind == tok::kw_try) {
165 while (Tok.is(tok::kw_catch)) {
166 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
167 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
172 // If this is a friend function, mark that it's late-parsed so that
173 // it's still known to be a definition even before we attach the
174 // parsed body. Sema needs to treat friend function definitions
175 // differently during template instantiation, and it's possible for
176 // the containing class to be instantiated before all its member
177 // function definitions are parsed.
179 // If you remove this, you can remove the code that clears the flag
180 // after parsing the member.
181 if (D.getDeclSpec().isFriendSpecified()) {
182 FunctionDecl *FD = getFunctionDecl(FnD);
183 Actions.CheckForFunctionRedefinition(FD);
184 FD->setLateTemplateParsed(true);
187 // If semantic analysis could not build a function declaration,
188 // just throw away the late-parsed declaration.
189 delete getCurrentClass().LateParsedDeclarations.back();
190 getCurrentClass().LateParsedDeclarations.pop_back();
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 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
201 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
202 "Current token not a '{' or '='!");
204 LateParsedMemberInitializer *MI =
205 new LateParsedMemberInitializer(this, VarD);
206 getCurrentClass().LateParsedDeclarations.push_back(MI);
207 CachedTokens &Toks = MI->Toks;
209 tok::TokenKind kind = Tok.getKind();
210 if (kind == tok::equal) {
215 if (kind == tok::l_brace) {
216 // Begin by storing the '{' token.
220 // Consume everything up to (and including) the matching right brace.
221 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
223 // Consume everything up to (but excluding) the comma or semicolon.
224 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
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.
231 Eof.setKind(tok::eof);
232 Eof.setLocation(Tok.getLocation());
236 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
237 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
238 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
239 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
241 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
242 : Self(P), Class(C) {}
244 Parser::LateParsedClass::~LateParsedClass() {
245 Self->DeallocateParsedClasses(Class);
248 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
249 Self->ParseLexedMethodDeclarations(*Class);
252 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
253 Self->ParseLexedMemberInitializers(*Class);
256 void Parser::LateParsedClass::ParseLexedMethodDefs() {
257 Self->ParseLexedMethodDefs(*Class);
260 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
261 Self->ParseLexedMethodDeclaration(*this);
264 void Parser::LexedMethod::ParseLexedMethodDefs() {
265 Self->ParseLexedMethodDef(*this);
268 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
269 Self->ParseLexedMemberInitializer(*this);
272 /// ParseLexedMethodDeclarations - We finished parsing the member
273 /// specification of a top (non-nested) C++ class. Now go over the
274 /// stack of method declarations with some parts for which parsing was
275 /// delayed (such as default arguments) and parse them.
276 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
277 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
278 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
279 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
280 if (HasTemplateScope) {
281 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
282 ++CurTemplateDepthTracker;
285 // The current scope is still active if we're the top-level class.
286 // Otherwise we'll need to push and enter a new scope.
287 bool HasClassScope = !Class.TopLevelClass;
288 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
291 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
293 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
294 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
298 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
301 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
302 // If this is a member template, introduce the template parameter scope.
303 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
304 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
305 if (LM.TemplateScope) {
306 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
307 ++CurTemplateDepthTracker;
309 // Start the delayed C++ method declaration
310 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
312 // Introduce the parameters into scope and parse their default
314 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
315 Scope::FunctionDeclarationScope | Scope::DeclScope);
316 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
317 // Introduce the parameter into scope.
318 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
319 LM.DefaultArgs[I].Param);
321 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
322 // Save the current token position.
323 SourceLocation origLoc = Tok.getLocation();
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->front(), Toks->size(), true, false);
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(Actions,
339 Sema::PotentiallyEvaluatedIfUsed,
340 LM.DefaultArgs[I].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 if (DefArgResult.isInvalid())
349 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
351 if (Tok.is(tok::cxx_defaultarg_end))
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(LM.DefaultArgs[I].Param, EqualLoc,
363 DefArgResult.take());
366 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
367 Tok.getLocation()) &&
368 "ParseAssignmentExpression went over the default arg tokens!");
369 // There could be leftover tokens (e.g. because of an error).
370 // Skip through until we reach the original token position.
371 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
375 LM.DefaultArgs[I].Toks = 0;
379 PrototypeScope.Exit();
381 // Finish the delayed C++ method declaration.
382 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
385 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
386 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
387 /// collected during its parsing and parse them all.
388 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
389 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
390 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
391 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
392 if (HasTemplateScope) {
393 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
394 ++CurTemplateDepthTracker;
396 bool HasClassScope = !Class.TopLevelClass;
397 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
400 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
401 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
405 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
406 // If this is a member template, introduce the template parameter scope.
407 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
408 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
409 if (LM.TemplateScope) {
410 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
411 ++CurTemplateDepthTracker;
413 // Save the current token position.
414 SourceLocation origLoc = Tok.getLocation();
416 assert(!LM.Toks.empty() && "Empty body!");
417 // Append the current token at the end of the new token stream so that it
419 LM.Toks.push_back(Tok);
420 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
422 // Consume the previously pushed token.
423 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
424 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
425 && "Inline method not starting with '{', ':' or 'try'");
427 // Parse the method body. Function body parsing code is similar enough
428 // to be re-used for method bodies as well.
429 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
430 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
432 if (Tok.is(tok::kw_try)) {
433 ParseFunctionTryBlock(LM.D, FnScope);
434 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
435 Tok.getLocation()) &&
436 "ParseFunctionTryBlock went over the cached tokens!");
437 // There could be leftover tokens (e.g. because of an error).
438 // Skip through until we reach the original token position.
439 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
443 if (Tok.is(tok::colon)) {
444 ParseConstructorInitializer(LM.D);
447 if (!Tok.is(tok::l_brace)) {
449 Actions.ActOnFinishFunctionBody(LM.D, 0);
450 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
455 Actions.ActOnDefaultCtorInitializers(LM.D);
457 assert((Actions.getDiagnostics().hasErrorOccurred() ||
458 !isa<FunctionTemplateDecl>(LM.D) ||
459 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
460 < TemplateParameterDepth) &&
461 "TemplateParameterDepth should be greater than the depth of "
462 "current template being instantiated!");
464 ParseFunctionStatementBody(LM.D, FnScope);
466 // Clear the late-template-parsed bit if we set it before.
467 if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false);
469 if (Tok.getLocation() != origLoc) {
470 // Due to parsing error, we either went over the cached tokens or
471 // there are still cached tokens left. If it's the latter case skip the
473 // Since this is an uncommon situation that should be avoided, use the
474 // expensive isBeforeInTranslationUnit call.
475 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
477 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
482 /// ParseLexedMemberInitializers - We finished parsing the member specification
483 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
484 /// initializers that were collected during its parsing and parse them all.
485 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
486 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
487 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
489 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
490 if (HasTemplateScope) {
491 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
492 ++CurTemplateDepthTracker;
494 // Set or update the scope flags.
495 bool AlreadyHasClassScope = Class.TopLevelClass;
496 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
497 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
498 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
500 if (!AlreadyHasClassScope)
501 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
502 Class.TagOrTemplate);
504 if (!Class.LateParsedDeclarations.empty()) {
505 // C++11 [expr.prim.general]p4:
506 // Otherwise, if a member-declarator declares a non-static data member
507 // (9.2) of a class X, the expression this is a prvalue of type "pointer
508 // to X" within the optional brace-or-equal-initializer. It shall not
509 // appear elsewhere in the member-declarator.
510 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
511 /*TypeQuals=*/(unsigned)0);
513 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
514 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
518 if (!AlreadyHasClassScope)
519 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
520 Class.TagOrTemplate);
522 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
525 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
526 if (!MI.Field || MI.Field->isInvalidDecl())
529 // Append the current token at the end of the new token stream so that it
531 MI.Toks.push_back(Tok);
532 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
534 // Consume the previously pushed token.
535 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
537 SourceLocation EqualLoc;
539 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
542 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
544 // The next token should be our artificial terminating EOF token.
545 if (Tok.isNot(tok::eof)) {
546 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
547 if (!EndLoc.isValid())
548 EndLoc = Tok.getLocation();
549 // No fixit; we can't recover as if there were a semicolon here.
550 Diag(EndLoc, diag::err_expected_semi_decl_list);
552 // Consume tokens until we hit the artificial EOF.
553 while (Tok.isNot(tok::eof))
559 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
560 /// container until the token 'T' is reached (which gets
561 /// consumed/stored too, if ConsumeFinalToken).
562 /// If StopAtSemi is true, then we will stop early at a ';' character.
563 /// Returns true if token 'T1' or 'T2' was found.
564 /// NOTE: This is a specialized version of Parser::SkipUntil.
565 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
567 bool StopAtSemi, bool ConsumeFinalToken) {
568 // We always want this function to consume at least one token if the first
569 // token isn't T and if not at EOF.
570 bool isFirstTokenConsumed = true;
572 // If we found one of the tokens, stop and return true.
573 if (Tok.is(T1) || Tok.is(T2)) {
574 if (ConsumeFinalToken) {
581 switch (Tok.getKind()) {
583 // Ran out of tokens.
587 // Recursively consume properly-nested parens.
590 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
593 // Recursively consume properly-nested square brackets.
596 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
599 // Recursively consume properly-nested braces.
602 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
605 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
606 // Since the user wasn't looking for this token (if they were, it would
607 // already be handled), this isn't balanced. If there is a LHS token at a
608 // higher level, we will assume that this matches the unbalanced token
609 // and return it. Otherwise, this is a spurious RHS token, which we skip.
611 if (ParenCount && !isFirstTokenConsumed)
612 return false; // Matches something.
617 if (BracketCount && !isFirstTokenConsumed)
618 return false; // Matches something.
623 if (BraceCount && !isFirstTokenConsumed)
624 return false; // Matches something.
629 case tok::code_completion:
631 ConsumeCodeCompletionToken();
634 case tok::string_literal:
635 case tok::wide_string_literal:
636 case tok::utf8_string_literal:
637 case tok::utf16_string_literal:
638 case tok::utf32_string_literal:
640 ConsumeStringToken();
647 // consume this token.
652 isFirstTokenConsumed = false;
656 /// \brief Consume tokens and store them in the passed token container until
657 /// we've passed the try keyword and constructor initializers and have consumed
658 /// the opening brace of the function body. The opening brace will be consumed
659 /// if and only if there was no error.
661 /// \return True on error.
662 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
663 if (Tok.is(tok::kw_try)) {
668 if (Tok.isNot(tok::colon)) {
669 // Easy case, just a function body.
671 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
672 // brace: an opening one is the function body, while a closing one probably
673 // means we've reached the end of the class.
674 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
676 /*ConsumeFinalToken=*/false);
677 if (Tok.isNot(tok::l_brace))
678 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
688 // We can't reliably skip over a mem-initializer-id, because it could be
689 // a template-id involving not-yet-declared names. Given:
691 // S ( ) : a < b < c > ( e )
693 // 'e' might be an initializer or part of a template argument, depending
694 // on whether 'b' is a template.
696 // Track whether we might be inside a template argument. We can give
697 // significantly better diagnostics if we know that we're not.
698 bool MightBeTemplateArgument = false;
701 // Skip over the mem-initializer-id, if possible.
702 if (Tok.is(tok::kw_decltype)) {
704 SourceLocation OpenLoc = ConsumeToken();
705 if (Tok.isNot(tok::l_paren))
706 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
710 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
711 Diag(Tok.getLocation(), diag::err_expected_rparen);
712 Diag(OpenLoc, diag::note_matching) << "(";
717 // Walk over a component of a nested-name-specifier.
718 if (Tok.is(tok::coloncolon)) {
722 if (Tok.is(tok::kw_template)) {
728 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
731 } else if (Tok.is(tok::code_completion)) {
733 ConsumeCodeCompletionToken();
734 // Consume the rest of the initializers permissively.
735 // FIXME: We should be able to perform code-completion here even if
736 // there isn't a subsequent '{' token.
737 MightBeTemplateArgument = true;
742 } while (Tok.is(tok::coloncolon));
744 if (Tok.is(tok::less))
745 MightBeTemplateArgument = true;
747 if (MightBeTemplateArgument) {
748 // We may be inside a template argument list. Grab up to the start of the
749 // next parenthesized initializer or braced-init-list. This *might* be the
750 // initializer, or it might be a subexpression in the template argument
752 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
753 // if all angles are closed.
754 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
756 /*ConsumeFinalToken=*/false)) {
757 // We're not just missing the initializer, we're also missing the
759 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
761 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
762 // We found something weird in a mem-initializer-id.
763 return Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
764 ? diag::err_expected_lparen_or_lbrace
765 : diag::err_expected_lparen);
768 tok::TokenKind kind = Tok.getKind();
770 bool IsLParen = (kind == tok::l_paren);
771 SourceLocation OpenLoc = Tok.getLocation();
776 assert(kind == tok::l_brace && "Must be left paren or brace here.");
778 // In C++03, this has to be the start of the function body, which
779 // means the initializer is malformed; we'll diagnose it later.
780 if (!getLangOpts().CPlusPlus11)
784 // Grab the initializer (or the subexpression of the template argument).
785 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
786 // if we might be inside the braces of a lambda-expression.
787 if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
788 Toks, /*StopAtSemi=*/true)) {
789 Diag(Tok, IsLParen ? diag::err_expected_rparen :
790 diag::err_expected_rbrace);
791 Diag(OpenLoc, diag::note_matching) << (IsLParen ? "(" : "{");
795 // Grab pack ellipsis, if present.
796 if (Tok.is(tok::ellipsis)) {
801 // If we know we just consumed a mem-initializer, we must have ',' or '{'
803 if (Tok.is(tok::comma)) {
806 } else if (Tok.is(tok::l_brace)) {
807 // This is the function body if the ')' or '}' is immediately followed by
808 // a '{'. That cannot happen within a template argument, apart from the
809 // case where a template argument contains a compound literal:
811 // S ( ) : a < b < c > ( d ) { }
812 // // End of declaration, or still inside the template argument?
814 // ... and the case where the template argument contains a lambda:
816 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
819 // FIXME: Disambiguate these cases. Note that the latter case is probably
820 // going to be made ill-formed by core issue 1607.
824 } else if (!MightBeTemplateArgument) {
825 return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
830 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
832 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
834 assert(Tok.is(tok::question));
838 while (Tok.isNot(tok::colon)) {
839 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true,
840 /*ConsumeFinalToken*/false))
843 // If we found a nested conditional, consume it.
844 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
854 /// \brief A tentative parsing action that can also revert token annotations.
855 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
857 explicit UnannotatedTentativeParsingAction(Parser &Self,
858 tok::TokenKind EndKind)
859 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
860 // Stash away the old token stream, so we can restore it once the
861 // tentative parse is complete.
862 TentativeParsingAction Inner(Self);
863 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
867 void RevertAnnotations() {
870 // Put back the original tokens.
871 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
873 Token *Buffer = new Token[Toks.size()];
874 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
875 Buffer[Toks.size() - 1] = Self.Tok;
876 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
878 Self.Tok = Toks.front();
885 tok::TokenKind EndKind;
888 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
889 /// container until the end of the current initializer expression (either a
890 /// default argument or an in-class initializer for a non-static data member).
891 /// The final token is not consumed.
892 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
893 CachedInitKind CIK) {
894 // We always want this function to consume at least one token if not at EOF.
895 bool IsFirstTokenConsumed = true;
897 // Number of possible unclosed <s we've seen so far. These might be templates,
898 // and might not, but if there were none of them (or we know for sure that
899 // we're within a template), we can avoid a tentative parse.
900 unsigned AngleCount = 0;
901 unsigned KnownTemplateCount = 0;
904 switch (Tok.getKind()) {
906 // If we might be in a template, perform a tentative parse to check.
908 // Not a template argument: this is the end of the initializer.
910 if (KnownTemplateCount)
913 // We hit a comma inside angle brackets. This is the hard case. The
914 // rule we follow is:
915 // * For a default argument, if the tokens after the comma form a
916 // syntactically-valid parameter-declaration-clause, in which each
917 // parameter has an initializer, then this comma ends the default
919 // * For a default initializer, if the tokens after the comma form a
920 // syntactically-valid init-declarator-list, then this comma ends
921 // the default initializer.
923 UnannotatedTentativeParsingAction PA(*this,
924 CIK == CIK_DefaultInitializer
925 ? tok::semi : tok::r_paren);
926 Sema::TentativeAnalysisScope Scope(Actions);
928 TPResult Result = TPResult::Error();
931 case CIK_DefaultInitializer:
932 Result = TryParseInitDeclaratorList();
933 // If we parsed a complete, ambiguous init-declarator-list, this
934 // is only syntactically-valid if it's followed by a semicolon.
935 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi))
936 Result = TPResult::False();
939 case CIK_DefaultArgument:
940 bool InvalidAsDeclaration = false;
941 Result = TryParseParameterDeclarationClause(
942 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
943 // If this is an expression or a declaration with a missing
944 // 'typename', assume it's not a declaration.
945 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration)
946 Result = TPResult::False();
950 // If what follows could be a declaration, it is a declaration.
951 if (Result != TPResult::False() && Result != TPResult::Error()) {
956 // In the uncommon case that we decide the following tokens are part
957 // of a template argument, revert any annotations we've performed in
958 // those tokens. We're not going to look them up until we've parsed
959 // the rest of the class, and that might add more declarations.
960 PA.RevertAnnotations();
963 // Keep going. We know we're inside a template argument list now.
964 ++KnownTemplateCount;
968 // Ran out of tokens.
972 // FIXME: A '<' can only start a template-id if it's preceded by an
973 // identifier, an operator-function-id, or a literal-operator-id.
978 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
979 // that is *never* the end of the initializer. Skip to the ':'.
980 if (!ConsumeAndStoreConditional(Toks))
984 case tok::greatergreatergreater:
985 if (!getLangOpts().CPlusPlus11)
987 if (AngleCount) --AngleCount;
988 if (KnownTemplateCount) --KnownTemplateCount;
990 case tok::greatergreater:
991 if (!getLangOpts().CPlusPlus11)
993 if (AngleCount) --AngleCount;
994 if (KnownTemplateCount) --KnownTemplateCount;
997 if (AngleCount) --AngleCount;
998 if (KnownTemplateCount) --KnownTemplateCount;
1001 case tok::kw_template:
1002 // 'template' identifier '<' is known to start a template argument list,
1003 // and can be used to disambiguate the parse.
1004 // FIXME: Support all forms of 'template' unqualified-id '<'.
1005 Toks.push_back(Tok);
1007 if (Tok.is(tok::identifier)) {
1008 Toks.push_back(Tok);
1010 if (Tok.is(tok::less)) {
1011 ++KnownTemplateCount;
1012 Toks.push_back(Tok);
1018 case tok::kw_operator:
1019 // If 'operator' precedes other punctuation, that punctuation loses
1020 // its special behavior.
1021 Toks.push_back(Tok);
1023 switch (Tok.getKind()) {
1025 case tok::greatergreatergreater:
1026 case tok::greatergreater:
1029 Toks.push_back(Tok);
1038 // Recursively consume properly-nested parens.
1039 Toks.push_back(Tok);
1041 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1044 // Recursively consume properly-nested square brackets.
1045 Toks.push_back(Tok);
1047 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1050 // Recursively consume properly-nested braces.
1051 Toks.push_back(Tok);
1053 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1056 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1057 // Since the user wasn't looking for this token (if they were, it would
1058 // already be handled), this isn't balanced. If there is a LHS token at a
1059 // higher level, we will assume that this matches the unbalanced token
1060 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1062 if (CIK == CIK_DefaultArgument)
1063 return true; // End of the default argument.
1064 if (ParenCount && !IsFirstTokenConsumed)
1065 return false; // Matches something.
1068 if (BracketCount && !IsFirstTokenConsumed)
1069 return false; // Matches something.
1072 if (BraceCount && !IsFirstTokenConsumed)
1073 return false; // Matches something.
1076 case tok::code_completion:
1077 Toks.push_back(Tok);
1078 ConsumeCodeCompletionToken();
1081 case tok::string_literal:
1082 case tok::wide_string_literal:
1083 case tok::utf8_string_literal:
1084 case tok::utf16_string_literal:
1085 case tok::utf32_string_literal:
1086 Toks.push_back(Tok);
1087 ConsumeStringToken();
1090 if (CIK == CIK_DefaultInitializer)
1091 return true; // End of the default initializer.
1095 Toks.push_back(Tok);
1099 IsFirstTokenConsumed = false;