ParseCXXInlineMethods.cpp revision 207619
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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/ParseDiagnostic.h"
15#include "clang/Parse/Parser.h"
16#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
18using namespace clang;
19
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.
23Parser::DeclPtrTy
24Parser::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'!");
30
31  Action::MultiTemplateParamsArg TemplateParams(Actions,
32          TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
33          TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
34
35  DeclPtrTy FnD;
36  if (D.getDeclSpec().isFriendSpecified())
37    // FIXME: Friend templates
38    FnD = Actions.ActOnFriendFunctionDecl(CurScope, D, true,
39                                          move(TemplateParams));
40  else // FIXME: pass template information through
41    FnD = Actions.ActOnCXXMemberDeclarator(CurScope, AS, D,
42                                           move(TemplateParams), 0, 0,
43                                           /*IsDefinition*/true);
44
45  HandleMemberFunctionDefaultArgs(D, FnD);
46
47  // Consume the tokens and store them for later parsing.
48
49  getCurrentClass().MethodDefs.push_back(LexedMethod(FnD));
50  getCurrentClass().MethodDefs.back().TemplateScope
51    = CurScope->isTemplateParamScope();
52  CachedTokens &Toks = getCurrentClass().MethodDefs.back().Toks;
53
54  tok::TokenKind kind = Tok.getKind();
55  // We may have a constructor initializer or function-try-block here.
56  if (kind == tok::colon || kind == tok::kw_try) {
57    // Consume everything up to (and including) the left brace.
58    if (!ConsumeAndStoreUntil(tok::l_brace, Toks)) {
59      // We didn't find the left-brace we expected after the
60      // constructor initializer.
61      if (Tok.is(tok::semi)) {
62        // We found a semicolon; complain, consume the semicolon, and
63        // don't try to parse this method later.
64        Diag(Tok.getLocation(), diag::err_expected_lbrace);
65        ConsumeAnyToken();
66        getCurrentClass().MethodDefs.pop_back();
67        return FnD;
68      }
69    }
70
71  } else {
72    // Begin by storing the '{' token.
73    Toks.push_back(Tok);
74    ConsumeBrace();
75  }
76  // Consume everything up to (and including) the matching right brace.
77  ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
78
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);
84    }
85  }
86
87  return FnD;
88}
89
90/// ParseLexedMethodDeclarations - We finished parsing the member
91/// specification of a top (non-nested) C++ class. Now go over the
92/// stack of method declarations with some parts for which parsing was
93/// delayed (such as default arguments) and parse them.
94void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
95  bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
96  ParseScope TemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
97  if (HasTemplateScope)
98    Actions.ActOnReenterTemplateScope(CurScope, Class.TagOrTemplate);
99
100  // The current scope is still active if we're the top-level class.
101  // Otherwise we'll need to push and enter a new scope.
102  bool HasClassScope = !Class.TopLevelClass;
103  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
104                        HasClassScope);
105  if (HasClassScope)
106    Actions.ActOnStartDelayedMemberDeclarations(CurScope, Class.TagOrTemplate);
107
108  for (; !Class.MethodDecls.empty(); Class.MethodDecls.pop_front()) {
109    LateParsedMethodDeclaration &LM = Class.MethodDecls.front();
110
111    // If this is a member template, introduce the template parameter scope.
112    ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
113    if (LM.TemplateScope)
114      Actions.ActOnReenterTemplateScope(CurScope, LM.Method);
115
116    // Start the delayed C++ method declaration
117    Actions.ActOnStartDelayedCXXMethodDeclaration(CurScope, LM.Method);
118
119    // Introduce the parameters into scope and parse their default
120    // arguments.
121    ParseScope PrototypeScope(this,
122                              Scope::FunctionPrototypeScope|Scope::DeclScope);
123    for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
124      // Introduce the parameter into scope.
125      Actions.ActOnDelayedCXXMethodParameter(CurScope, LM.DefaultArgs[I].Param);
126
127      if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
128        // Save the current token position.
129        SourceLocation origLoc = Tok.getLocation();
130
131        // Parse the default argument from its saved token stream.
132        Toks->push_back(Tok); // So that the current token doesn't get lost
133        PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
134
135        // Consume the previously-pushed token.
136        ConsumeAnyToken();
137
138        // Consume the '='.
139        assert(Tok.is(tok::equal) && "Default argument not starting with '='");
140        SourceLocation EqualLoc = ConsumeToken();
141
142        OwningExprResult DefArgResult(ParseAssignmentExpression());
143        if (DefArgResult.isInvalid())
144          Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
145        else
146          Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
147                                            move(DefArgResult));
148
149        assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
150                                                           Tok.getLocation()) &&
151               "ParseAssignmentExpression went over the default arg tokens!");
152        // There could be leftover tokens (e.g. because of an error).
153        // Skip through until we reach the original token position.
154        while (Tok.getLocation() != origLoc)
155          ConsumeAnyToken();
156
157        delete Toks;
158        LM.DefaultArgs[I].Toks = 0;
159      }
160    }
161    PrototypeScope.Exit();
162
163    // Finish the delayed C++ method declaration.
164    Actions.ActOnFinishDelayedCXXMethodDeclaration(CurScope, LM.Method);
165  }
166
167  for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
168    ParseLexedMethodDeclarations(*Class.NestedClasses[I]);
169
170  if (HasClassScope)
171    Actions.ActOnFinishDelayedMemberDeclarations(CurScope, Class.TagOrTemplate);
172}
173
174/// ParseLexedMethodDefs - We finished parsing the member specification of a top
175/// (non-nested) C++ class. Now go over the stack of lexed methods that were
176/// collected during its parsing and parse them all.
177void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
178  bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
179  ParseScope TemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
180  if (HasTemplateScope)
181    Actions.ActOnReenterTemplateScope(CurScope, Class.TagOrTemplate);
182
183  bool HasClassScope = !Class.TopLevelClass;
184  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
185                        HasClassScope);
186
187  for (; !Class.MethodDefs.empty(); Class.MethodDefs.pop_front()) {
188    LexedMethod &LM = Class.MethodDefs.front();
189
190    // If this is a member template, introduce the template parameter scope.
191    ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
192    if (LM.TemplateScope)
193      Actions.ActOnReenterTemplateScope(CurScope, LM.D);
194
195    // Save the current token position.
196    SourceLocation origLoc = Tok.getLocation();
197
198    assert(!LM.Toks.empty() && "Empty body!");
199    // Append the current token at the end of the new token stream so that it
200    // doesn't get lost.
201    LM.Toks.push_back(Tok);
202    PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
203
204    // Consume the previously pushed token.
205    ConsumeAnyToken();
206    assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
207           && "Inline method not starting with '{', ':' or 'try'");
208
209    // Parse the method body. Function body parsing code is similar enough
210    // to be re-used for method bodies as well.
211    ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
212    Actions.ActOnStartOfFunctionDef(CurScope, LM.D);
213
214    if (Tok.is(tok::kw_try)) {
215      ParseFunctionTryBlock(LM.D);
216      assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
217                                                           Tok.getLocation()) &&
218             "ParseFunctionTryBlock went over the cached tokens!");
219      assert(Tok.getLocation() == origLoc &&
220             "ParseFunctionTryBlock left tokens in the token stream!");
221      continue;
222    }
223    if (Tok.is(tok::colon)) {
224      ParseConstructorInitializer(LM.D);
225
226      // Error recovery.
227      if (!Tok.is(tok::l_brace)) {
228        Actions.ActOnFinishFunctionBody(LM.D, Action::StmtArg(Actions));
229        continue;
230      }
231    } else
232      Actions.ActOnDefaultCtorInitializers(LM.D);
233
234    ParseFunctionStatementBody(LM.D);
235    assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
236                                                           Tok.getLocation()) &&
237           "We consumed more than the cached tokens!");
238    assert(Tok.getLocation() == origLoc &&
239           "Tokens were left in the token stream!");
240  }
241
242  for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
243    ParseLexedMethodDefs(*Class.NestedClasses[I]);
244}
245
246/// ConsumeAndStoreUntil - Consume and store the token at the passed token
247/// container until the token 'T' is reached (which gets
248/// consumed/stored too, if ConsumeFinalToken).
249/// If StopAtSemi is true, then we will stop early at a ';' character.
250/// Returns true if token 'T1' or 'T2' was found.
251/// NOTE: This is a specialized version of Parser::SkipUntil.
252bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
253                                  CachedTokens &Toks,
254                                  bool StopAtSemi, bool ConsumeFinalToken) {
255  // We always want this function to consume at least one token if the first
256  // token isn't T and if not at EOF.
257  bool isFirstTokenConsumed = true;
258  while (1) {
259    // If we found one of the tokens, stop and return true.
260    if (Tok.is(T1) || Tok.is(T2)) {
261      if (ConsumeFinalToken) {
262        Toks.push_back(Tok);
263        ConsumeAnyToken();
264      }
265      return true;
266    }
267
268    switch (Tok.getKind()) {
269    case tok::eof:
270      // Ran out of tokens.
271      return false;
272
273    case tok::l_paren:
274      // Recursively consume properly-nested parens.
275      Toks.push_back(Tok);
276      ConsumeParen();
277      ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
278      break;
279    case tok::l_square:
280      // Recursively consume properly-nested square brackets.
281      Toks.push_back(Tok);
282      ConsumeBracket();
283      ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
284      break;
285    case tok::l_brace:
286      // Recursively consume properly-nested braces.
287      Toks.push_back(Tok);
288      ConsumeBrace();
289      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
290      break;
291
292    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
293    // Since the user wasn't looking for this token (if they were, it would
294    // already be handled), this isn't balanced.  If there is a LHS token at a
295    // higher level, we will assume that this matches the unbalanced token
296    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
297    case tok::r_paren:
298      if (ParenCount && !isFirstTokenConsumed)
299        return false;  // Matches something.
300      Toks.push_back(Tok);
301      ConsumeParen();
302      break;
303    case tok::r_square:
304      if (BracketCount && !isFirstTokenConsumed)
305        return false;  // Matches something.
306      Toks.push_back(Tok);
307      ConsumeBracket();
308      break;
309    case tok::r_brace:
310      if (BraceCount && !isFirstTokenConsumed)
311        return false;  // Matches something.
312      Toks.push_back(Tok);
313      ConsumeBrace();
314      break;
315
316    case tok::string_literal:
317    case tok::wide_string_literal:
318      Toks.push_back(Tok);
319      ConsumeStringToken();
320      break;
321    case tok::semi:
322      if (StopAtSemi)
323        return false;
324      // FALL THROUGH.
325    default:
326      // consume this token.
327      Toks.push_back(Tok);
328      ConsumeToken();
329      break;
330    }
331    isFirstTokenConsumed = false;
332  }
333}
334