ParseCXXInlineMethods.cpp 45 KB

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