ParseCXXInlineMethods.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. #include "clang/Parse/ParseDiagnostic.h"
  14. #include "clang/Parse/Parser.h"
  15. #include "clang/Sema/DeclSpec.h"
  16. #include "clang/Sema/Scope.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "RAIIObjectsForParser.h"
  19. using namespace clang;
  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. Decl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
  24. AttributeList *AccessAttrs,
  25. ParsingDeclarator &D,
  26. const ParsedTemplateInfo &TemplateInfo,
  27. const VirtSpecifiers& VS,
  28. FunctionDefinitionKind DefinitionKind,
  29. ExprResult& Init) {
  30. assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
  31. assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
  32. Tok.is(tok::equal)) &&
  33. "Current token not a '{', ':', '=', or 'try'!");
  34. MultiTemplateParamsArg TemplateParams(Actions,
  35. TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
  36. TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
  37. Decl *FnD;
  38. D.setFunctionDefinitionKind(DefinitionKind);
  39. if (D.getDeclSpec().isFriendSpecified())
  40. FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
  41. TemplateParams);
  42. else {
  43. FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
  44. TemplateParams, 0,
  45. VS, ICIS_NoInit);
  46. if (FnD) {
  47. Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs,
  48. false, true);
  49. bool TypeSpecContainsAuto
  50. = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
  51. if (Init.isUsable())
  52. Actions.AddInitializerToDecl(FnD, Init.get(), false,
  53. TypeSpecContainsAuto);
  54. else
  55. Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
  56. }
  57. }
  58. HandleMemberFunctionDeclDelays(D, FnD);
  59. D.complete(FnD);
  60. if (Tok.is(tok::equal)) {
  61. ConsumeToken();
  62. if (!FnD) {
  63. SkipUntil(tok::semi);
  64. return 0;
  65. }
  66. bool Delete = false;
  67. SourceLocation KWLoc;
  68. if (Tok.is(tok::kw_delete)) {
  69. Diag(Tok, getLangOpts().CPlusPlus0x ?
  70. diag::warn_cxx98_compat_deleted_function :
  71. diag::ext_deleted_function);
  72. KWLoc = ConsumeToken();
  73. Actions.SetDeclDeleted(FnD, KWLoc);
  74. Delete = true;
  75. } else if (Tok.is(tok::kw_default)) {
  76. Diag(Tok, getLangOpts().CPlusPlus0x ?
  77. diag::warn_cxx98_compat_defaulted_function :
  78. diag::ext_defaulted_function);
  79. KWLoc = ConsumeToken();
  80. Actions.SetDeclDefaulted(FnD, KWLoc);
  81. } else {
  82. llvm_unreachable("function definition after = not 'delete' or 'default'");
  83. }
  84. if (Tok.is(tok::comma)) {
  85. Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
  86. << Delete;
  87. SkipUntil(tok::semi);
  88. } else {
  89. ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
  90. Delete ? "delete" : "default", tok::semi);
  91. }
  92. return FnD;
  93. }
  94. // In delayed template parsing mode, if we are within a class template
  95. // or if we are about to parse function member template then consume
  96. // the tokens and store them for parsing at the end of the translation unit.
  97. if (getLangOpts().DelayedTemplateParsing &&
  98. DefinitionKind == FDK_Definition &&
  99. ((Actions.CurContext->isDependentContext() ||
  100. TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) &&
  101. !Actions.IsInsideALocalClassWithinATemplateFunction())) {
  102. if (FnD) {
  103. LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(FnD);
  104. FunctionDecl *FD = 0;
  105. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(FnD))
  106. FD = FunTmpl->getTemplatedDecl();
  107. else
  108. FD = cast<FunctionDecl>(FnD);
  109. Actions.CheckForFunctionRedefinition(FD);
  110. LateParsedTemplateMap[FD] = LPT;
  111. Actions.MarkAsLateParsedTemplate(FD);
  112. LexTemplateFunctionForLateParsing(LPT->Toks);
  113. } else {
  114. CachedTokens Toks;
  115. LexTemplateFunctionForLateParsing(Toks);
  116. }
  117. return FnD;
  118. }
  119. // Consume the tokens and store them for later parsing.
  120. LexedMethod* LM = new LexedMethod(this, FnD);
  121. getCurrentClass().LateParsedDeclarations.push_back(LM);
  122. LM->TemplateScope = getCurScope()->isTemplateParamScope();
  123. CachedTokens &Toks = LM->Toks;
  124. tok::TokenKind kind = Tok.getKind();
  125. // Consume everything up to (and including) the left brace of the
  126. // function body.
  127. if (ConsumeAndStoreFunctionPrologue(Toks)) {
  128. // We didn't find the left-brace we expected after the
  129. // constructor initializer; we already printed an error, and it's likely
  130. // impossible to recover, so don't try to parse this method later.
  131. // If we stopped at a semicolon, consume it to avoid an extra warning.
  132. if (Tok.is(tok::semi))
  133. ConsumeToken();
  134. delete getCurrentClass().LateParsedDeclarations.back();
  135. getCurrentClass().LateParsedDeclarations.pop_back();
  136. return FnD;
  137. } else {
  138. // Consume everything up to (and including) the matching right brace.
  139. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  140. }
  141. // If we're in a function-try-block, we need to store all the catch blocks.
  142. if (kind == tok::kw_try) {
  143. while (Tok.is(tok::kw_catch)) {
  144. ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
  145. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  146. }
  147. }
  148. if (!FnD) {
  149. // If semantic analysis could not build a function declaration,
  150. // just throw away the late-parsed declaration.
  151. delete getCurrentClass().LateParsedDeclarations.back();
  152. getCurrentClass().LateParsedDeclarations.pop_back();
  153. }
  154. return FnD;
  155. }
  156. /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
  157. /// specified Declarator is a well formed C++ non-static data member
  158. /// declaration. Now lex its initializer and store its tokens for parsing
  159. /// after the class is complete.
  160. void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
  161. assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
  162. "Current token not a '{' or '='!");
  163. LateParsedMemberInitializer *MI =
  164. new LateParsedMemberInitializer(this, VarD);
  165. getCurrentClass().LateParsedDeclarations.push_back(MI);
  166. CachedTokens &Toks = MI->Toks;
  167. tok::TokenKind kind = Tok.getKind();
  168. if (kind == tok::equal) {
  169. Toks.push_back(Tok);
  170. ConsumeToken();
  171. }
  172. if (kind == tok::l_brace) {
  173. // Begin by storing the '{' token.
  174. Toks.push_back(Tok);
  175. ConsumeBrace();
  176. // Consume everything up to (and including) the matching right brace.
  177. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
  178. } else {
  179. // Consume everything up to (but excluding) the comma or semicolon.
  180. ConsumeAndStoreUntil(tok::comma, Toks, /*StopAtSemi=*/true,
  181. /*ConsumeFinalToken=*/false);
  182. }
  183. // Store an artificial EOF token to ensure that we don't run off the end of
  184. // the initializer when we come to parse it.
  185. Token Eof;
  186. Eof.startToken();
  187. Eof.setKind(tok::eof);
  188. Eof.setLocation(Tok.getLocation());
  189. Toks.push_back(Eof);
  190. }
  191. Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
  192. void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
  193. void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
  194. void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
  195. Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
  196. : Self(P), Class(C) {}
  197. Parser::LateParsedClass::~LateParsedClass() {
  198. Self->DeallocateParsedClasses(Class);
  199. }
  200. void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
  201. Self->ParseLexedMethodDeclarations(*Class);
  202. }
  203. void Parser::LateParsedClass::ParseLexedMemberInitializers() {
  204. Self->ParseLexedMemberInitializers(*Class);
  205. }
  206. void Parser::LateParsedClass::ParseLexedMethodDefs() {
  207. Self->ParseLexedMethodDefs(*Class);
  208. }
  209. void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
  210. Self->ParseLexedMethodDeclaration(*this);
  211. }
  212. void Parser::LexedMethod::ParseLexedMethodDefs() {
  213. Self->ParseLexedMethodDef(*this);
  214. }
  215. void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
  216. Self->ParseLexedMemberInitializer(*this);
  217. }
  218. /// ParseLexedMethodDeclarations - We finished parsing the member
  219. /// specification of a top (non-nested) C++ class. Now go over the
  220. /// stack of method declarations with some parts for which parsing was
  221. /// delayed (such as default arguments) and parse them.
  222. void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
  223. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  224. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
  225. if (HasTemplateScope)
  226. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  227. // The current scope is still active if we're the top-level class.
  228. // Otherwise we'll need to push and enter a new scope.
  229. bool HasClassScope = !Class.TopLevelClass;
  230. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
  231. HasClassScope);
  232. if (HasClassScope)
  233. Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
  234. for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
  235. Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
  236. }
  237. if (HasClassScope)
  238. Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
  239. }
  240. void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
  241. // If this is a member template, introduce the template parameter scope.
  242. ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
  243. if (LM.TemplateScope)
  244. Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
  245. // Start the delayed C++ method declaration
  246. Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
  247. // Introduce the parameters into scope and parse their default
  248. // arguments.
  249. ParseScope PrototypeScope(this,
  250. Scope::FunctionPrototypeScope|Scope::DeclScope);
  251. for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
  252. // Introduce the parameter into scope.
  253. Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
  254. LM.DefaultArgs[I].Param);
  255. if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
  256. // Save the current token position.
  257. SourceLocation origLoc = Tok.getLocation();
  258. // Parse the default argument from its saved token stream.
  259. Toks->push_back(Tok); // So that the current token doesn't get lost
  260. PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
  261. // Consume the previously-pushed token.
  262. ConsumeAnyToken();
  263. // Consume the '='.
  264. assert(Tok.is(tok::equal) && "Default argument not starting with '='");
  265. SourceLocation EqualLoc = ConsumeToken();
  266. // The argument isn't actually potentially evaluated unless it is
  267. // used.
  268. EnterExpressionEvaluationContext Eval(Actions,
  269. Sema::PotentiallyEvaluatedIfUsed,
  270. LM.DefaultArgs[I].Param);
  271. ExprResult DefArgResult;
  272. if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
  273. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  274. DefArgResult = ParseBraceInitializer();
  275. } else
  276. DefArgResult = ParseAssignmentExpression();
  277. if (DefArgResult.isInvalid())
  278. Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
  279. else {
  280. if (Tok.is(tok::cxx_defaultarg_end))
  281. ConsumeToken();
  282. else
  283. Diag(Tok.getLocation(), diag::err_default_arg_unparsed);
  284. Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
  285. DefArgResult.take());
  286. }
  287. assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
  288. Tok.getLocation()) &&
  289. "ParseAssignmentExpression went over the default arg tokens!");
  290. // There could be leftover tokens (e.g. because of an error).
  291. // Skip through until we reach the original token position.
  292. while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
  293. ConsumeAnyToken();
  294. delete Toks;
  295. LM.DefaultArgs[I].Toks = 0;
  296. }
  297. }
  298. PrototypeScope.Exit();
  299. // Finish the delayed C++ method declaration.
  300. Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
  301. }
  302. /// ParseLexedMethodDefs - We finished parsing the member specification of a top
  303. /// (non-nested) C++ class. Now go over the stack of lexed methods that were
  304. /// collected during its parsing and parse them all.
  305. void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
  306. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  307. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
  308. if (HasTemplateScope)
  309. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  310. bool HasClassScope = !Class.TopLevelClass;
  311. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
  312. HasClassScope);
  313. for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
  314. Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
  315. }
  316. }
  317. void Parser::ParseLexedMethodDef(LexedMethod &LM) {
  318. // If this is a member template, introduce the template parameter scope.
  319. ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
  320. if (LM.TemplateScope)
  321. Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
  322. // Save the current token position.
  323. SourceLocation origLoc = Tok.getLocation();
  324. assert(!LM.Toks.empty() && "Empty body!");
  325. // Append the current token at the end of the new token stream so that it
  326. // doesn't get lost.
  327. LM.Toks.push_back(Tok);
  328. PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
  329. // Consume the previously pushed token.
  330. ConsumeAnyToken();
  331. assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
  332. && "Inline method not starting with '{', ':' or 'try'");
  333. // Parse the method body. Function body parsing code is similar enough
  334. // to be re-used for method bodies as well.
  335. ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
  336. Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
  337. if (Tok.is(tok::kw_try)) {
  338. ParseFunctionTryBlock(LM.D, FnScope);
  339. assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
  340. Tok.getLocation()) &&
  341. "ParseFunctionTryBlock went over the cached tokens!");
  342. // There could be leftover tokens (e.g. because of an error).
  343. // Skip through until we reach the original token position.
  344. while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
  345. ConsumeAnyToken();
  346. return;
  347. }
  348. if (Tok.is(tok::colon)) {
  349. ParseConstructorInitializer(LM.D);
  350. // Error recovery.
  351. if (!Tok.is(tok::l_brace)) {
  352. FnScope.Exit();
  353. Actions.ActOnFinishFunctionBody(LM.D, 0);
  354. while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
  355. ConsumeAnyToken();
  356. return;
  357. }
  358. } else
  359. Actions.ActOnDefaultCtorInitializers(LM.D);
  360. ParseFunctionStatementBody(LM.D, FnScope);
  361. if (Tok.getLocation() != origLoc) {
  362. // Due to parsing error, we either went over the cached tokens or
  363. // there are still cached tokens left. If it's the latter case skip the
  364. // leftover tokens.
  365. // Since this is an uncommon situation that should be avoided, use the
  366. // expensive isBeforeInTranslationUnit call.
  367. if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
  368. origLoc))
  369. while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
  370. ConsumeAnyToken();
  371. }
  372. }
  373. /// ParseLexedMemberInitializers - We finished parsing the member specification
  374. /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
  375. /// initializers that were collected during its parsing and parse them all.
  376. void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
  377. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  378. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
  379. HasTemplateScope);
  380. if (HasTemplateScope)
  381. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  382. // Set or update the scope flags.
  383. bool AlreadyHasClassScope = Class.TopLevelClass;
  384. unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
  385. ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
  386. ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
  387. if (!AlreadyHasClassScope)
  388. Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
  389. Class.TagOrTemplate);
  390. if (!Class.LateParsedDeclarations.empty()) {
  391. // C++11 [expr.prim.general]p4:
  392. // Otherwise, if a member-declarator declares a non-static data member
  393. // (9.2) of a class X, the expression this is a prvalue of type "pointer
  394. // to X" within the optional brace-or-equal-initializer. It shall not
  395. // appear elsewhere in the member-declarator.
  396. Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
  397. /*TypeQuals=*/(unsigned)0);
  398. for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
  399. Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
  400. }
  401. }
  402. if (!AlreadyHasClassScope)
  403. Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
  404. Class.TagOrTemplate);
  405. Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
  406. }
  407. void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
  408. if (!MI.Field || MI.Field->isInvalidDecl())
  409. return;
  410. // Append the current token at the end of the new token stream so that it
  411. // doesn't get lost.
  412. MI.Toks.push_back(Tok);
  413. PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
  414. // Consume the previously pushed token.
  415. ConsumeAnyToken();
  416. SourceLocation EqualLoc;
  417. ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
  418. EqualLoc);
  419. Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
  420. // The next token should be our artificial terminating EOF token.
  421. if (Tok.isNot(tok::eof)) {
  422. SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
  423. if (!EndLoc.isValid())
  424. EndLoc = Tok.getLocation();
  425. // No fixit; we can't recover as if there were a semicolon here.
  426. Diag(EndLoc, diag::err_expected_semi_decl_list);
  427. // Consume tokens until we hit the artificial EOF.
  428. while (Tok.isNot(tok::eof))
  429. ConsumeAnyToken();
  430. }
  431. ConsumeAnyToken();
  432. }
  433. /// ConsumeAndStoreUntil - Consume and store the token at the passed token
  434. /// container until the token 'T' is reached (which gets
  435. /// consumed/stored too, if ConsumeFinalToken).
  436. /// If StopAtSemi is true, then we will stop early at a ';' character.
  437. /// Returns true if token 'T1' or 'T2' was found.
  438. /// NOTE: This is a specialized version of Parser::SkipUntil.
  439. bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
  440. CachedTokens &Toks,
  441. bool StopAtSemi, bool ConsumeFinalToken) {
  442. // We always want this function to consume at least one token if the first
  443. // token isn't T and if not at EOF.
  444. bool isFirstTokenConsumed = true;
  445. while (1) {
  446. // If we found one of the tokens, stop and return true.
  447. if (Tok.is(T1) || Tok.is(T2)) {
  448. if (ConsumeFinalToken) {
  449. Toks.push_back(Tok);
  450. ConsumeAnyToken();
  451. }
  452. return true;
  453. }
  454. switch (Tok.getKind()) {
  455. case tok::eof:
  456. // Ran out of tokens.
  457. return false;
  458. case tok::l_paren:
  459. // Recursively consume properly-nested parens.
  460. Toks.push_back(Tok);
  461. ConsumeParen();
  462. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  463. break;
  464. case tok::l_square:
  465. // Recursively consume properly-nested square brackets.
  466. Toks.push_back(Tok);
  467. ConsumeBracket();
  468. ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
  469. break;
  470. case tok::l_brace:
  471. // Recursively consume properly-nested braces.
  472. Toks.push_back(Tok);
  473. ConsumeBrace();
  474. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  475. break;
  476. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  477. // Since the user wasn't looking for this token (if they were, it would
  478. // already be handled), this isn't balanced. If there is a LHS token at a
  479. // higher level, we will assume that this matches the unbalanced token
  480. // and return it. Otherwise, this is a spurious RHS token, which we skip.
  481. case tok::r_paren:
  482. if (ParenCount && !isFirstTokenConsumed)
  483. return false; // Matches something.
  484. Toks.push_back(Tok);
  485. ConsumeParen();
  486. break;
  487. case tok::r_square:
  488. if (BracketCount && !isFirstTokenConsumed)
  489. return false; // Matches something.
  490. Toks.push_back(Tok);
  491. ConsumeBracket();
  492. break;
  493. case tok::r_brace:
  494. if (BraceCount && !isFirstTokenConsumed)
  495. return false; // Matches something.
  496. Toks.push_back(Tok);
  497. ConsumeBrace();
  498. break;
  499. case tok::code_completion:
  500. Toks.push_back(Tok);
  501. ConsumeCodeCompletionToken();
  502. break;
  503. case tok::string_literal:
  504. case tok::wide_string_literal:
  505. case tok::utf8_string_literal:
  506. case tok::utf16_string_literal:
  507. case tok::utf32_string_literal:
  508. Toks.push_back(Tok);
  509. ConsumeStringToken();
  510. break;
  511. case tok::semi:
  512. if (StopAtSemi)
  513. return false;
  514. // FALL THROUGH.
  515. default:
  516. // consume this token.
  517. Toks.push_back(Tok);
  518. ConsumeToken();
  519. break;
  520. }
  521. isFirstTokenConsumed = false;
  522. }
  523. }
  524. /// \brief Consume tokens and store them in the passed token container until
  525. /// we've passed the try keyword and constructor initializers and have consumed
  526. /// the opening brace of the function body. The opening brace will be consumed
  527. /// if and only if there was no error.
  528. ///
  529. /// \return True on error.
  530. bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
  531. if (Tok.is(tok::kw_try)) {
  532. Toks.push_back(Tok);
  533. ConsumeToken();
  534. }
  535. bool ReadInitializer = false;
  536. if (Tok.is(tok::colon)) {
  537. // Initializers can contain braces too.
  538. Toks.push_back(Tok);
  539. ConsumeToken();
  540. while (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
  541. if (Tok.is(tok::eof) || Tok.is(tok::semi))
  542. return Diag(Tok.getLocation(), diag::err_expected_lbrace);
  543. // Grab the identifier.
  544. if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
  545. /*StopAtSemi=*/true,
  546. /*ConsumeFinalToken=*/false))
  547. return Diag(Tok.getLocation(), diag::err_expected_lparen);
  548. tok::TokenKind kind = Tok.getKind();
  549. Toks.push_back(Tok);
  550. bool IsLParen = (kind == tok::l_paren);
  551. SourceLocation LOpen = Tok.getLocation();
  552. if (IsLParen) {
  553. ConsumeParen();
  554. } else {
  555. assert(kind == tok::l_brace && "Must be left paren or brace here.");
  556. ConsumeBrace();
  557. // In C++03, this has to be the start of the function body, which
  558. // means the initializer is malformed; we'll diagnose it later.
  559. if (!getLangOpts().CPlusPlus0x)
  560. return false;
  561. }
  562. // Grab the initializer
  563. if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
  564. Toks, /*StopAtSemi=*/true)) {
  565. Diag(Tok, IsLParen ? diag::err_expected_rparen :
  566. diag::err_expected_rbrace);
  567. Diag(LOpen, diag::note_matching) << (IsLParen ? "(" : "{");
  568. return true;
  569. }
  570. // Grab pack ellipsis, if present
  571. if (Tok.is(tok::ellipsis)) {
  572. Toks.push_back(Tok);
  573. ConsumeToken();
  574. }
  575. // Grab the separating comma, if any.
  576. if (Tok.is(tok::comma)) {
  577. Toks.push_back(Tok);
  578. ConsumeToken();
  579. } else if (Tok.isNot(tok::l_brace)) {
  580. ReadInitializer = true;
  581. break;
  582. }
  583. }
  584. }
  585. // Grab any remaining garbage to be diagnosed later. We stop when we reach a
  586. // brace: an opening one is the function body, while a closing one probably
  587. // means we've reached the end of the class.
  588. ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
  589. /*StopAtSemi=*/true,
  590. /*ConsumeFinalToken=*/false);
  591. if (Tok.isNot(tok::l_brace)) {
  592. if (ReadInitializer)
  593. return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
  594. return Diag(Tok.getLocation(), diag::err_expected_lbrace);
  595. }
  596. Toks.push_back(Tok);
  597. ConsumeBrace();
  598. return false;
  599. }