]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Parse/ParseCXXInlineMethods.cpp
Update clang to r100181.
[FreeBSD/FreeBSD.git] / lib / Parse / ParseCXXInlineMethods.cpp
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"
18 using 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.
23 Parser::DeclPtrTy
24 Parser::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.
92 void 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   // The current scope is still active if we're the top-level class.
99   // Otherwise we'll need to push and enter a new scope.
100   bool HasClassScope = !Class.TopLevelClass;
101   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, HasClassScope);
102   if (HasClassScope)
103     Actions.ActOnStartDelayedMemberDeclarations(CurScope, Class.TagOrTemplate);
104
105   for (; !Class.MethodDecls.empty(); Class.MethodDecls.pop_front()) {
106     LateParsedMethodDeclaration &LM = Class.MethodDecls.front();
107
108     // If this is a member template, introduce the template parameter scope.
109     ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
110     if (LM.TemplateScope)
111       Actions.ActOnReenterTemplateScope(CurScope, LM.Method);
112
113     // Start the delayed C++ method declaration
114     Actions.ActOnStartDelayedCXXMethodDeclaration(CurScope, LM.Method);
115
116     // Introduce the parameters into scope and parse their default
117     // arguments.
118     ParseScope PrototypeScope(this,
119                               Scope::FunctionPrototypeScope|Scope::DeclScope);
120     for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
121       // Introduce the parameter into scope.
122       Actions.ActOnDelayedCXXMethodParameter(CurScope, LM.DefaultArgs[I].Param);
123
124       if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
125         // Save the current token position.
126         SourceLocation origLoc = Tok.getLocation();
127
128         // Parse the default argument from its saved token stream.
129         Toks->push_back(Tok); // So that the current token doesn't get lost
130         PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
131
132         // Consume the previously-pushed token.
133         ConsumeAnyToken();
134
135         // Consume the '='.
136         assert(Tok.is(tok::equal) && "Default argument not starting with '='");
137         SourceLocation EqualLoc = ConsumeToken();
138
139         OwningExprResult DefArgResult(ParseAssignmentExpression());
140         if (DefArgResult.isInvalid())
141           Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
142         else
143           Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
144                                             move(DefArgResult));
145
146         assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
147                                                            Tok.getLocation()) &&
148                "ParseAssignmentExpression went over the default arg tokens!");
149         // There could be leftover tokens (e.g. because of an error).
150         // Skip through until we reach the original token position.
151         while (Tok.getLocation() != origLoc)
152           ConsumeAnyToken();
153
154         delete Toks;
155         LM.DefaultArgs[I].Toks = 0;
156       }
157     }
158     PrototypeScope.Exit();
159
160     // Finish the delayed C++ method declaration.
161     Actions.ActOnFinishDelayedCXXMethodDeclaration(CurScope, LM.Method);
162   }
163
164   for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
165     ParseLexedMethodDeclarations(*Class.NestedClasses[I]);
166
167   if (HasClassScope)
168     Actions.ActOnFinishDelayedMemberDeclarations(CurScope, Class.TagOrTemplate);
169 }
170
171 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
172 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
173 /// collected during its parsing and parse them all.
174 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
175   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
176   ParseScope TemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
177   if (HasTemplateScope)
178     Actions.ActOnReenterTemplateScope(CurScope, Class.TagOrTemplate);
179
180   bool HasClassScope = !Class.TopLevelClass;
181   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
182                         HasClassScope);
183
184   for (; !Class.MethodDefs.empty(); Class.MethodDefs.pop_front()) {
185     LexedMethod &LM = Class.MethodDefs.front();
186
187     // If this is a member template, introduce the template parameter scope.
188     ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
189     if (LM.TemplateScope)
190       Actions.ActOnReenterTemplateScope(CurScope, LM.D);
191
192     // Save the current token position.
193     SourceLocation origLoc = Tok.getLocation();
194
195     assert(!LM.Toks.empty() && "Empty body!");
196     // Append the current token at the end of the new token stream so that it
197     // doesn't get lost.
198     LM.Toks.push_back(Tok);
199     PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
200
201     // Consume the previously pushed token.
202     ConsumeAnyToken();
203     assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
204            && "Inline method not starting with '{', ':' or 'try'");
205
206     // Parse the method body. Function body parsing code is similar enough
207     // to be re-used for method bodies as well.
208     ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
209     Actions.ActOnStartOfFunctionDef(CurScope, LM.D);
210
211     if (Tok.is(tok::kw_try)) {
212       ParseFunctionTryBlock(LM.D);
213       assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
214                                                            Tok.getLocation()) &&
215              "ParseFunctionTryBlock went over the cached tokens!");
216       assert(Tok.getLocation() == origLoc &&
217              "ParseFunctionTryBlock left tokens in the token stream!");
218       continue;
219     }
220     if (Tok.is(tok::colon))
221       ParseConstructorInitializer(LM.D);
222     else
223       Actions.ActOnDefaultCtorInitializers(LM.D);
224
225     // FIXME: What if ParseConstructorInitializer doesn't leave us with a '{'??
226     ParseFunctionStatementBody(LM.D);
227     assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
228                                                            Tok.getLocation()) &&
229            "We consumed more than the cached tokens!");
230     assert(Tok.getLocation() == origLoc &&
231            "Tokens were left in the token stream!");
232   }
233
234   for (unsigned I = 0, N = Class.NestedClasses.size(); I != N; ++I)
235     ParseLexedMethodDefs(*Class.NestedClasses[I]);
236 }
237
238 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
239 /// container until the token 'T' is reached (which gets
240 /// consumed/stored too, if ConsumeFinalToken).
241 /// If EarlyAbortIf is specified, then we will stop early if we find that
242 /// token at the top level.
243 /// Returns true if token 'T1' or 'T2' was found.
244 /// NOTE: This is a specialized version of Parser::SkipUntil.
245 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
246                                   CachedTokens &Toks,
247                                   tok::TokenKind EarlyAbortIf,
248                                   bool ConsumeFinalToken) {
249   // We always want this function to consume at least one token if the first
250   // token isn't T and if not at EOF.
251   bool isFirstTokenConsumed = true;
252   while (1) {
253     // If we found one of the tokens, stop and return true.
254     if (Tok.is(T1) || Tok.is(T2)) {
255       if (ConsumeFinalToken) {
256         Toks.push_back(Tok);
257         ConsumeAnyToken();
258       }
259       return true;
260     }
261
262     // If we found the early-abort token, return.
263     if (Tok.is(EarlyAbortIf))
264       return false;
265
266     switch (Tok.getKind()) {
267     case tok::eof:
268       // Ran out of tokens.
269       return false;
270
271     case tok::l_paren:
272       // Recursively consume properly-nested parens.
273       Toks.push_back(Tok);
274       ConsumeParen();
275       ConsumeAndStoreUntil(tok::r_paren, tok::unknown, Toks);
276       break;
277     case tok::l_square:
278       // Recursively consume properly-nested square brackets.
279       Toks.push_back(Tok);
280       ConsumeBracket();
281       ConsumeAndStoreUntil(tok::r_square, tok::unknown, Toks);
282       break;
283     case tok::l_brace:
284       // Recursively consume properly-nested braces.
285       Toks.push_back(Tok);
286       ConsumeBrace();
287       ConsumeAndStoreUntil(tok::r_brace, tok::unknown, Toks);
288       break;
289
290     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
291     // Since the user wasn't looking for this token (if they were, it would
292     // already be handled), this isn't balanced.  If there is a LHS token at a
293     // higher level, we will assume that this matches the unbalanced token
294     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
295     case tok::r_paren:
296       if (ParenCount && !isFirstTokenConsumed)
297         return false;  // Matches something.
298       Toks.push_back(Tok);
299       ConsumeParen();
300       break;
301     case tok::r_square:
302       if (BracketCount && !isFirstTokenConsumed)
303         return false;  // Matches something.
304       Toks.push_back(Tok);
305       ConsumeBracket();
306       break;
307     case tok::r_brace:
308       if (BraceCount && !isFirstTokenConsumed)
309         return false;  // Matches something.
310       Toks.push_back(Tok);
311       ConsumeBrace();
312       break;
313
314     case tok::string_literal:
315     case tok::wide_string_literal:
316       Toks.push_back(Tok);
317       ConsumeStringToken();
318       break;
319     default:
320       // consume this token.
321       Toks.push_back(Tok);
322       ConsumeToken();
323       break;
324     }
325     isFirstTokenConsumed = false;
326   }
327 }