When throwing an elidable object, first try to treat the subexpression
[clang.git] / lib / Parse / ParseCXXInlineMethods.cpp
blob0a5a586f73819d249f624aed3a429a928bb5f1eb
1 //===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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);
33 Decl *FnD;
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,
41 VirtSpecifiers(), 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);
64 ConsumeAnyToken();
65 delete getCurrentClass().LateParsedDeclarations.back();
66 getCurrentClass().LateParsedDeclarations.pop_back();
67 return FnD;
71 } else {
72 // Begin by storing the '{' token.
73 Toks.push_back(Tok);
74 ConsumeBrace();
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);
87 return FnD;
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,
131 HasClassScope);
132 if (HasClassScope)
133 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
135 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
136 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
139 if (HasClassScope)
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
153 // arguments.
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.
169 ConsumeAnyToken();
171 // Consume the '='.
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
176 // used.
177 EnterExpressionEvaluationContext Eval(Actions,
178 Sema::PotentiallyEvaluatedIfUsed);
180 ExprResult DefArgResult(ParseAssignmentExpression());
181 if (DefArgResult.isInvalid())
182 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
183 else {
184 if (Tok.is(tok::cxx_defaultarg_end))
185 ConsumeToken();
186 else
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))
198 ConsumeAnyToken();
200 delete Toks;
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,
221 HasClassScope);
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
239 // doesn't get lost.
240 LM.Toks.push_back(Tok);
241 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
243 // Consume the previously pushed token.
244 ConsumeAnyToken();
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))
261 ConsumeAnyToken();
262 return;
264 if (Tok.is(tok::colon)) {
265 ParseConstructorInitializer(LM.D);
267 // Error recovery.
268 if (!Tok.is(tok::l_brace)) {
269 Actions.ActOnFinishFunctionBody(LM.D, 0);
270 return;
272 } else
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
280 // leftover tokens.
281 // Since this is an uncommon situation that should be avoided, use the
282 // expensive isBeforeInTranslationUnit call.
283 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
284 origLoc))
285 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
286 ConsumeAnyToken();
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,
298 CachedTokens &Toks,
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;
303 while (1) {
304 // If we found one of the tokens, stop and return true.
305 if (Tok.is(T1) || Tok.is(T2)) {
306 if (ConsumeFinalToken) {
307 Toks.push_back(Tok);
308 ConsumeAnyToken();
310 return true;
313 switch (Tok.getKind()) {
314 case tok::eof:
315 // Ran out of tokens.
316 return false;
318 case tok::l_paren:
319 // Recursively consume properly-nested parens.
320 Toks.push_back(Tok);
321 ConsumeParen();
322 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
323 break;
324 case tok::l_square:
325 // Recursively consume properly-nested square brackets.
326 Toks.push_back(Tok);
327 ConsumeBracket();
328 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
329 break;
330 case tok::l_brace:
331 // Recursively consume properly-nested braces.
332 Toks.push_back(Tok);
333 ConsumeBrace();
334 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
335 break;
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.
342 case tok::r_paren:
343 if (ParenCount && !isFirstTokenConsumed)
344 return false; // Matches something.
345 Toks.push_back(Tok);
346 ConsumeParen();
347 break;
348 case tok::r_square:
349 if (BracketCount && !isFirstTokenConsumed)
350 return false; // Matches something.
351 Toks.push_back(Tok);
352 ConsumeBracket();
353 break;
354 case tok::r_brace:
355 if (BraceCount && !isFirstTokenConsumed)
356 return false; // Matches something.
357 Toks.push_back(Tok);
358 ConsumeBrace();
359 break;
361 case tok::string_literal:
362 case tok::wide_string_literal:
363 Toks.push_back(Tok);
364 ConsumeStringToken();
365 break;
366 case tok::semi:
367 if (StopAtSemi)
368 return false;
369 // FALL THROUGH.
370 default:
371 // consume this token.
372 Toks.push_back(Tok);
373 ConsumeToken();
374 break;
376 isFirstTokenConsumed = false;