ParseCXXInlineMethods.cpp revision 199990
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  DeclPtrTy FnD;
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);
42
43  HandleMemberFunctionDefaultArgs(D, FnD);
44
45  // Consume the tokens and store them for later parsing.
46
47  getCurrentClass().MethodDefs.push_back(LexedMethod(FnD));
48  getCurrentClass().MethodDefs.back().TemplateScope
49    = CurScope->isTemplateParamScope();
50  CachedTokens &Toks = getCurrentClass().MethodDefs.back().Toks;
51
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);
63        ConsumeAnyToken();
64        getCurrentClass().MethodDefs.pop_back();
65        return FnD;
66      }
67    }
68
69  } else {
70    // Begin by storing the '{' token.
71    Toks.push_back(Tok);
72    ConsumeBrace();
73  }
74  // Consume everything up to (and including) the matching right brace.
75  ConsumeAndStoreUntil(tok::r_brace, tok::unknown, Toks);
76
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);
82    }
83  }
84
85  return FnD;
86}
87
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.
92void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
93  bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
94  ParseScope TemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
95  if (HasTemplateScope)
96    Actions.ActOnReenterTemplateScope(CurScope, Class.TagOrTemplate);
97
98  bool HasClassScope = !Class.TopLevelClass;
99  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
100                        HasClassScope);
101
102  for (; !Class.MethodDecls.empty(); Class.MethodDecls.pop_front()) {
103    LateParsedMethodDeclaration &LM = Class.MethodDecls.front();
104
105    // If this is a member template, introduce the template parameter scope.
106    ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
107    if (LM.TemplateScope)
108      Actions.ActOnReenterTemplateScope(CurScope, LM.Method);
109
110    // Start the delayed C++ method declaration
111    Actions.ActOnStartDelayedCXXMethodDeclaration(CurScope, LM.Method);
112
113    // Introduce the parameters into scope and parse their default
114    // arguments.
115    ParseScope PrototypeScope(this,
116                              Scope::FunctionPrototypeScope|Scope::DeclScope);
117    for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
118      // Introduce the parameter into scope.
119      Actions.ActOnDelayedCXXMethodParameter(CurScope, LM.DefaultArgs[I].Param);
120
121      if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
122        // Parse the default argument from its saved token stream.
123        Toks->push_back(Tok); // So that the current token doesn't get lost
124        PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
125
126        // Consume the previously-pushed token.
127        ConsumeAnyToken();
128
129        // Consume the '='.
130        assert(Tok.is(tok::equal) && "Default argument not starting with '='");
131        SourceLocation EqualLoc = ConsumeToken();
132
133        OwningExprResult DefArgResult(ParseAssignmentExpression());
134        if (DefArgResult.isInvalid())
135          Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
136        else
137          Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
138                                            move(DefArgResult));
139        delete Toks;
140        LM.DefaultArgs[I].Toks = 0;
141      }
142    }
143    PrototypeScope.Exit();
144
145    // Finish the delayed C++ method declaration.
146    Actions.ActOnFinishDelayedCXXMethodDeclaration(CurScope, LM.Method);
147  }
148
149  for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
150    ParseLexedMethodDeclarations(*Class.NestedClasses[I]);
151}
152
153/// ParseLexedMethodDefs - We finished parsing the member specification of a top
154/// (non-nested) C++ class. Now go over the stack of lexed methods that were
155/// collected during its parsing and parse them all.
156void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
157  bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
158  ParseScope TemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
159  if (HasTemplateScope)
160    Actions.ActOnReenterTemplateScope(CurScope, Class.TagOrTemplate);
161
162  bool HasClassScope = !Class.TopLevelClass;
163  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
164                        HasClassScope);
165
166  for (; !Class.MethodDefs.empty(); Class.MethodDefs.pop_front()) {
167    LexedMethod &LM = Class.MethodDefs.front();
168
169    // If this is a member template, introduce the template parameter scope.
170    ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
171    if (LM.TemplateScope)
172      Actions.ActOnReenterTemplateScope(CurScope, LM.D);
173
174    assert(!LM.Toks.empty() && "Empty body!");
175    // Append the current token at the end of the new token stream so that it
176    // doesn't get lost.
177    LM.Toks.push_back(Tok);
178    PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
179
180    // Consume the previously pushed token.
181    ConsumeAnyToken();
182    assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
183           && "Inline method not starting with '{', ':' or 'try'");
184
185    // Parse the method body. Function body parsing code is similar enough
186    // to be re-used for method bodies as well.
187    ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
188    Actions.ActOnStartOfFunctionDef(CurScope, LM.D);
189
190    if (Tok.is(tok::kw_try)) {
191      ParseFunctionTryBlock(LM.D);
192      continue;
193    }
194    if (Tok.is(tok::colon))
195      ParseConstructorInitializer(LM.D);
196    else
197      Actions.ActOnDefaultCtorInitializers(LM.D);
198
199    // FIXME: What if ParseConstructorInitializer doesn't leave us with a '{'??
200    ParseFunctionStatementBody(LM.D);
201  }
202
203  for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
204    ParseLexedMethodDefs(*Class.NestedClasses[I]);
205}
206
207/// ConsumeAndStoreUntil - Consume and store the token at the passed token
208/// container until the token 'T' is reached (which gets
209/// consumed/stored too, if ConsumeFinalToken).
210/// If EarlyAbortIf is specified, then we will stop early if we find that
211/// token at the top level.
212/// Returns true if token 'T1' or 'T2' was found.
213/// NOTE: This is a specialized version of Parser::SkipUntil.
214bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
215                                  CachedTokens &Toks,
216                                  tok::TokenKind EarlyAbortIf,
217                                  bool ConsumeFinalToken) {
218  // We always want this function to consume at least one token if the first
219  // token isn't T and if not at EOF.
220  bool isFirstTokenConsumed = true;
221  while (1) {
222    // If we found one of the tokens, stop and return true.
223    if (Tok.is(T1) || Tok.is(T2)) {
224      if (ConsumeFinalToken) {
225        Toks.push_back(Tok);
226        ConsumeAnyToken();
227      }
228      return true;
229    }
230
231    // If we found the early-abort token, return.
232    if (Tok.is(EarlyAbortIf))
233      return false;
234
235    switch (Tok.getKind()) {
236    case tok::eof:
237      // Ran out of tokens.
238      return false;
239
240    case tok::l_paren:
241      // Recursively consume properly-nested parens.
242      Toks.push_back(Tok);
243      ConsumeParen();
244      ConsumeAndStoreUntil(tok::r_paren, tok::unknown, Toks);
245      break;
246    case tok::l_square:
247      // Recursively consume properly-nested square brackets.
248      Toks.push_back(Tok);
249      ConsumeBracket();
250      ConsumeAndStoreUntil(tok::r_square, tok::unknown, Toks);
251      break;
252    case tok::l_brace:
253      // Recursively consume properly-nested braces.
254      Toks.push_back(Tok);
255      ConsumeBrace();
256      ConsumeAndStoreUntil(tok::r_brace, tok::unknown, Toks);
257      break;
258
259    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
260    // Since the user wasn't looking for this token (if they were, it would
261    // already be handled), this isn't balanced.  If there is a LHS token at a
262    // higher level, we will assume that this matches the unbalanced token
263    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
264    case tok::r_paren:
265      if (ParenCount && !isFirstTokenConsumed)
266        return false;  // Matches something.
267      Toks.push_back(Tok);
268      ConsumeParen();
269      break;
270    case tok::r_square:
271      if (BracketCount && !isFirstTokenConsumed)
272        return false;  // Matches something.
273      Toks.push_back(Tok);
274      ConsumeBracket();
275      break;
276    case tok::r_brace:
277      if (BraceCount && !isFirstTokenConsumed)
278        return false;  // Matches something.
279      Toks.push_back(Tok);
280      ConsumeBrace();
281      break;
282
283    case tok::string_literal:
284    case tok::wide_string_literal:
285      Toks.push_back(Tok);
286      ConsumeStringToken();
287      break;
288    default:
289      // consume this token.
290      Toks.push_back(Tok);
291      ConsumeToken();
292      break;
293    }
294    isFirstTokenConsumed = false;
295  }
296}
297