ParseCXXInlineMethods.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. //===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements parsing for C++ class inline methods.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Parse/Parser.h"
  13. #include "clang/AST/DeclTemplate.h"
  14. #include "clang/Parse/ParseDiagnostic.h"
  15. #include "clang/Parse/RAIIObjectsForParser.h"
  16. #include "clang/Sema/DeclSpec.h"
  17. #include "clang/Sema/Scope.h"
  18. using namespace clang;
  19. /// ParseCXXInlineMethodDef - We parsed and verified that the specified
  20. /// Declarator is a well formed C++ inline method definition. Now lex its body
  21. /// and store its tokens for parsing after the C++ class is complete.
  22. NamedDecl *Parser::ParseCXXInlineMethodDef(
  23. AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D,
  24. const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS,
  25. SourceLocation PureSpecLoc) {
  26. assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
  27. assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
  28. "Current token not a '{', ':', '=', or 'try'!");
  29. MultiTemplateParamsArg TemplateParams(
  30. TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
  31. : nullptr,
  32. TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
  33. NamedDecl *FnD;
  34. if (D.getDeclSpec().isFriendSpecified())
  35. FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
  36. TemplateParams);
  37. else {
  38. FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
  39. TemplateParams, nullptr,
  40. VS, ICIS_NoInit);
  41. if (FnD) {
  42. Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
  43. if (PureSpecLoc.isValid())
  44. Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
  45. }
  46. }
  47. if (FnD)
  48. HandleMemberFunctionDeclDelays(D, FnD);
  49. D.complete(FnD);
  50. if (TryConsumeToken(tok::equal)) {
  51. if (!FnD) {
  52. SkipUntil(tok::semi);
  53. return nullptr;
  54. }
  55. bool Delete = false;
  56. SourceLocation KWLoc;
  57. SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
  58. if (TryConsumeToken(tok::kw_delete, KWLoc)) {
  59. Diag(KWLoc, getLangOpts().CPlusPlus11
  60. ? diag::warn_cxx98_compat_defaulted_deleted_function
  61. : diag::ext_defaulted_deleted_function)
  62. << 1 /* deleted */;
  63. Actions.SetDeclDeleted(FnD, KWLoc);
  64. Delete = true;
  65. if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
  66. DeclAsFunction->setRangeEnd(KWEndLoc);
  67. }
  68. } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
  69. Diag(KWLoc, getLangOpts().CPlusPlus11
  70. ? diag::warn_cxx98_compat_defaulted_deleted_function
  71. : diag::ext_defaulted_deleted_function)
  72. << 0 /* defaulted */;
  73. Actions.SetDeclDefaulted(FnD, KWLoc);
  74. if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
  75. DeclAsFunction->setRangeEnd(KWEndLoc);
  76. }
  77. } else {
  78. llvm_unreachable("function definition after = not 'delete' or 'default'");
  79. }
  80. if (Tok.is(tok::comma)) {
  81. Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
  82. << Delete;
  83. SkipUntil(tok::semi);
  84. } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  85. Delete ? "delete" : "default")) {
  86. SkipUntil(tok::semi);
  87. }
  88. return FnD;
  89. }
  90. if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) &&
  91. trySkippingFunctionBody()) {
  92. Actions.ActOnSkippedFunctionBody(FnD);
  93. return FnD;
  94. }
  95. // In delayed template parsing mode, if we are within a class template
  96. // or if we are about to parse function member template then consume
  97. // the tokens and store them for parsing at the end of the translation unit.
  98. if (getLangOpts().DelayedTemplateParsing &&
  99. D.getFunctionDefinitionKind() == FDK_Definition &&
  100. !D.getDeclSpec().hasConstexprSpecifier() &&
  101. !(FnD && FnD->getAsFunction() &&
  102. FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
  103. ((Actions.CurContext->isDependentContext() ||
  104. (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
  105. TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
  106. !Actions.IsInsideALocalClassWithinATemplateFunction())) {
  107. CachedTokens Toks;
  108. LexTemplateFunctionForLateParsing(Toks);
  109. if (FnD) {
  110. FunctionDecl *FD = FnD->getAsFunction();
  111. Actions.CheckForFunctionRedefinition(FD);
  112. Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
  113. }
  114. return FnD;
  115. }
  116. // Consume the tokens and store them for later parsing.
  117. LexedMethod* LM = new LexedMethod(this, FnD);
  118. getCurrentClass().LateParsedDeclarations.push_back(LM);
  119. LM->TemplateScope = getCurScope()->isTemplateParamScope();
  120. CachedTokens &Toks = LM->Toks;
  121. tok::TokenKind kind = Tok.getKind();
  122. // Consume everything up to (and including) the left brace of the
  123. // function body.
  124. if (ConsumeAndStoreFunctionPrologue(Toks)) {
  125. // We didn't find the left-brace we expected after the
  126. // constructor initializer; we already printed an error, and it's likely
  127. // impossible to recover, so don't try to parse this method later.
  128. // Skip over the rest of the decl and back to somewhere that looks
  129. // reasonable.
  130. SkipMalformedDecl();
  131. delete getCurrentClass().LateParsedDeclarations.back();
  132. getCurrentClass().LateParsedDeclarations.pop_back();
  133. return FnD;
  134. } else {
  135. // Consume everything up to (and including) the matching right brace.
  136. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  137. }
  138. // If we're in a function-try-block, we need to store all the catch blocks.
  139. if (kind == tok::kw_try) {
  140. while (Tok.is(tok::kw_catch)) {
  141. ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
  142. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  143. }
  144. }
  145. if (FnD) {
  146. FunctionDecl *FD = FnD->getAsFunction();
  147. // Track that this function will eventually have a body; Sema needs
  148. // to know this.
  149. Actions.CheckForFunctionRedefinition(FD);
  150. FD->setWillHaveBody(true);
  151. } else {
  152. // If semantic analysis could not build a function declaration,
  153. // just throw away the late-parsed declaration.
  154. delete getCurrentClass().LateParsedDeclarations.back();
  155. getCurrentClass().LateParsedDeclarations.pop_back();
  156. }
  157. return FnD;
  158. }
  159. /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
  160. /// specified Declarator is a well formed C++ non-static data member
  161. /// declaration. Now lex its initializer and store its tokens for parsing
  162. /// after the class is complete.
  163. void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
  164. assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
  165. "Current token not a '{' or '='!");
  166. LateParsedMemberInitializer *MI =
  167. new LateParsedMemberInitializer(this, VarD);
  168. getCurrentClass().LateParsedDeclarations.push_back(MI);
  169. CachedTokens &Toks = MI->Toks;
  170. tok::TokenKind kind = Tok.getKind();
  171. if (kind == tok::equal) {
  172. Toks.push_back(Tok);
  173. ConsumeToken();
  174. }
  175. if (kind == tok::l_brace) {
  176. // Begin by storing the '{' token.
  177. Toks.push_back(Tok);
  178. ConsumeBrace();
  179. // Consume everything up to (and including) the matching right brace.
  180. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
  181. } else {
  182. // Consume everything up to (but excluding) the comma or semicolon.
  183. ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
  184. }
  185. // Store an artificial EOF token to ensure that we don't run off the end of
  186. // the initializer when we come to parse it.
  187. Token Eof;
  188. Eof.startToken();
  189. Eof.setKind(tok::eof);
  190. Eof.setLocation(Tok.getLocation());
  191. Eof.setEofData(VarD);
  192. Toks.push_back(Eof);
  193. }
  194. Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
  195. void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
  196. void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
  197. void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
  198. Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
  199. : Self(P), Class(C) {}
  200. Parser::LateParsedClass::~LateParsedClass() {
  201. Self->DeallocateParsedClasses(Class);
  202. }
  203. void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
  204. Self->ParseLexedMethodDeclarations(*Class);
  205. }
  206. void Parser::LateParsedClass::ParseLexedMemberInitializers() {
  207. Self->ParseLexedMemberInitializers(*Class);
  208. }
  209. void Parser::LateParsedClass::ParseLexedMethodDefs() {
  210. Self->ParseLexedMethodDefs(*Class);
  211. }
  212. void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
  213. Self->ParseLexedMethodDeclaration(*this);
  214. }
  215. void Parser::LexedMethod::ParseLexedMethodDefs() {
  216. Self->ParseLexedMethodDef(*this);
  217. }
  218. void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
  219. Self->ParseLexedMemberInitializer(*this);
  220. }
  221. /// ParseLexedMethodDeclarations - We finished parsing the member
  222. /// specification of a top (non-nested) C++ class. Now go over the
  223. /// stack of method declarations with some parts for which parsing was
  224. /// delayed (such as default arguments) and parse them.
  225. void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
  226. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  227. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
  228. HasTemplateScope);
  229. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  230. if (HasTemplateScope) {
  231. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  232. ++CurTemplateDepthTracker;
  233. }
  234. // The current scope is still active if we're the top-level class.
  235. // Otherwise we'll need to push and enter a new scope.
  236. bool HasClassScope = !Class.TopLevelClass;
  237. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
  238. HasClassScope);
  239. if (HasClassScope)
  240. Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
  241. Class.TagOrTemplate);
  242. for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
  243. Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
  244. }
  245. if (HasClassScope)
  246. Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
  247. Class.TagOrTemplate);
  248. }
  249. void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
  250. // If this is a member template, introduce the template parameter scope.
  251. ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
  252. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  253. if (LM.TemplateScope) {
  254. Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
  255. ++CurTemplateDepthTracker;
  256. }
  257. // Start the delayed C++ method declaration
  258. Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
  259. // Introduce the parameters into scope and parse their default
  260. // arguments.
  261. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
  262. Scope::FunctionDeclarationScope | Scope::DeclScope);
  263. for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
  264. auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
  265. // Introduce the parameter into scope.
  266. bool HasUnparsed = Param->hasUnparsedDefaultArg();
  267. Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
  268. std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
  269. if (Toks) {
  270. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  271. // Mark the end of the default argument so that we know when to stop when
  272. // we parse it later on.
  273. Token LastDefaultArgToken = Toks->back();
  274. Token DefArgEnd;
  275. DefArgEnd.startToken();
  276. DefArgEnd.setKind(tok::eof);
  277. DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
  278. DefArgEnd.setEofData(Param);
  279. Toks->push_back(DefArgEnd);
  280. // Parse the default argument from its saved token stream.
  281. Toks->push_back(Tok); // So that the current token doesn't get lost
  282. PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true);
  283. // Consume the previously-pushed token.
  284. ConsumeAnyToken();
  285. // Consume the '='.
  286. assert(Tok.is(tok::equal) && "Default argument not starting with '='");
  287. SourceLocation EqualLoc = ConsumeToken();
  288. // The argument isn't actually potentially evaluated unless it is
  289. // used.
  290. EnterExpressionEvaluationContext Eval(
  291. Actions,
  292. Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, Param);
  293. ExprResult DefArgResult;
  294. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  295. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  296. DefArgResult = ParseBraceInitializer();
  297. } else
  298. DefArgResult = ParseAssignmentExpression();
  299. DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
  300. if (DefArgResult.isInvalid()) {
  301. Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
  302. } else {
  303. if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
  304. // The last two tokens are the terminator and the saved value of
  305. // Tok; the last token in the default argument is the one before
  306. // those.
  307. assert(Toks->size() >= 3 && "expected a token in default arg");
  308. Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
  309. << SourceRange(Tok.getLocation(),
  310. (*Toks)[Toks->size() - 3].getLocation());
  311. }
  312. Actions.ActOnParamDefaultArgument(Param, EqualLoc,
  313. DefArgResult.get());
  314. }
  315. // There could be leftover tokens (e.g. because of an error).
  316. // Skip through until we reach the 'end of default argument' token.
  317. while (Tok.isNot(tok::eof))
  318. ConsumeAnyToken();
  319. if (Tok.is(tok::eof) && Tok.getEofData() == Param)
  320. ConsumeAnyToken();
  321. } else if (HasUnparsed) {
  322. assert(Param->hasInheritedDefaultArg());
  323. FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
  324. ParmVarDecl *OldParam = Old->getParamDecl(I);
  325. assert (!OldParam->hasUnparsedDefaultArg());
  326. if (OldParam->hasUninstantiatedDefaultArg())
  327. Param->setUninstantiatedDefaultArg(
  328. OldParam->getUninstantiatedDefaultArg());
  329. else
  330. Param->setDefaultArg(OldParam->getInit());
  331. }
  332. }
  333. // Parse a delayed exception-specification, if there is one.
  334. if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
  335. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  336. // Add the 'stop' token.
  337. Token LastExceptionSpecToken = Toks->back();
  338. Token ExceptionSpecEnd;
  339. ExceptionSpecEnd.startToken();
  340. ExceptionSpecEnd.setKind(tok::eof);
  341. ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
  342. ExceptionSpecEnd.setEofData(LM.Method);
  343. Toks->push_back(ExceptionSpecEnd);
  344. // Parse the default argument from its saved token stream.
  345. Toks->push_back(Tok); // So that the current token doesn't get lost
  346. PP.EnterTokenStream(*Toks, true, /*IsReinject*/true);
  347. // Consume the previously-pushed token.
  348. ConsumeAnyToken();
  349. // C++11 [expr.prim.general]p3:
  350. // If a declaration declares a member function or member function
  351. // template of a class X, the expression this is a prvalue of type
  352. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  353. // and the end of the function-definition, member-declarator, or
  354. // declarator.
  355. CXXMethodDecl *Method;
  356. if (FunctionTemplateDecl *FunTmpl
  357. = dyn_cast<FunctionTemplateDecl>(LM.Method))
  358. Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
  359. else
  360. Method = cast<CXXMethodDecl>(LM.Method);
  361. Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
  362. Method->getMethodQualifiers(),
  363. getLangOpts().CPlusPlus11);
  364. // Parse the exception-specification.
  365. SourceRange SpecificationRange;
  366. SmallVector<ParsedType, 4> DynamicExceptions;
  367. SmallVector<SourceRange, 4> DynamicExceptionRanges;
  368. ExprResult NoexceptExpr;
  369. CachedTokens *ExceptionSpecTokens;
  370. ExceptionSpecificationType EST
  371. = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
  372. DynamicExceptions,
  373. DynamicExceptionRanges, NoexceptExpr,
  374. ExceptionSpecTokens);
  375. if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
  376. Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
  377. // Attach the exception-specification to the method.
  378. Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
  379. SpecificationRange,
  380. DynamicExceptions,
  381. DynamicExceptionRanges,
  382. NoexceptExpr.isUsable()?
  383. NoexceptExpr.get() : nullptr);
  384. // There could be leftover tokens (e.g. because of an error).
  385. // Skip through until we reach the original token position.
  386. while (Tok.isNot(tok::eof))
  387. ConsumeAnyToken();
  388. // Clean up the remaining EOF token.
  389. if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
  390. ConsumeAnyToken();
  391. delete Toks;
  392. LM.ExceptionSpecTokens = nullptr;
  393. }
  394. PrototypeScope.Exit();
  395. // Finish the delayed C++ method declaration.
  396. Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
  397. }
  398. /// ParseLexedMethodDefs - We finished parsing the member specification of a top
  399. /// (non-nested) C++ class. Now go over the stack of lexed methods that were
  400. /// collected during its parsing and parse them all.
  401. void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
  402. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  403. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
  404. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  405. if (HasTemplateScope) {
  406. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  407. ++CurTemplateDepthTracker;
  408. }
  409. bool HasClassScope = !Class.TopLevelClass;
  410. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
  411. HasClassScope);
  412. for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
  413. Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
  414. }
  415. }
  416. void Parser::ParseLexedMethodDef(LexedMethod &LM) {
  417. // If this is a member template, introduce the template parameter scope.
  418. ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
  419. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  420. if (LM.TemplateScope) {
  421. Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
  422. ++CurTemplateDepthTracker;
  423. }
  424. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  425. assert(!LM.Toks.empty() && "Empty body!");
  426. Token LastBodyToken = LM.Toks.back();
  427. Token BodyEnd;
  428. BodyEnd.startToken();
  429. BodyEnd.setKind(tok::eof);
  430. BodyEnd.setLocation(LastBodyToken.getEndLoc());
  431. BodyEnd.setEofData(LM.D);
  432. LM.Toks.push_back(BodyEnd);
  433. // Append the current token at the end of the new token stream so that it
  434. // doesn't get lost.
  435. LM.Toks.push_back(Tok);
  436. PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
  437. // Consume the previously pushed token.
  438. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  439. assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
  440. && "Inline method not starting with '{', ':' or 'try'");
  441. // Parse the method body. Function body parsing code is similar enough
  442. // to be re-used for method bodies as well.
  443. ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
  444. Scope::CompoundStmtScope);
  445. Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
  446. if (Tok.is(tok::kw_try)) {
  447. ParseFunctionTryBlock(LM.D, FnScope);
  448. while (Tok.isNot(tok::eof))
  449. ConsumeAnyToken();
  450. if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
  451. ConsumeAnyToken();
  452. return;
  453. }
  454. if (Tok.is(tok::colon)) {
  455. ParseConstructorInitializer(LM.D);
  456. // Error recovery.
  457. if (!Tok.is(tok::l_brace)) {
  458. FnScope.Exit();
  459. Actions.ActOnFinishFunctionBody(LM.D, nullptr);
  460. while (Tok.isNot(tok::eof))
  461. ConsumeAnyToken();
  462. if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
  463. ConsumeAnyToken();
  464. return;
  465. }
  466. } else
  467. Actions.ActOnDefaultCtorInitializers(LM.D);
  468. assert((Actions.getDiagnostics().hasErrorOccurred() ||
  469. !isa<FunctionTemplateDecl>(LM.D) ||
  470. cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
  471. < TemplateParameterDepth) &&
  472. "TemplateParameterDepth should be greater than the depth of "
  473. "current template being instantiated!");
  474. ParseFunctionStatementBody(LM.D, FnScope);
  475. while (Tok.isNot(tok::eof))
  476. ConsumeAnyToken();
  477. if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
  478. ConsumeAnyToken();
  479. if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
  480. if (isa<CXXMethodDecl>(FD) ||
  481. FD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend))
  482. Actions.ActOnFinishInlineFunctionDef(FD);
  483. }
  484. /// ParseLexedMemberInitializers - We finished parsing the member specification
  485. /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
  486. /// initializers that were collected during its parsing and parse them all.
  487. void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
  488. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  489. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
  490. HasTemplateScope);
  491. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  492. if (HasTemplateScope) {
  493. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  494. ++CurTemplateDepthTracker;
  495. }
  496. // Set or update the scope flags.
  497. bool AlreadyHasClassScope = Class.TopLevelClass;
  498. unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
  499. ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
  500. ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
  501. if (!AlreadyHasClassScope)
  502. Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
  503. Class.TagOrTemplate);
  504. if (!Class.LateParsedDeclarations.empty()) {
  505. // C++11 [expr.prim.general]p4:
  506. // Otherwise, if a member-declarator declares a non-static data member
  507. // (9.2) of a class X, the expression this is a prvalue of type "pointer
  508. // to X" within the optional brace-or-equal-initializer. It shall not
  509. // appear elsewhere in the member-declarator.
  510. Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
  511. Qualifiers());
  512. for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
  513. Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
  514. }
  515. }
  516. if (!AlreadyHasClassScope)
  517. Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
  518. Class.TagOrTemplate);
  519. Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
  520. }
  521. void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
  522. if (!MI.Field || MI.Field->isInvalidDecl())
  523. return;
  524. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  525. // Append the current token at the end of the new token stream so that it
  526. // doesn't get lost.
  527. MI.Toks.push_back(Tok);
  528. PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true);
  529. // Consume the previously pushed token.
  530. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  531. SourceLocation EqualLoc;
  532. Actions.ActOnStartCXXInClassMemberInitializer();
  533. ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
  534. EqualLoc);
  535. Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
  536. Init.get());
  537. // The next token should be our artificial terminating EOF token.
  538. if (Tok.isNot(tok::eof)) {
  539. if (!Init.isInvalid()) {
  540. SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
  541. if (!EndLoc.isValid())
  542. EndLoc = Tok.getLocation();
  543. // No fixit; we can't recover as if there were a semicolon here.
  544. Diag(EndLoc, diag::err_expected_semi_decl_list);
  545. }
  546. // Consume tokens until we hit the artificial EOF.
  547. while (Tok.isNot(tok::eof))
  548. ConsumeAnyToken();
  549. }
  550. // Make sure this is *our* artificial EOF token.
  551. if (Tok.getEofData() == MI.Field)
  552. ConsumeAnyToken();
  553. }
  554. /// ConsumeAndStoreUntil - Consume and store the token at the passed token
  555. /// container until the token 'T' is reached (which gets
  556. /// consumed/stored too, if ConsumeFinalToken).
  557. /// If StopAtSemi is true, then we will stop early at a ';' character.
  558. /// Returns true if token 'T1' or 'T2' was found.
  559. /// NOTE: This is a specialized version of Parser::SkipUntil.
  560. bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
  561. CachedTokens &Toks,
  562. bool StopAtSemi, bool ConsumeFinalToken) {
  563. // We always want this function to consume at least one token if the first
  564. // token isn't T and if not at EOF.
  565. bool isFirstTokenConsumed = true;
  566. while (1) {
  567. // If we found one of the tokens, stop and return true.
  568. if (Tok.is(T1) || Tok.is(T2)) {
  569. if (ConsumeFinalToken) {
  570. Toks.push_back(Tok);
  571. ConsumeAnyToken();
  572. }
  573. return true;
  574. }
  575. switch (Tok.getKind()) {
  576. case tok::eof:
  577. case tok::annot_module_begin:
  578. case tok::annot_module_end:
  579. case tok::annot_module_include:
  580. // Ran out of tokens.
  581. return false;
  582. case tok::l_paren:
  583. // Recursively consume properly-nested parens.
  584. Toks.push_back(Tok);
  585. ConsumeParen();
  586. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  587. break;
  588. case tok::l_square:
  589. // Recursively consume properly-nested square brackets.
  590. Toks.push_back(Tok);
  591. ConsumeBracket();
  592. ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
  593. break;
  594. case tok::l_brace:
  595. // Recursively consume properly-nested braces.
  596. Toks.push_back(Tok);
  597. ConsumeBrace();
  598. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  599. break;
  600. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  601. // Since the user wasn't looking for this token (if they were, it would
  602. // already be handled), this isn't balanced. If there is a LHS token at a
  603. // higher level, we will assume that this matches the unbalanced token
  604. // and return it. Otherwise, this is a spurious RHS token, which we skip.
  605. case tok::r_paren:
  606. if (ParenCount && !isFirstTokenConsumed)
  607. return false; // Matches something.
  608. Toks.push_back(Tok);
  609. ConsumeParen();
  610. break;
  611. case tok::r_square:
  612. if (BracketCount && !isFirstTokenConsumed)
  613. return false; // Matches something.
  614. Toks.push_back(Tok);
  615. ConsumeBracket();
  616. break;
  617. case tok::r_brace:
  618. if (BraceCount && !isFirstTokenConsumed)
  619. return false; // Matches something.
  620. Toks.push_back(Tok);
  621. ConsumeBrace();
  622. break;
  623. case tok::semi:
  624. if (StopAtSemi)
  625. return false;
  626. LLVM_FALLTHROUGH;
  627. default:
  628. // consume this token.
  629. Toks.push_back(Tok);
  630. ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
  631. break;
  632. }
  633. isFirstTokenConsumed = false;
  634. }
  635. }
  636. /// Consume tokens and store them in the passed token container until
  637. /// we've passed the try keyword and constructor initializers and have consumed
  638. /// the opening brace of the function body. The opening brace will be consumed
  639. /// if and only if there was no error.
  640. ///
  641. /// \return True on error.
  642. bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
  643. if (Tok.is(tok::kw_try)) {
  644. Toks.push_back(Tok);
  645. ConsumeToken();
  646. }
  647. if (Tok.isNot(tok::colon)) {
  648. // Easy case, just a function body.
  649. // Grab any remaining garbage to be diagnosed later. We stop when we reach a
  650. // brace: an opening one is the function body, while a closing one probably
  651. // means we've reached the end of the class.
  652. ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
  653. /*StopAtSemi=*/true,
  654. /*ConsumeFinalToken=*/false);
  655. if (Tok.isNot(tok::l_brace))
  656. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
  657. Toks.push_back(Tok);
  658. ConsumeBrace();
  659. return false;
  660. }
  661. Toks.push_back(Tok);
  662. ConsumeToken();
  663. // We can't reliably skip over a mem-initializer-id, because it could be
  664. // a template-id involving not-yet-declared names. Given:
  665. //
  666. // S ( ) : a < b < c > ( e )
  667. //
  668. // 'e' might be an initializer or part of a template argument, depending
  669. // on whether 'b' is a template.
  670. // Track whether we might be inside a template argument. We can give
  671. // significantly better diagnostics if we know that we're not.
  672. bool MightBeTemplateArgument = false;
  673. while (true) {
  674. // Skip over the mem-initializer-id, if possible.
  675. if (Tok.is(tok::kw_decltype)) {
  676. Toks.push_back(Tok);
  677. SourceLocation OpenLoc = ConsumeToken();
  678. if (Tok.isNot(tok::l_paren))
  679. return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
  680. << "decltype";
  681. Toks.push_back(Tok);
  682. ConsumeParen();
  683. if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
  684. Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
  685. Diag(OpenLoc, diag::note_matching) << tok::l_paren;
  686. return true;
  687. }
  688. }
  689. do {
  690. // Walk over a component of a nested-name-specifier.
  691. if (Tok.is(tok::coloncolon)) {
  692. Toks.push_back(Tok);
  693. ConsumeToken();
  694. if (Tok.is(tok::kw_template)) {
  695. Toks.push_back(Tok);
  696. ConsumeToken();
  697. }
  698. }
  699. if (Tok.is(tok::identifier)) {
  700. Toks.push_back(Tok);
  701. ConsumeToken();
  702. } else {
  703. break;
  704. }
  705. } while (Tok.is(tok::coloncolon));
  706. if (Tok.is(tok::code_completion)) {
  707. Toks.push_back(Tok);
  708. ConsumeCodeCompletionToken();
  709. if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
  710. // Could be the start of another member initializer (the ',' has not
  711. // been written yet)
  712. continue;
  713. }
  714. }
  715. if (Tok.is(tok::comma)) {
  716. // The initialization is missing, we'll diagnose it later.
  717. Toks.push_back(Tok);
  718. ConsumeToken();
  719. continue;
  720. }
  721. if (Tok.is(tok::less))
  722. MightBeTemplateArgument = true;
  723. if (MightBeTemplateArgument) {
  724. // We may be inside a template argument list. Grab up to the start of the
  725. // next parenthesized initializer or braced-init-list. This *might* be the
  726. // initializer, or it might be a subexpression in the template argument
  727. // list.
  728. // FIXME: Count angle brackets, and clear MightBeTemplateArgument
  729. // if all angles are closed.
  730. if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
  731. /*StopAtSemi=*/true,
  732. /*ConsumeFinalToken=*/false)) {
  733. // We're not just missing the initializer, we're also missing the
  734. // function body!
  735. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
  736. }
  737. } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
  738. // We found something weird in a mem-initializer-id.
  739. if (getLangOpts().CPlusPlus11)
  740. return Diag(Tok.getLocation(), diag::err_expected_either)
  741. << tok::l_paren << tok::l_brace;
  742. else
  743. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
  744. }
  745. tok::TokenKind kind = Tok.getKind();
  746. Toks.push_back(Tok);
  747. bool IsLParen = (kind == tok::l_paren);
  748. SourceLocation OpenLoc = Tok.getLocation();
  749. if (IsLParen) {
  750. ConsumeParen();
  751. } else {
  752. assert(kind == tok::l_brace && "Must be left paren or brace here.");
  753. ConsumeBrace();
  754. // In C++03, this has to be the start of the function body, which
  755. // means the initializer is malformed; we'll diagnose it later.
  756. if (!getLangOpts().CPlusPlus11)
  757. return false;
  758. const Token &PreviousToken = Toks[Toks.size() - 2];
  759. if (!MightBeTemplateArgument &&
  760. !PreviousToken.isOneOf(tok::identifier, tok::greater,
  761. tok::greatergreater)) {
  762. // If the opening brace is not preceded by one of these tokens, we are
  763. // missing the mem-initializer-id. In order to recover better, we need
  764. // to use heuristics to determine if this '{' is most likely the
  765. // beginning of a brace-init-list or the function body.
  766. // Check the token after the corresponding '}'.
  767. TentativeParsingAction PA(*this);
  768. if (SkipUntil(tok::r_brace) &&
  769. !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
  770. // Consider there was a malformed initializer and this is the start
  771. // of the function body. We'll diagnose it later.
  772. PA.Revert();
  773. return false;
  774. }
  775. PA.Revert();
  776. }
  777. }
  778. // Grab the initializer (or the subexpression of the template argument).
  779. // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
  780. // if we might be inside the braces of a lambda-expression.
  781. tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
  782. if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
  783. Diag(Tok, diag::err_expected) << CloseKind;
  784. Diag(OpenLoc, diag::note_matching) << kind;
  785. return true;
  786. }
  787. // Grab pack ellipsis, if present.
  788. if (Tok.is(tok::ellipsis)) {
  789. Toks.push_back(Tok);
  790. ConsumeToken();
  791. }
  792. // If we know we just consumed a mem-initializer, we must have ',' or '{'
  793. // next.
  794. if (Tok.is(tok::comma)) {
  795. Toks.push_back(Tok);
  796. ConsumeToken();
  797. } else if (Tok.is(tok::l_brace)) {
  798. // This is the function body if the ')' or '}' is immediately followed by
  799. // a '{'. That cannot happen within a template argument, apart from the
  800. // case where a template argument contains a compound literal:
  801. //
  802. // S ( ) : a < b < c > ( d ) { }
  803. // // End of declaration, or still inside the template argument?
  804. //
  805. // ... and the case where the template argument contains a lambda:
  806. //
  807. // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
  808. // ( ) > ( ) { }
  809. //
  810. // FIXME: Disambiguate these cases. Note that the latter case is probably
  811. // going to be made ill-formed by core issue 1607.
  812. Toks.push_back(Tok);
  813. ConsumeBrace();
  814. return false;
  815. } else if (!MightBeTemplateArgument) {
  816. return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
  817. << tok::comma;
  818. }
  819. }
  820. }
  821. /// Consume and store tokens from the '?' to the ':' in a conditional
  822. /// expression.
  823. bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
  824. // Consume '?'.
  825. assert(Tok.is(tok::question));
  826. Toks.push_back(Tok);
  827. ConsumeToken();
  828. while (Tok.isNot(tok::colon)) {
  829. if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
  830. /*StopAtSemi=*/true,
  831. /*ConsumeFinalToken=*/false))
  832. return false;
  833. // If we found a nested conditional, consume it.
  834. if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
  835. return false;
  836. }
  837. // Consume ':'.
  838. Toks.push_back(Tok);
  839. ConsumeToken();
  840. return true;
  841. }
  842. /// A tentative parsing action that can also revert token annotations.
  843. class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
  844. public:
  845. explicit UnannotatedTentativeParsingAction(Parser &Self,
  846. tok::TokenKind EndKind)
  847. : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
  848. // Stash away the old token stream, so we can restore it once the
  849. // tentative parse is complete.
  850. TentativeParsingAction Inner(Self);
  851. Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
  852. Inner.Revert();
  853. }
  854. void RevertAnnotations() {
  855. Revert();
  856. // Put back the original tokens.
  857. Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
  858. if (Toks.size()) {
  859. auto Buffer = std::make_unique<Token[]>(Toks.size());
  860. std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
  861. Buffer[Toks.size() - 1] = Self.Tok;
  862. Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true,
  863. /*IsReinject*/ true);
  864. Self.Tok = Toks.front();
  865. }
  866. }
  867. private:
  868. Parser &Self;
  869. CachedTokens Toks;
  870. tok::TokenKind EndKind;
  871. };
  872. /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
  873. /// container until the end of the current initializer expression (either a
  874. /// default argument or an in-class initializer for a non-static data member).
  875. ///
  876. /// Returns \c true if we reached the end of something initializer-shaped,
  877. /// \c false if we bailed out.
  878. bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
  879. CachedInitKind CIK) {
  880. // We always want this function to consume at least one token if not at EOF.
  881. bool IsFirstToken = true;
  882. // Number of possible unclosed <s we've seen so far. These might be templates,
  883. // and might not, but if there were none of them (or we know for sure that
  884. // we're within a template), we can avoid a tentative parse.
  885. unsigned AngleCount = 0;
  886. unsigned KnownTemplateCount = 0;
  887. while (1) {
  888. switch (Tok.getKind()) {
  889. case tok::comma:
  890. // If we might be in a template, perform a tentative parse to check.
  891. if (!AngleCount)
  892. // Not a template argument: this is the end of the initializer.
  893. return true;
  894. if (KnownTemplateCount)
  895. goto consume_token;
  896. // We hit a comma inside angle brackets. This is the hard case. The
  897. // rule we follow is:
  898. // * For a default argument, if the tokens after the comma form a
  899. // syntactically-valid parameter-declaration-clause, in which each
  900. // parameter has an initializer, then this comma ends the default
  901. // argument.
  902. // * For a default initializer, if the tokens after the comma form a
  903. // syntactically-valid init-declarator-list, then this comma ends
  904. // the default initializer.
  905. {
  906. UnannotatedTentativeParsingAction PA(*this,
  907. CIK == CIK_DefaultInitializer
  908. ? tok::semi : tok::r_paren);
  909. Sema::TentativeAnalysisScope Scope(Actions);
  910. TPResult Result = TPResult::Error;
  911. ConsumeToken();
  912. switch (CIK) {
  913. case CIK_DefaultInitializer:
  914. Result = TryParseInitDeclaratorList();
  915. // If we parsed a complete, ambiguous init-declarator-list, this
  916. // is only syntactically-valid if it's followed by a semicolon.
  917. if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
  918. Result = TPResult::False;
  919. break;
  920. case CIK_DefaultArgument:
  921. bool InvalidAsDeclaration = false;
  922. Result = TryParseParameterDeclarationClause(
  923. &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
  924. // If this is an expression or a declaration with a missing
  925. // 'typename', assume it's not a declaration.
  926. if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
  927. Result = TPResult::False;
  928. break;
  929. }
  930. // If what follows could be a declaration, it is a declaration.
  931. if (Result != TPResult::False && Result != TPResult::Error) {
  932. PA.Revert();
  933. return true;
  934. }
  935. // In the uncommon case that we decide the following tokens are part
  936. // of a template argument, revert any annotations we've performed in
  937. // those tokens. We're not going to look them up until we've parsed
  938. // the rest of the class, and that might add more declarations.
  939. PA.RevertAnnotations();
  940. }
  941. // Keep going. We know we're inside a template argument list now.
  942. ++KnownTemplateCount;
  943. goto consume_token;
  944. case tok::eof:
  945. case tok::annot_module_begin:
  946. case tok::annot_module_end:
  947. case tok::annot_module_include:
  948. // Ran out of tokens.
  949. return false;
  950. case tok::less:
  951. // FIXME: A '<' can only start a template-id if it's preceded by an
  952. // identifier, an operator-function-id, or a literal-operator-id.
  953. ++AngleCount;
  954. goto consume_token;
  955. case tok::question:
  956. // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
  957. // that is *never* the end of the initializer. Skip to the ':'.
  958. if (!ConsumeAndStoreConditional(Toks))
  959. return false;
  960. break;
  961. case tok::greatergreatergreater:
  962. if (!getLangOpts().CPlusPlus11)
  963. goto consume_token;
  964. if (AngleCount) --AngleCount;
  965. if (KnownTemplateCount) --KnownTemplateCount;
  966. LLVM_FALLTHROUGH;
  967. case tok::greatergreater:
  968. if (!getLangOpts().CPlusPlus11)
  969. goto consume_token;
  970. if (AngleCount) --AngleCount;
  971. if (KnownTemplateCount) --KnownTemplateCount;
  972. LLVM_FALLTHROUGH;
  973. case tok::greater:
  974. if (AngleCount) --AngleCount;
  975. if (KnownTemplateCount) --KnownTemplateCount;
  976. goto consume_token;
  977. case tok::kw_template:
  978. // 'template' identifier '<' is known to start a template argument list,
  979. // and can be used to disambiguate the parse.
  980. // FIXME: Support all forms of 'template' unqualified-id '<'.
  981. Toks.push_back(Tok);
  982. ConsumeToken();
  983. if (Tok.is(tok::identifier)) {
  984. Toks.push_back(Tok);
  985. ConsumeToken();
  986. if (Tok.is(tok::less)) {
  987. ++AngleCount;
  988. ++KnownTemplateCount;
  989. Toks.push_back(Tok);
  990. ConsumeToken();
  991. }
  992. }
  993. break;
  994. case tok::kw_operator:
  995. // If 'operator' precedes other punctuation, that punctuation loses
  996. // its special behavior.
  997. Toks.push_back(Tok);
  998. ConsumeToken();
  999. switch (Tok.getKind()) {
  1000. case tok::comma:
  1001. case tok::greatergreatergreater:
  1002. case tok::greatergreater:
  1003. case tok::greater:
  1004. case tok::less:
  1005. Toks.push_back(Tok);
  1006. ConsumeToken();
  1007. break;
  1008. default:
  1009. break;
  1010. }
  1011. break;
  1012. case tok::l_paren:
  1013. // Recursively consume properly-nested parens.
  1014. Toks.push_back(Tok);
  1015. ConsumeParen();
  1016. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  1017. break;
  1018. case tok::l_square:
  1019. // Recursively consume properly-nested square brackets.
  1020. Toks.push_back(Tok);
  1021. ConsumeBracket();
  1022. ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
  1023. break;
  1024. case tok::l_brace:
  1025. // Recursively consume properly-nested braces.
  1026. Toks.push_back(Tok);
  1027. ConsumeBrace();
  1028. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1029. break;
  1030. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  1031. // Since the user wasn't looking for this token (if they were, it would
  1032. // already be handled), this isn't balanced. If there is a LHS token at a
  1033. // higher level, we will assume that this matches the unbalanced token
  1034. // and return it. Otherwise, this is a spurious RHS token, which we
  1035. // consume and pass on to downstream code to diagnose.
  1036. case tok::r_paren:
  1037. if (CIK == CIK_DefaultArgument)
  1038. return true; // End of the default argument.
  1039. if (ParenCount && !IsFirstToken)
  1040. return false;
  1041. Toks.push_back(Tok);
  1042. ConsumeParen();
  1043. continue;
  1044. case tok::r_square:
  1045. if (BracketCount && !IsFirstToken)
  1046. return false;
  1047. Toks.push_back(Tok);
  1048. ConsumeBracket();
  1049. continue;
  1050. case tok::r_brace:
  1051. if (BraceCount && !IsFirstToken)
  1052. return false;
  1053. Toks.push_back(Tok);
  1054. ConsumeBrace();
  1055. continue;
  1056. case tok::code_completion:
  1057. Toks.push_back(Tok);
  1058. ConsumeCodeCompletionToken();
  1059. break;
  1060. case tok::string_literal:
  1061. case tok::wide_string_literal:
  1062. case tok::utf8_string_literal:
  1063. case tok::utf16_string_literal:
  1064. case tok::utf32_string_literal:
  1065. Toks.push_back(Tok);
  1066. ConsumeStringToken();
  1067. break;
  1068. case tok::semi:
  1069. if (CIK == CIK_DefaultInitializer)
  1070. return true; // End of the default initializer.
  1071. LLVM_FALLTHROUGH;
  1072. default:
  1073. consume_token:
  1074. Toks.push_back(Tok);
  1075. ConsumeToken();
  1076. break;
  1077. }
  1078. IsFirstToken = false;
  1079. }
  1080. }