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
, ParsingDeclarator
&D
,
24 const ParsedTemplateInfo
&TemplateInfo
,
25 const VirtSpecifiers
& VS
) {
26 assert(D
.isFunctionDeclarator() && "This isn't a function declarator!");
27 assert((Tok
.is(tok::l_brace
) || Tok
.is(tok::colon
) || Tok
.is(tok::kw_try
)) &&
28 "Current token not a '{', ':' or 'try'!");
30 MultiTemplateParamsArg
TemplateParams(Actions
,
31 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->data() : 0,
32 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->size() : 0);
35 if (D
.getDeclSpec().isFriendSpecified())
36 // FIXME: Friend templates
37 FnD
= Actions
.ActOnFriendFunctionDecl(getCurScope(), D
, true,
38 move(TemplateParams
));
39 else { // FIXME: pass template information through
40 if (VS
.isOverrideSpecified())
41 Diag(VS
.getOverrideLoc(), diag::ext_override_inline
) << "override";
42 if (VS
.isFinalSpecified())
43 Diag(VS
.getFinalLoc(), diag::ext_override_inline
) << "final";
44 if (VS
.isNewSpecified())
45 Diag(VS
.getNewLoc(), diag::ext_override_inline
) << "new";
47 FnD
= Actions
.ActOnCXXMemberDeclarator(getCurScope(), AS
, D
,
48 move(TemplateParams
), 0,
49 VS
, 0, /*IsDefinition*/true);
52 HandleMemberFunctionDefaultArgs(D
, FnD
);
56 // Consume the tokens and store them for later parsing.
58 LexedMethod
* LM
= new LexedMethod(this, FnD
);
59 getCurrentClass().LateParsedDeclarations
.push_back(LM
);
60 LM
->TemplateScope
= getCurScope()->isTemplateParamScope();
61 CachedTokens
&Toks
= LM
->Toks
;
63 tok::TokenKind kind
= Tok
.getKind();
64 // We may have a constructor initializer or function-try-block here.
65 if (kind
== tok::colon
|| kind
== tok::kw_try
) {
66 // Consume everything up to (and including) the left brace.
67 if (!ConsumeAndStoreUntil(tok::l_brace
, Toks
)) {
68 // We didn't find the left-brace we expected after the
69 // constructor initializer.
70 if (Tok
.is(tok::semi
)) {
71 // We found a semicolon; complain, consume the semicolon, and
72 // don't try to parse this method later.
73 Diag(Tok
.getLocation(), diag::err_expected_lbrace
);
75 delete getCurrentClass().LateParsedDeclarations
.back();
76 getCurrentClass().LateParsedDeclarations
.pop_back();
82 // Begin by storing the '{' token.
86 // Consume everything up to (and including) the matching right brace.
87 ConsumeAndStoreUntil(tok::r_brace
, Toks
, /*StopAtSemi=*/false);
89 // If we're in a function-try-block, we need to store all the catch blocks.
90 if (kind
== tok::kw_try
) {
91 while (Tok
.is(tok::kw_catch
)) {
92 ConsumeAndStoreUntil(tok::l_brace
, Toks
, /*StopAtSemi=*/false);
93 ConsumeAndStoreUntil(tok::r_brace
, Toks
, /*StopAtSemi=*/false);
100 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
101 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
102 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
104 Parser::LateParsedClass::LateParsedClass(Parser
*P
, ParsingClass
*C
)
105 : Self(P
), Class(C
) {}
107 Parser::LateParsedClass::~LateParsedClass() {
108 Self
->DeallocateParsedClasses(Class
);
111 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
112 Self
->ParseLexedMethodDeclarations(*Class
);
115 void Parser::LateParsedClass::ParseLexedMethodDefs() {
116 Self
->ParseLexedMethodDefs(*Class
);
119 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
120 Self
->ParseLexedMethodDeclaration(*this);
123 void Parser::LexedMethod::ParseLexedMethodDefs() {
124 Self
->ParseLexedMethodDef(*this);
127 /// ParseLexedMethodDeclarations - We finished parsing the member
128 /// specification of a top (non-nested) C++ class. Now go over the
129 /// stack of method declarations with some parts for which parsing was
130 /// delayed (such as default arguments) and parse them.
131 void Parser::ParseLexedMethodDeclarations(ParsingClass
&Class
) {
132 bool HasTemplateScope
= !Class
.TopLevelClass
&& Class
.TemplateScope
;
133 ParseScope
ClassTemplateScope(this, Scope::TemplateParamScope
, HasTemplateScope
);
134 if (HasTemplateScope
)
135 Actions
.ActOnReenterTemplateScope(getCurScope(), Class
.TagOrTemplate
);
137 // The current scope is still active if we're the top-level class.
138 // Otherwise we'll need to push and enter a new scope.
139 bool HasClassScope
= !Class
.TopLevelClass
;
140 ParseScope
ClassScope(this, Scope::ClassScope
|Scope::DeclScope
,
143 Actions
.ActOnStartDelayedMemberDeclarations(getCurScope(), Class
.TagOrTemplate
);
145 for (size_t i
= 0; i
< Class
.LateParsedDeclarations
.size(); ++i
) {
146 Class
.LateParsedDeclarations
[i
]->ParseLexedMethodDeclarations();
150 Actions
.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class
.TagOrTemplate
);
153 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration
&LM
) {
154 // If this is a member template, introduce the template parameter scope.
155 ParseScope
TemplateScope(this, Scope::TemplateParamScope
, LM
.TemplateScope
);
156 if (LM
.TemplateScope
)
157 Actions
.ActOnReenterTemplateScope(getCurScope(), LM
.Method
);
159 // Start the delayed C++ method declaration
160 Actions
.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM
.Method
);
162 // Introduce the parameters into scope and parse their default
164 ParseScope
PrototypeScope(this,
165 Scope::FunctionPrototypeScope
|Scope::DeclScope
);
166 for (unsigned I
= 0, N
= LM
.DefaultArgs
.size(); I
!= N
; ++I
) {
167 // Introduce the parameter into scope.
168 Actions
.ActOnDelayedCXXMethodParameter(getCurScope(), LM
.DefaultArgs
[I
].Param
);
170 if (CachedTokens
*Toks
= LM
.DefaultArgs
[I
].Toks
) {
171 // Save the current token position.
172 SourceLocation origLoc
= Tok
.getLocation();
174 // Parse the default argument from its saved token stream.
175 Toks
->push_back(Tok
); // So that the current token doesn't get lost
176 PP
.EnterTokenStream(&Toks
->front(), Toks
->size(), true, false);
178 // Consume the previously-pushed token.
182 assert(Tok
.is(tok::equal
) && "Default argument not starting with '='");
183 SourceLocation EqualLoc
= ConsumeToken();
185 // The argument isn't actually potentially evaluated unless it is
187 EnterExpressionEvaluationContext
Eval(Actions
,
188 Sema::PotentiallyEvaluatedIfUsed
);
190 ExprResult
DefArgResult(ParseAssignmentExpression());
191 if (DefArgResult
.isInvalid())
192 Actions
.ActOnParamDefaultArgumentError(LM
.DefaultArgs
[I
].Param
);
194 if (Tok
.is(tok::cxx_defaultarg_end
))
197 Diag(Tok
.getLocation(), diag::err_default_arg_unparsed
);
198 Actions
.ActOnParamDefaultArgument(LM
.DefaultArgs
[I
].Param
, EqualLoc
,
199 DefArgResult
.take());
202 assert(!PP
.getSourceManager().isBeforeInTranslationUnit(origLoc
,
203 Tok
.getLocation()) &&
204 "ParseAssignmentExpression went over the default arg tokens!");
205 // There could be leftover tokens (e.g. because of an error).
206 // Skip through until we reach the original token position.
207 while (Tok
.getLocation() != origLoc
&& Tok
.isNot(tok::eof
))
211 LM
.DefaultArgs
[I
].Toks
= 0;
214 PrototypeScope
.Exit();
216 // Finish the delayed C++ method declaration.
217 Actions
.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM
.Method
);
220 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
221 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
222 /// collected during its parsing and parse them all.
223 void Parser::ParseLexedMethodDefs(ParsingClass
&Class
) {
224 bool HasTemplateScope
= !Class
.TopLevelClass
&& Class
.TemplateScope
;
225 ParseScope
ClassTemplateScope(this, Scope::TemplateParamScope
, HasTemplateScope
);
226 if (HasTemplateScope
)
227 Actions
.ActOnReenterTemplateScope(getCurScope(), Class
.TagOrTemplate
);
229 bool HasClassScope
= !Class
.TopLevelClass
;
230 ParseScope
ClassScope(this, Scope::ClassScope
|Scope::DeclScope
,
233 for (size_t i
= 0; i
< Class
.LateParsedDeclarations
.size(); ++i
) {
234 Class
.LateParsedDeclarations
[i
]->ParseLexedMethodDefs();
238 void Parser::ParseLexedMethodDef(LexedMethod
&LM
) {
239 // If this is a member template, introduce the template parameter scope.
240 ParseScope
TemplateScope(this, Scope::TemplateParamScope
, LM
.TemplateScope
);
241 if (LM
.TemplateScope
)
242 Actions
.ActOnReenterTemplateScope(getCurScope(), LM
.D
);
244 // Save the current token position.
245 SourceLocation origLoc
= Tok
.getLocation();
247 assert(!LM
.Toks
.empty() && "Empty body!");
248 // Append the current token at the end of the new token stream so that it
250 LM
.Toks
.push_back(Tok
);
251 PP
.EnterTokenStream(LM
.Toks
.data(), LM
.Toks
.size(), true, false);
253 // Consume the previously pushed token.
255 assert((Tok
.is(tok::l_brace
) || Tok
.is(tok::colon
) || Tok
.is(tok::kw_try
))
256 && "Inline method not starting with '{', ':' or 'try'");
258 // Parse the method body. Function body parsing code is similar enough
259 // to be re-used for method bodies as well.
260 ParseScope
FnScope(this, Scope::FnScope
|Scope::DeclScope
);
261 Actions
.ActOnStartOfFunctionDef(getCurScope(), LM
.D
);
263 if (Tok
.is(tok::kw_try
)) {
264 ParseFunctionTryBlock(LM
.D
);
265 assert(!PP
.getSourceManager().isBeforeInTranslationUnit(origLoc
,
266 Tok
.getLocation()) &&
267 "ParseFunctionTryBlock went over the cached tokens!");
268 // There could be leftover tokens (e.g. because of an error).
269 // Skip through until we reach the original token position.
270 while (Tok
.getLocation() != origLoc
&& Tok
.isNot(tok::eof
))
274 if (Tok
.is(tok::colon
)) {
275 ParseConstructorInitializer(LM
.D
);
278 if (!Tok
.is(tok::l_brace
)) {
279 Actions
.ActOnFinishFunctionBody(LM
.D
, 0);
283 Actions
.ActOnDefaultCtorInitializers(LM
.D
);
285 ParseFunctionStatementBody(LM
.D
);
287 if (Tok
.getLocation() != origLoc
) {
288 // Due to parsing error, we either went over the cached tokens or
289 // there are still cached tokens left. If it's the latter case skip the
291 // Since this is an uncommon situation that should be avoided, use the
292 // expensive isBeforeInTranslationUnit call.
293 if (PP
.getSourceManager().isBeforeInTranslationUnit(Tok
.getLocation(),
295 while (Tok
.getLocation() != origLoc
&& Tok
.isNot(tok::eof
))
301 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
302 /// container until the token 'T' is reached (which gets
303 /// consumed/stored too, if ConsumeFinalToken).
304 /// If StopAtSemi is true, then we will stop early at a ';' character.
305 /// Returns true if token 'T1' or 'T2' was found.
306 /// NOTE: This is a specialized version of Parser::SkipUntil.
307 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1
, tok::TokenKind T2
,
309 bool StopAtSemi
, bool ConsumeFinalToken
) {
310 // We always want this function to consume at least one token if the first
311 // token isn't T and if not at EOF.
312 bool isFirstTokenConsumed
= true;
314 // If we found one of the tokens, stop and return true.
315 if (Tok
.is(T1
) || Tok
.is(T2
)) {
316 if (ConsumeFinalToken
) {
323 switch (Tok
.getKind()) {
325 // Ran out of tokens.
329 // Recursively consume properly-nested parens.
332 ConsumeAndStoreUntil(tok::r_paren
, Toks
, /*StopAtSemi=*/false);
335 // Recursively consume properly-nested square brackets.
338 ConsumeAndStoreUntil(tok::r_square
, Toks
, /*StopAtSemi=*/false);
341 // Recursively consume properly-nested braces.
344 ConsumeAndStoreUntil(tok::r_brace
, Toks
, /*StopAtSemi=*/false);
347 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
348 // Since the user wasn't looking for this token (if they were, it would
349 // already be handled), this isn't balanced. If there is a LHS token at a
350 // higher level, we will assume that this matches the unbalanced token
351 // and return it. Otherwise, this is a spurious RHS token, which we skip.
353 if (ParenCount
&& !isFirstTokenConsumed
)
354 return false; // Matches something.
359 if (BracketCount
&& !isFirstTokenConsumed
)
360 return false; // Matches something.
365 if (BraceCount
&& !isFirstTokenConsumed
)
366 return false; // Matches something.
371 case tok::string_literal
:
372 case tok::wide_string_literal
:
374 ConsumeStringToken();
381 // consume this token.
386 isFirstTokenConsumed
= false;