ParseCXXInlineMethods.cpp revision 210299
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(getCurScope(), D, true,
39                                          move(TemplateParams));
40  else // FIXME: pass template information through
41    FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), 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    = getCurScope()->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(getCurScope(), 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(getCurScope(), 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(getCurScope(), LM.Method);
115
116    // Start the delayed C++ method declaration
117    Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), 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(getCurScope(), 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 && Tok.isNot(tok::eof))
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(getCurScope(), 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(getCurScope(), 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(getCurScope(), 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(getCurScope(), 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(getCurScope(), 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      // There could be leftover tokens (e.g. because of an error).
220      // Skip through until we reach the original token position.
221      while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
222        ConsumeAnyToken();
223      continue;
224    }
225    if (Tok.is(tok::colon)) {
226      ParseConstructorInitializer(LM.D);
227
228      // Error recovery.
229      if (!Tok.is(tok::l_brace)) {
230        Actions.ActOnFinishFunctionBody(LM.D, Action::StmtArg(Actions));
231        continue;
232      }
233    } else
234      Actions.ActOnDefaultCtorInitializers(LM.D);
235
236    ParseFunctionStatementBody(LM.D);
237
238    if (Tok.getLocation() != origLoc) {
239      // Due to parsing error, we either went over the cached tokens or
240      // there are still cached tokens left. If it's the latter case skip the
241      // leftover tokens.
242      // Since this is an uncommon situation that should be avoided, use the
243      // expensive isBeforeInTranslationUnit call.
244      if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
245                                                          origLoc))
246        while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
247          ConsumeAnyToken();
248
249    }
250  }
251
252  for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
253    ParseLexedMethodDefs(*Class.NestedClasses[I]);
254}
255
256/// ConsumeAndStoreUntil - Consume and store the token at the passed token
257/// container until the token 'T' is reached (which gets
258/// consumed/stored too, if ConsumeFinalToken).
259/// If StopAtSemi is true, then we will stop early at a ';' character.
260/// Returns true if token 'T1' or 'T2' was found.
261/// NOTE: This is a specialized version of Parser::SkipUntil.
262bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
263                                  CachedTokens &Toks,
264                                  bool StopAtSemi, bool ConsumeFinalToken) {
265  // We always want this function to consume at least one token if the first
266  // token isn't T and if not at EOF.
267  bool isFirstTokenConsumed = true;
268  while (1) {
269    // If we found one of the tokens, stop and return true.
270    if (Tok.is(T1) || Tok.is(T2)) {
271      if (ConsumeFinalToken) {
272        Toks.push_back(Tok);
273        ConsumeAnyToken();
274      }
275      return true;
276    }
277
278    switch (Tok.getKind()) {
279    case tok::eof:
280      // Ran out of tokens.
281      return false;
282
283    case tok::l_paren:
284      // Recursively consume properly-nested parens.
285      Toks.push_back(Tok);
286      ConsumeParen();
287      ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
288      break;
289    case tok::l_square:
290      // Recursively consume properly-nested square brackets.
291      Toks.push_back(Tok);
292      ConsumeBracket();
293      ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
294      break;
295    case tok::l_brace:
296      // Recursively consume properly-nested braces.
297      Toks.push_back(Tok);
298      ConsumeBrace();
299      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
300      break;
301
302    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
303    // Since the user wasn't looking for this token (if they were, it would
304    // already be handled), this isn't balanced.  If there is a LHS token at a
305    // higher level, we will assume that this matches the unbalanced token
306    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
307    case tok::r_paren:
308      if (ParenCount && !isFirstTokenConsumed)
309        return false;  // Matches something.
310      Toks.push_back(Tok);
311      ConsumeParen();
312      break;
313    case tok::r_square:
314      if (BracketCount && !isFirstTokenConsumed)
315        return false;  // Matches something.
316      Toks.push_back(Tok);
317      ConsumeBracket();
318      break;
319    case tok::r_brace:
320      if (BraceCount && !isFirstTokenConsumed)
321        return false;  // Matches something.
322      Toks.push_back(Tok);
323      ConsumeBrace();
324      break;
325
326    case tok::string_literal:
327    case tok::wide_string_literal:
328      Toks.push_back(Tok);
329      ConsumeStringToken();
330      break;
331    case tok::semi:
332      if (StopAtSemi)
333        return false;
334      // FALL THROUGH.
335    default:
336      // consume this token.
337      Toks.push_back(Tok);
338      ConsumeToken();
339      break;
340    }
341    isFirstTokenConsumed = false;
342  }
343}
344