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/Sema/DeclSpec.h"
17 #include "clang/Sema/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.
23 Decl
*Parser::ParseCXXInlineMethodDef(AccessSpecifier AS
, Declarator
&D
,
24 const ParsedTemplateInfo
&TemplateInfo
) {
25 assert(D
.isFunctionDeclarator() && "This isn't a function declarator!");
26 assert((Tok
.is(tok::l_brace
) || Tok
.is(tok::colon
) || Tok
.is(tok::kw_try
)) &&
27 "Current token not a '{', ':' or 'try'!");
29 MultiTemplateParamsArg
TemplateParams(Actions
,
30 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->data() : 0,
31 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->size() : 0);
34 if (D
.getDeclSpec().isFriendSpecified())
35 // FIXME: Friend templates
36 FnD
= Actions
.ActOnFriendFunctionDecl(getCurScope(), D
, true,
37 move(TemplateParams
));
38 else // FIXME: pass template information through
39 FnD
= Actions
.ActOnCXXMemberDeclarator(getCurScope(), AS
, D
,
40 move(TemplateParams
), 0,
42 /*IsDefinition*/true);
44 HandleMemberFunctionDefaultArgs(D
, FnD
);
46 // Consume the tokens and store them for later parsing.
48 LexedMethod
* LM
= new LexedMethod(this, FnD
);
49 getCurrentClass().LateParsedDeclarations
.push_back(LM
);
50 LM
->TemplateScope
= getCurScope()->isTemplateParamScope();
51 CachedTokens
&Toks
= LM
->Toks
;
53 tok::TokenKind kind
= Tok
.getKind();
54 // We may have a constructor initializer or function-try-block here.
55 if (kind
== tok::colon
|| kind
== tok::kw_try
) {
56 // Consume everything up to (and including) the left brace.
57 if (!ConsumeAndStoreUntil(tok::l_brace
, Toks
)) {
58 // We didn't find the left-brace we expected after the
59 // constructor initializer.
60 if (Tok
.is(tok::semi
)) {
61 // We found a semicolon; complain, consume the semicolon, and
62 // don't try to parse this method later.
63 Diag(Tok
.getLocation(), diag::err_expected_lbrace
);
65 delete getCurrentClass().LateParsedDeclarations
.back();
66 getCurrentClass().LateParsedDeclarations
.pop_back();
72 // Begin by storing the '{' token.
76 // Consume everything up to (and including) the matching right brace.
77 ConsumeAndStoreUntil(tok::r_brace
, Toks
, /*StopAtSemi=*/false);
79 // If we're in a function-try-block, we need to store all the catch blocks.
80 if (kind
== tok::kw_try
) {
81 while (Tok
.is(tok::kw_catch
)) {
82 ConsumeAndStoreUntil(tok::l_brace
, Toks
, /*StopAtSemi=*/false);
83 ConsumeAndStoreUntil(tok::r_brace
, Toks
, /*StopAtSemi=*/false);
90 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
91 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
92 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
94 Parser::LateParsedClass::LateParsedClass(Parser
*P
, ParsingClass
*C
)
95 : Self(P
), Class(C
) {}
97 Parser::LateParsedClass::~LateParsedClass() {
98 Self
->DeallocateParsedClasses(Class
);
101 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
102 Self
->ParseLexedMethodDeclarations(*Class
);
105 void Parser::LateParsedClass::ParseLexedMethodDefs() {
106 Self
->ParseLexedMethodDefs(*Class
);
109 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
110 Self
->ParseLexedMethodDeclaration(*this);
113 void Parser::LexedMethod::ParseLexedMethodDefs() {
114 Self
->ParseLexedMethodDef(*this);
117 /// ParseLexedMethodDeclarations - We finished parsing the member
118 /// specification of a top (non-nested) C++ class. Now go over the
119 /// stack of method declarations with some parts for which parsing was
120 /// delayed (such as default arguments) and parse them.
121 void Parser::ParseLexedMethodDeclarations(ParsingClass
&Class
) {
122 bool HasTemplateScope
= !Class
.TopLevelClass
&& Class
.TemplateScope
;
123 ParseScope
ClassTemplateScope(this, Scope::TemplateParamScope
, HasTemplateScope
);
124 if (HasTemplateScope
)
125 Actions
.ActOnReenterTemplateScope(getCurScope(), Class
.TagOrTemplate
);
127 // The current scope is still active if we're the top-level class.
128 // Otherwise we'll need to push and enter a new scope.
129 bool HasClassScope
= !Class
.TopLevelClass
;
130 ParseScope
ClassScope(this, Scope::ClassScope
|Scope::DeclScope
,
133 Actions
.ActOnStartDelayedMemberDeclarations(getCurScope(), Class
.TagOrTemplate
);
135 for (size_t i
= 0; i
< Class
.LateParsedDeclarations
.size(); ++i
) {
136 Class
.LateParsedDeclarations
[i
]->ParseLexedMethodDeclarations();
140 Actions
.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class
.TagOrTemplate
);
143 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration
&LM
) {
144 // If this is a member template, introduce the template parameter scope.
145 ParseScope
TemplateScope(this, Scope::TemplateParamScope
, LM
.TemplateScope
);
146 if (LM
.TemplateScope
)
147 Actions
.ActOnReenterTemplateScope(getCurScope(), LM
.Method
);
149 // Start the delayed C++ method declaration
150 Actions
.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM
.Method
);
152 // Introduce the parameters into scope and parse their default
154 ParseScope
PrototypeScope(this,
155 Scope::FunctionPrototypeScope
|Scope::DeclScope
);
156 for (unsigned I
= 0, N
= LM
.DefaultArgs
.size(); I
!= N
; ++I
) {
157 // Introduce the parameter into scope.
158 Actions
.ActOnDelayedCXXMethodParameter(getCurScope(), LM
.DefaultArgs
[I
].Param
);
160 if (CachedTokens
*Toks
= LM
.DefaultArgs
[I
].Toks
) {
161 // Save the current token position.
162 SourceLocation origLoc
= Tok
.getLocation();
164 // Parse the default argument from its saved token stream.
165 Toks
->push_back(Tok
); // So that the current token doesn't get lost
166 PP
.EnterTokenStream(&Toks
->front(), Toks
->size(), true, false);
168 // Consume the previously-pushed token.
172 assert(Tok
.is(tok::equal
) && "Default argument not starting with '='");
173 SourceLocation EqualLoc
= ConsumeToken();
175 // The argument isn't actually potentially evaluated unless it is
177 EnterExpressionEvaluationContext
Eval(Actions
,
178 Sema::PotentiallyEvaluatedIfUsed
);
180 ExprResult
DefArgResult(ParseAssignmentExpression());
181 if (DefArgResult
.isInvalid())
182 Actions
.ActOnParamDefaultArgumentError(LM
.DefaultArgs
[I
].Param
);
184 if (Tok
.is(tok::cxx_defaultarg_end
))
187 Diag(Tok
.getLocation(), diag::err_default_arg_unparsed
);
188 Actions
.ActOnParamDefaultArgument(LM
.DefaultArgs
[I
].Param
, EqualLoc
,
189 DefArgResult
.take());
192 assert(!PP
.getSourceManager().isBeforeInTranslationUnit(origLoc
,
193 Tok
.getLocation()) &&
194 "ParseAssignmentExpression went over the default arg tokens!");
195 // There could be leftover tokens (e.g. because of an error).
196 // Skip through until we reach the original token position.
197 while (Tok
.getLocation() != origLoc
&& Tok
.isNot(tok::eof
))
201 LM
.DefaultArgs
[I
].Toks
= 0;
204 PrototypeScope
.Exit();
206 // Finish the delayed C++ method declaration.
207 Actions
.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM
.Method
);
210 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
211 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
212 /// collected during its parsing and parse them all.
213 void Parser::ParseLexedMethodDefs(ParsingClass
&Class
) {
214 bool HasTemplateScope
= !Class
.TopLevelClass
&& Class
.TemplateScope
;
215 ParseScope
ClassTemplateScope(this, Scope::TemplateParamScope
, HasTemplateScope
);
216 if (HasTemplateScope
)
217 Actions
.ActOnReenterTemplateScope(getCurScope(), Class
.TagOrTemplate
);
219 bool HasClassScope
= !Class
.TopLevelClass
;
220 ParseScope
ClassScope(this, Scope::ClassScope
|Scope::DeclScope
,
223 for (size_t i
= 0; i
< Class
.LateParsedDeclarations
.size(); ++i
) {
224 Class
.LateParsedDeclarations
[i
]->ParseLexedMethodDefs();
228 void Parser::ParseLexedMethodDef(LexedMethod
&LM
) {
229 // If this is a member template, introduce the template parameter scope.
230 ParseScope
TemplateScope(this, Scope::TemplateParamScope
, LM
.TemplateScope
);
231 if (LM
.TemplateScope
)
232 Actions
.ActOnReenterTemplateScope(getCurScope(), LM
.D
);
234 // Save the current token position.
235 SourceLocation origLoc
= Tok
.getLocation();
237 assert(!LM
.Toks
.empty() && "Empty body!");
238 // Append the current token at the end of the new token stream so that it
240 LM
.Toks
.push_back(Tok
);
241 PP
.EnterTokenStream(LM
.Toks
.data(), LM
.Toks
.size(), true, false);
243 // Consume the previously pushed token.
245 assert((Tok
.is(tok::l_brace
) || Tok
.is(tok::colon
) || Tok
.is(tok::kw_try
))
246 && "Inline method not starting with '{', ':' or 'try'");
248 // Parse the method body. Function body parsing code is similar enough
249 // to be re-used for method bodies as well.
250 ParseScope
FnScope(this, Scope::FnScope
|Scope::DeclScope
);
251 Actions
.ActOnStartOfFunctionDef(getCurScope(), LM
.D
);
253 if (Tok
.is(tok::kw_try
)) {
254 ParseFunctionTryBlock(LM
.D
);
255 assert(!PP
.getSourceManager().isBeforeInTranslationUnit(origLoc
,
256 Tok
.getLocation()) &&
257 "ParseFunctionTryBlock went over the cached tokens!");
258 // There could be leftover tokens (e.g. because of an error).
259 // Skip through until we reach the original token position.
260 while (Tok
.getLocation() != origLoc
&& Tok
.isNot(tok::eof
))
264 if (Tok
.is(tok::colon
)) {
265 ParseConstructorInitializer(LM
.D
);
268 if (!Tok
.is(tok::l_brace
)) {
269 Actions
.ActOnFinishFunctionBody(LM
.D
, 0);
273 Actions
.ActOnDefaultCtorInitializers(LM
.D
);
275 ParseFunctionStatementBody(LM
.D
);
277 if (Tok
.getLocation() != origLoc
) {
278 // Due to parsing error, we either went over the cached tokens or
279 // there are still cached tokens left. If it's the latter case skip the
281 // Since this is an uncommon situation that should be avoided, use the
282 // expensive isBeforeInTranslationUnit call.
283 if (PP
.getSourceManager().isBeforeInTranslationUnit(Tok
.getLocation(),
285 while (Tok
.getLocation() != origLoc
&& Tok
.isNot(tok::eof
))
291 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
292 /// container until the token 'T' is reached (which gets
293 /// consumed/stored too, if ConsumeFinalToken).
294 /// If StopAtSemi is true, then we will stop early at a ';' character.
295 /// Returns true if token 'T1' or 'T2' was found.
296 /// NOTE: This is a specialized version of Parser::SkipUntil.
297 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1
, tok::TokenKind T2
,
299 bool StopAtSemi
, bool ConsumeFinalToken
) {
300 // We always want this function to consume at least one token if the first
301 // token isn't T and if not at EOF.
302 bool isFirstTokenConsumed
= true;
304 // If we found one of the tokens, stop and return true.
305 if (Tok
.is(T1
) || Tok
.is(T2
)) {
306 if (ConsumeFinalToken
) {
313 switch (Tok
.getKind()) {
315 // Ran out of tokens.
319 // Recursively consume properly-nested parens.
322 ConsumeAndStoreUntil(tok::r_paren
, Toks
, /*StopAtSemi=*/false);
325 // Recursively consume properly-nested square brackets.
328 ConsumeAndStoreUntil(tok::r_square
, Toks
, /*StopAtSemi=*/false);
331 // Recursively consume properly-nested braces.
334 ConsumeAndStoreUntil(tok::r_brace
, Toks
, /*StopAtSemi=*/false);
337 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
338 // Since the user wasn't looking for this token (if they were, it would
339 // already be handled), this isn't balanced. If there is a LHS token at a
340 // higher level, we will assume that this matches the unbalanced token
341 // and return it. Otherwise, this is a spurious RHS token, which we skip.
343 if (ParenCount
&& !isFirstTokenConsumed
)
344 return false; // Matches something.
349 if (BracketCount
&& !isFirstTokenConsumed
)
350 return false; // Matches something.
355 if (BraceCount
&& !isFirstTokenConsumed
)
356 return false; // Matches something.
361 case tok::string_literal
:
362 case tok::wide_string_literal
:
364 ConsumeStringToken();
371 // consume this token.
376 isFirstTokenConsumed
= false;