ParseCXXInlineMethods.cpp revision 2b602adf9798eaf13850efaf8ed41c69d3cf7da6
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 assert(Tok.is(tok::cxx_defaultarg_end) && 147 "We didn't parse the whole default arg!"); 148 ConsumeToken(); // Consume tok::cxx_defaultarg_end. 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