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/ParseDiagnostic.h"
15 #include "clang/Parse/Parser.h"
16 #include "clang/Parse/DeclSpec.h"
17 #include "clang/Parse/Scope.h"
18 using namespace clang;
20 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
21 /// Declarator is a well formed C++ inline method definition. Now lex its body
22 /// and store its tokens for parsing after the C++ class is complete.
24 Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D,
25 const ParsedTemplateInfo &TemplateInfo) {
26 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
27 "This isn't a function declarator!");
28 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) &&
29 "Current token not a '{', ':' or 'try'!");
31 Action::MultiTemplateParamsArg TemplateParams(Actions,
32 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
33 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
35 if (D.getDeclSpec().isFriendSpecified())
36 // FIXME: Friend templates
37 FnD = Actions.ActOnFriendFunctionDecl(CurScope, D, true, move(TemplateParams));
38 else // FIXME: pass template information through
39 FnD = Actions.ActOnCXXMemberDeclarator(CurScope, AS, D,
40 move(TemplateParams), 0, 0,
41 /*IsDefinition*/true);
43 HandleMemberFunctionDefaultArgs(D, FnD);
45 // Consume the tokens and store them for later parsing.
47 getCurrentClass().MethodDefs.push_back(LexedMethod(FnD));
48 getCurrentClass().MethodDefs.back().TemplateScope
49 = CurScope->isTemplateParamScope();
50 CachedTokens &Toks = getCurrentClass().MethodDefs.back().Toks;
52 tok::TokenKind kind = Tok.getKind();
53 // We may have a constructor initializer or function-try-block here.
54 if (kind == tok::colon || kind == tok::kw_try) {
55 // Consume everything up to (and including) the left brace.
56 if (!ConsumeAndStoreUntil(tok::l_brace, tok::unknown, Toks, tok::semi)) {
57 // We didn't find the left-brace we expected after the
58 // constructor initializer.
59 if (Tok.is(tok::semi)) {
60 // We found a semicolon; complain, consume the semicolon, and
61 // don't try to parse this method later.
62 Diag(Tok.getLocation(), diag::err_expected_lbrace);
64 getCurrentClass().MethodDefs.pop_back();
70 // Begin by storing the '{' token.
74 // Consume everything up to (and including) the matching right brace.
75 ConsumeAndStoreUntil(tok::r_brace, tok::unknown, Toks);
77 // If we're in a function-try-block, we need to store all the catch blocks.
78 if (kind == tok::kw_try) {
79 while (Tok.is(tok::kw_catch)) {
80 ConsumeAndStoreUntil(tok::l_brace, tok::unknown, Toks);
81 ConsumeAndStoreUntil(tok::r_brace, tok::unknown, Toks);
88 /// ParseLexedMethodDeclarations - We finished parsing the member
89 /// specification of a top (non-nested) C++ class. Now go over the
90 /// stack of method declarations with some parts for which parsing was
91 /// delayed (such as default arguments) and parse them.
92 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
93 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
94 ParseScope TemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
96 Actions.ActOnReenterTemplateScope(CurScope, Class.TagOrTemplate);
98 // The current scope is still active if we're the top-level class.
99 // Otherwise we'll need to push and enter a new scope.
100 bool HasClassScope = !Class.TopLevelClass;
101 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, HasClassScope);
103 Actions.ActOnStartDelayedMemberDeclarations(CurScope, Class.TagOrTemplate);
105 for (; !Class.MethodDecls.empty(); Class.MethodDecls.pop_front()) {
106 LateParsedMethodDeclaration &LM = Class.MethodDecls.front();
108 // If this is a member template, introduce the template parameter scope.
109 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
110 if (LM.TemplateScope)
111 Actions.ActOnReenterTemplateScope(CurScope, LM.Method);
113 // Start the delayed C++ method declaration
114 Actions.ActOnStartDelayedCXXMethodDeclaration(CurScope, LM.Method);
116 // Introduce the parameters into scope and parse their default
118 ParseScope PrototypeScope(this,
119 Scope::FunctionPrototypeScope|Scope::DeclScope);
120 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
121 // Introduce the parameter into scope.
122 Actions.ActOnDelayedCXXMethodParameter(CurScope, LM.DefaultArgs[I].Param);
124 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
125 // Save the current token position.
126 SourceLocation origLoc = Tok.getLocation();
128 // Parse the default argument from its saved token stream.
129 Toks->push_back(Tok); // So that the current token doesn't get lost
130 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
132 // Consume the previously-pushed token.
136 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
137 SourceLocation EqualLoc = ConsumeToken();
139 OwningExprResult DefArgResult(ParseAssignmentExpression());
140 if (DefArgResult.isInvalid())
141 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
143 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
146 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
147 Tok.getLocation()) &&
148 "ParseAssignmentExpression went over the default arg tokens!");
149 // There could be leftover tokens (e.g. because of an error).
150 // Skip through until we reach the original token position.
151 while (Tok.getLocation() != origLoc)
155 LM.DefaultArgs[I].Toks = 0;
158 PrototypeScope.Exit();
160 // Finish the delayed C++ method declaration.
161 Actions.ActOnFinishDelayedCXXMethodDeclaration(CurScope, LM.Method);
164 for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
165 ParseLexedMethodDeclarations(*Class.NestedClasses[I]);
168 Actions.ActOnFinishDelayedMemberDeclarations(CurScope, Class.TagOrTemplate);
171 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
172 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
173 /// collected during its parsing and parse them all.
174 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
175 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
176 ParseScope TemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
177 if (HasTemplateScope)
178 Actions.ActOnReenterTemplateScope(CurScope, Class.TagOrTemplate);
180 bool HasClassScope = !Class.TopLevelClass;
181 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
184 for (; !Class.MethodDefs.empty(); Class.MethodDefs.pop_front()) {
185 LexedMethod &LM = Class.MethodDefs.front();
187 // If this is a member template, introduce the template parameter scope.
188 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
189 if (LM.TemplateScope)
190 Actions.ActOnReenterTemplateScope(CurScope, LM.D);
192 // Save the current token position.
193 SourceLocation origLoc = Tok.getLocation();
195 assert(!LM.Toks.empty() && "Empty body!");
196 // Append the current token at the end of the new token stream so that it
198 LM.Toks.push_back(Tok);
199 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
201 // Consume the previously pushed token.
203 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
204 && "Inline method not starting with '{', ':' or 'try'");
206 // Parse the method body. Function body parsing code is similar enough
207 // to be re-used for method bodies as well.
208 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
209 Actions.ActOnStartOfFunctionDef(CurScope, LM.D);
211 if (Tok.is(tok::kw_try)) {
212 ParseFunctionTryBlock(LM.D);
213 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
214 Tok.getLocation()) &&
215 "ParseFunctionTryBlock went over the cached tokens!");
216 assert(Tok.getLocation() == origLoc &&
217 "ParseFunctionTryBlock left tokens in the token stream!");
220 if (Tok.is(tok::colon))
221 ParseConstructorInitializer(LM.D);
223 Actions.ActOnDefaultCtorInitializers(LM.D);
225 // FIXME: What if ParseConstructorInitializer doesn't leave us with a '{'??
226 ParseFunctionStatementBody(LM.D);
227 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
228 Tok.getLocation()) &&
229 "We consumed more than the cached tokens!");
230 assert(Tok.getLocation() == origLoc &&
231 "Tokens were left in the token stream!");
234 for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
235 ParseLexedMethodDefs(*Class.NestedClasses[I]);
238 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
239 /// container until the token 'T' is reached (which gets
240 /// consumed/stored too, if ConsumeFinalToken).
241 /// If EarlyAbortIf is specified, then we will stop early if we find that
242 /// token at the top level.
243 /// Returns true if token 'T1' or 'T2' was found.
244 /// NOTE: This is a specialized version of Parser::SkipUntil.
245 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
247 tok::TokenKind EarlyAbortIf,
248 bool ConsumeFinalToken) {
249 // We always want this function to consume at least one token if the first
250 // token isn't T and if not at EOF.
251 bool isFirstTokenConsumed = true;
253 // If we found one of the tokens, stop and return true.
254 if (Tok.is(T1) || Tok.is(T2)) {
255 if (ConsumeFinalToken) {
262 // If we found the early-abort token, return.
263 if (Tok.is(EarlyAbortIf))
266 switch (Tok.getKind()) {
268 // Ran out of tokens.
272 // Recursively consume properly-nested parens.
275 ConsumeAndStoreUntil(tok::r_paren, tok::unknown, Toks);
278 // Recursively consume properly-nested square brackets.
281 ConsumeAndStoreUntil(tok::r_square, tok::unknown, Toks);
284 // Recursively consume properly-nested braces.
287 ConsumeAndStoreUntil(tok::r_brace, tok::unknown, Toks);
290 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
291 // Since the user wasn't looking for this token (if they were, it would
292 // already be handled), this isn't balanced. If there is a LHS token at a
293 // higher level, we will assume that this matches the unbalanced token
294 // and return it. Otherwise, this is a spurious RHS token, which we skip.
296 if (ParenCount && !isFirstTokenConsumed)
297 return false; // Matches something.
302 if (BracketCount && !isFirstTokenConsumed)
303 return false; // Matches something.
308 if (BraceCount && !isFirstTokenConsumed)
309 return false; // Matches something.
314 case tok::string_literal:
315 case tok::wide_string_literal:
317 ConsumeStringToken();
320 // consume this token.
325 isFirstTokenConsumed = false;