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