ParseCXXInlineMethods.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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() == FunctionDefinitionKind::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. CachedTokens &Toks = LM->Toks;
  120. tok::TokenKind kind = Tok.getKind();
  121. // Consume everything up to (and including) the left brace of the
  122. // function body.
  123. if (ConsumeAndStoreFunctionPrologue(Toks)) {
  124. // We didn't find the left-brace we expected after the
  125. // constructor initializer.
  126. // If we're code-completing and the completion point was in the broken
  127. // initializer, we want to parse it even though that will fail.
  128. if (PP.isCodeCompletionEnabled() &&
  129. llvm::any_of(Toks, [](const Token &Tok) {
  130. return Tok.is(tok::code_completion);
  131. })) {
  132. // If we gave up at the completion point, the initializer list was
  133. // likely truncated, so don't eat more tokens. We'll hit some extra
  134. // errors, but they should be ignored in code completion.
  135. return FnD;
  136. }
  137. // We already printed an error, and it's likely impossible to recover,
  138. // so don't try to parse this method later.
  139. // Skip over the rest of the decl and back to somewhere that looks
  140. // reasonable.
  141. SkipMalformedDecl();
  142. delete getCurrentClass().LateParsedDeclarations.back();
  143. getCurrentClass().LateParsedDeclarations.pop_back();
  144. return FnD;
  145. } else {
  146. // Consume everything up to (and including) the matching right brace.
  147. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  148. }
  149. // If we're in a function-try-block, we need to store all the catch blocks.
  150. if (kind == tok::kw_try) {
  151. while (Tok.is(tok::kw_catch)) {
  152. ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
  153. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  154. }
  155. }
  156. if (FnD) {
  157. FunctionDecl *FD = FnD->getAsFunction();
  158. // Track that this function will eventually have a body; Sema needs
  159. // to know this.
  160. Actions.CheckForFunctionRedefinition(FD);
  161. FD->setWillHaveBody(true);
  162. } else {
  163. // If semantic analysis could not build a function declaration,
  164. // just throw away the late-parsed declaration.
  165. delete getCurrentClass().LateParsedDeclarations.back();
  166. getCurrentClass().LateParsedDeclarations.pop_back();
  167. }
  168. return FnD;
  169. }
  170. /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
  171. /// specified Declarator is a well formed C++ non-static data member
  172. /// declaration. Now lex its initializer and store its tokens for parsing
  173. /// after the class is complete.
  174. void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
  175. assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
  176. "Current token not a '{' or '='!");
  177. LateParsedMemberInitializer *MI =
  178. new LateParsedMemberInitializer(this, VarD);
  179. getCurrentClass().LateParsedDeclarations.push_back(MI);
  180. CachedTokens &Toks = MI->Toks;
  181. tok::TokenKind kind = Tok.getKind();
  182. if (kind == tok::equal) {
  183. Toks.push_back(Tok);
  184. ConsumeToken();
  185. }
  186. if (kind == tok::l_brace) {
  187. // Begin by storing the '{' token.
  188. Toks.push_back(Tok);
  189. ConsumeBrace();
  190. // Consume everything up to (and including) the matching right brace.
  191. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
  192. } else {
  193. // Consume everything up to (but excluding) the comma or semicolon.
  194. ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
  195. }
  196. // Store an artificial EOF token to ensure that we don't run off the end of
  197. // the initializer when we come to parse it.
  198. Token Eof;
  199. Eof.startToken();
  200. Eof.setKind(tok::eof);
  201. Eof.setLocation(Tok.getLocation());
  202. Eof.setEofData(VarD);
  203. Toks.push_back(Eof);
  204. }
  205. Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
  206. void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
  207. void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
  208. void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
  209. void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
  210. void Parser::LateParsedDeclaration::ParseLexedPragmas() {}
  211. Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
  212. : Self(P), Class(C) {}
  213. Parser::LateParsedClass::~LateParsedClass() {
  214. Self->DeallocateParsedClasses(Class);
  215. }
  216. void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
  217. Self->ParseLexedMethodDeclarations(*Class);
  218. }
  219. void Parser::LateParsedClass::ParseLexedMemberInitializers() {
  220. Self->ParseLexedMemberInitializers(*Class);
  221. }
  222. void Parser::LateParsedClass::ParseLexedMethodDefs() {
  223. Self->ParseLexedMethodDefs(*Class);
  224. }
  225. void Parser::LateParsedClass::ParseLexedAttributes() {
  226. Self->ParseLexedAttributes(*Class);
  227. }
  228. void Parser::LateParsedClass::ParseLexedPragmas() {
  229. Self->ParseLexedPragmas(*Class);
  230. }
  231. void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
  232. Self->ParseLexedMethodDeclaration(*this);
  233. }
  234. void Parser::LexedMethod::ParseLexedMethodDefs() {
  235. Self->ParseLexedMethodDef(*this);
  236. }
  237. void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
  238. Self->ParseLexedMemberInitializer(*this);
  239. }
  240. void Parser::LateParsedAttribute::ParseLexedAttributes() {
  241. Self->ParseLexedAttribute(*this, true, false);
  242. }
  243. void Parser::LateParsedPragma::ParseLexedPragmas() {
  244. Self->ParseLexedPragma(*this);
  245. }
  246. /// Utility to re-enter a possibly-templated scope while parsing its
  247. /// late-parsed components.
  248. struct Parser::ReenterTemplateScopeRAII {
  249. Parser &P;
  250. MultiParseScope Scopes;
  251. TemplateParameterDepthRAII CurTemplateDepthTracker;
  252. ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true)
  253. : P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) {
  254. if (Enter) {
  255. CurTemplateDepthTracker.addDepth(
  256. P.ReenterTemplateScopes(Scopes, MaybeTemplated));
  257. }
  258. }
  259. };
  260. /// Utility to re-enter a class scope while parsing its late-parsed components.
  261. struct Parser::ReenterClassScopeRAII : ReenterTemplateScopeRAII {
  262. ParsingClass &Class;
  263. ReenterClassScopeRAII(Parser &P, ParsingClass &Class)
  264. : ReenterTemplateScopeRAII(P, Class.TagOrTemplate,
  265. /*Enter=*/!Class.TopLevelClass),
  266. Class(Class) {
  267. // If this is the top-level class, we're still within its scope.
  268. if (Class.TopLevelClass)
  269. return;
  270. // Re-enter the class scope itself.
  271. Scopes.Enter(Scope::ClassScope|Scope::DeclScope);
  272. P.Actions.ActOnStartDelayedMemberDeclarations(P.getCurScope(),
  273. Class.TagOrTemplate);
  274. }
  275. ~ReenterClassScopeRAII() {
  276. if (Class.TopLevelClass)
  277. return;
  278. P.Actions.ActOnFinishDelayedMemberDeclarations(P.getCurScope(),
  279. Class.TagOrTemplate);
  280. }
  281. };
  282. /// ParseLexedMethodDeclarations - We finished parsing the member
  283. /// specification of a top (non-nested) C++ class. Now go over the
  284. /// stack of method declarations with some parts for which parsing was
  285. /// delayed (such as default arguments) and parse them.
  286. void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
  287. ReenterClassScopeRAII InClassScope(*this, Class);
  288. for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
  289. LateD->ParseLexedMethodDeclarations();
  290. }
  291. void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
  292. // If this is a member template, introduce the template parameter scope.
  293. ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method);
  294. // Start the delayed C++ method declaration
  295. Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
  296. // Introduce the parameters into scope and parse their default
  297. // arguments.
  298. InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope |
  299. Scope::FunctionDeclarationScope |
  300. Scope::DeclScope);
  301. for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
  302. auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
  303. // Introduce the parameter into scope.
  304. bool HasUnparsed = Param->hasUnparsedDefaultArg();
  305. Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
  306. std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
  307. if (Toks) {
  308. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  309. // Mark the end of the default argument so that we know when to stop when
  310. // we parse it later on.
  311. Token LastDefaultArgToken = Toks->back();
  312. Token DefArgEnd;
  313. DefArgEnd.startToken();
  314. DefArgEnd.setKind(tok::eof);
  315. DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
  316. DefArgEnd.setEofData(Param);
  317. Toks->push_back(DefArgEnd);
  318. // Parse the default argument from its saved token stream.
  319. Toks->push_back(Tok); // So that the current token doesn't get lost
  320. PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true);
  321. // Consume the previously-pushed token.
  322. ConsumeAnyToken();
  323. // Consume the '='.
  324. assert(Tok.is(tok::equal) && "Default argument not starting with '='");
  325. SourceLocation EqualLoc = ConsumeToken();
  326. // The argument isn't actually potentially evaluated unless it is
  327. // used.
  328. EnterExpressionEvaluationContext Eval(
  329. Actions,
  330. Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, Param);
  331. ExprResult DefArgResult;
  332. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  333. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  334. DefArgResult = ParseBraceInitializer();
  335. } else
  336. DefArgResult = ParseAssignmentExpression();
  337. DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
  338. if (DefArgResult.isInvalid()) {
  339. Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
  340. } else {
  341. if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
  342. // The last two tokens are the terminator and the saved value of
  343. // Tok; the last token in the default argument is the one before
  344. // those.
  345. assert(Toks->size() >= 3 && "expected a token in default arg");
  346. Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
  347. << SourceRange(Tok.getLocation(),
  348. (*Toks)[Toks->size() - 3].getLocation());
  349. }
  350. Actions.ActOnParamDefaultArgument(Param, EqualLoc,
  351. DefArgResult.get());
  352. }
  353. // There could be leftover tokens (e.g. because of an error).
  354. // Skip through until we reach the 'end of default argument' token.
  355. while (Tok.isNot(tok::eof))
  356. ConsumeAnyToken();
  357. if (Tok.is(tok::eof) && Tok.getEofData() == Param)
  358. ConsumeAnyToken();
  359. } else if (HasUnparsed) {
  360. assert(Param->hasInheritedDefaultArg());
  361. const FunctionDecl *Old;
  362. if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method))
  363. Old =
  364. cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl();
  365. else
  366. Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
  367. if (Old) {
  368. ParmVarDecl *OldParam = const_cast<ParmVarDecl*>(Old->getParamDecl(I));
  369. assert(!OldParam->hasUnparsedDefaultArg());
  370. if (OldParam->hasUninstantiatedDefaultArg())
  371. Param->setUninstantiatedDefaultArg(
  372. OldParam->getUninstantiatedDefaultArg());
  373. else
  374. Param->setDefaultArg(OldParam->getInit());
  375. }
  376. }
  377. }
  378. // Parse a delayed exception-specification, if there is one.
  379. if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
  380. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  381. // Add the 'stop' token.
  382. Token LastExceptionSpecToken = Toks->back();
  383. Token ExceptionSpecEnd;
  384. ExceptionSpecEnd.startToken();
  385. ExceptionSpecEnd.setKind(tok::eof);
  386. ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
  387. ExceptionSpecEnd.setEofData(LM.Method);
  388. Toks->push_back(ExceptionSpecEnd);
  389. // Parse the default argument from its saved token stream.
  390. Toks->push_back(Tok); // So that the current token doesn't get lost
  391. PP.EnterTokenStream(*Toks, true, /*IsReinject*/true);
  392. // Consume the previously-pushed token.
  393. ConsumeAnyToken();
  394. // C++11 [expr.prim.general]p3:
  395. // If a declaration declares a member function or member function
  396. // template of a class X, the expression this is a prvalue of type
  397. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  398. // and the end of the function-definition, member-declarator, or
  399. // declarator.
  400. CXXMethodDecl *Method;
  401. if (FunctionTemplateDecl *FunTmpl
  402. = dyn_cast<FunctionTemplateDecl>(LM.Method))
  403. Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
  404. else
  405. Method = dyn_cast<CXXMethodDecl>(LM.Method);
  406. Sema::CXXThisScopeRAII ThisScope(
  407. Actions, Method ? Method->getParent() : nullptr,
  408. Method ? Method->getMethodQualifiers() : Qualifiers{},
  409. Method && getLangOpts().CPlusPlus11);
  410. // Parse the exception-specification.
  411. SourceRange SpecificationRange;
  412. SmallVector<ParsedType, 4> DynamicExceptions;
  413. SmallVector<SourceRange, 4> DynamicExceptionRanges;
  414. ExprResult NoexceptExpr;
  415. CachedTokens *ExceptionSpecTokens;
  416. ExceptionSpecificationType EST
  417. = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
  418. DynamicExceptions,
  419. DynamicExceptionRanges, NoexceptExpr,
  420. ExceptionSpecTokens);
  421. if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
  422. Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
  423. // Attach the exception-specification to the method.
  424. Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
  425. SpecificationRange,
  426. DynamicExceptions,
  427. DynamicExceptionRanges,
  428. NoexceptExpr.isUsable()?
  429. NoexceptExpr.get() : nullptr);
  430. // There could be leftover tokens (e.g. because of an error).
  431. // Skip through until we reach the original token position.
  432. while (Tok.isNot(tok::eof))
  433. ConsumeAnyToken();
  434. // Clean up the remaining EOF token.
  435. if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
  436. ConsumeAnyToken();
  437. delete Toks;
  438. LM.ExceptionSpecTokens = nullptr;
  439. }
  440. InFunctionTemplateScope.Scopes.Exit();
  441. // Finish the delayed C++ method declaration.
  442. Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
  443. }
  444. /// ParseLexedMethodDefs - We finished parsing the member specification of a top
  445. /// (non-nested) C++ class. Now go over the stack of lexed methods that were
  446. /// collected during its parsing and parse them all.
  447. void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
  448. ReenterClassScopeRAII InClassScope(*this, Class);
  449. for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
  450. D->ParseLexedMethodDefs();
  451. }
  452. void Parser::ParseLexedMethodDef(LexedMethod &LM) {
  453. // If this is a member template, introduce the template parameter scope.
  454. ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D);
  455. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  456. assert(!LM.Toks.empty() && "Empty body!");
  457. Token LastBodyToken = LM.Toks.back();
  458. Token BodyEnd;
  459. BodyEnd.startToken();
  460. BodyEnd.setKind(tok::eof);
  461. BodyEnd.setLocation(LastBodyToken.getEndLoc());
  462. BodyEnd.setEofData(LM.D);
  463. LM.Toks.push_back(BodyEnd);
  464. // Append the current token at the end of the new token stream so that it
  465. // doesn't get lost.
  466. LM.Toks.push_back(Tok);
  467. PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
  468. // Consume the previously pushed token.
  469. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  470. assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
  471. && "Inline method not starting with '{', ':' or 'try'");
  472. // Parse the method body. Function body parsing code is similar enough
  473. // to be re-used for method bodies as well.
  474. ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
  475. Scope::CompoundStmtScope);
  476. Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
  477. if (Tok.is(tok::kw_try)) {
  478. ParseFunctionTryBlock(LM.D, FnScope);
  479. while (Tok.isNot(tok::eof))
  480. ConsumeAnyToken();
  481. if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
  482. ConsumeAnyToken();
  483. return;
  484. }
  485. if (Tok.is(tok::colon)) {
  486. ParseConstructorInitializer(LM.D);
  487. // Error recovery.
  488. if (!Tok.is(tok::l_brace)) {
  489. FnScope.Exit();
  490. Actions.ActOnFinishFunctionBody(LM.D, nullptr);
  491. while (Tok.isNot(tok::eof))
  492. ConsumeAnyToken();
  493. if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
  494. ConsumeAnyToken();
  495. return;
  496. }
  497. } else
  498. Actions.ActOnDefaultCtorInitializers(LM.D);
  499. assert((Actions.getDiagnostics().hasErrorOccurred() ||
  500. !isa<FunctionTemplateDecl>(LM.D) ||
  501. cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
  502. < TemplateParameterDepth) &&
  503. "TemplateParameterDepth should be greater than the depth of "
  504. "current template being instantiated!");
  505. ParseFunctionStatementBody(LM.D, FnScope);
  506. while (Tok.isNot(tok::eof))
  507. ConsumeAnyToken();
  508. if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
  509. ConsumeAnyToken();
  510. if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
  511. if (isa<CXXMethodDecl>(FD) ||
  512. FD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend))
  513. Actions.ActOnFinishInlineFunctionDef(FD);
  514. }
  515. /// ParseLexedMemberInitializers - We finished parsing the member specification
  516. /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
  517. /// initializers that were collected during its parsing and parse them all.
  518. void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
  519. ReenterClassScopeRAII InClassScope(*this, Class);
  520. if (!Class.LateParsedDeclarations.empty()) {
  521. // C++11 [expr.prim.general]p4:
  522. // Otherwise, if a member-declarator declares a non-static data member
  523. // (9.2) of a class X, the expression this is a prvalue of type "pointer
  524. // to X" within the optional brace-or-equal-initializer. It shall not
  525. // appear elsewhere in the member-declarator.
  526. // FIXME: This should be done in ParseLexedMemberInitializer, not here.
  527. Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
  528. Qualifiers());
  529. for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
  530. D->ParseLexedMemberInitializers();
  531. }
  532. Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
  533. }
  534. void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
  535. if (!MI.Field || MI.Field->isInvalidDecl())
  536. return;
  537. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  538. // Append the current token at the end of the new token stream so that it
  539. // doesn't get lost.
  540. MI.Toks.push_back(Tok);
  541. PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true);
  542. // Consume the previously pushed token.
  543. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  544. SourceLocation EqualLoc;
  545. Actions.ActOnStartCXXInClassMemberInitializer();
  546. ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
  547. EqualLoc);
  548. Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
  549. Init.get());
  550. // The next token should be our artificial terminating EOF token.
  551. if (Tok.isNot(tok::eof)) {
  552. if (!Init.isInvalid()) {
  553. SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
  554. if (!EndLoc.isValid())
  555. EndLoc = Tok.getLocation();
  556. // No fixit; we can't recover as if there were a semicolon here.
  557. Diag(EndLoc, diag::err_expected_semi_decl_list);
  558. }
  559. // Consume tokens until we hit the artificial EOF.
  560. while (Tok.isNot(tok::eof))
  561. ConsumeAnyToken();
  562. }
  563. // Make sure this is *our* artificial EOF token.
  564. if (Tok.getEofData() == MI.Field)
  565. ConsumeAnyToken();
  566. }
  567. /// Wrapper class which calls ParseLexedAttribute, after setting up the
  568. /// scope appropriately.
  569. void Parser::ParseLexedAttributes(ParsingClass &Class) {
  570. ReenterClassScopeRAII InClassScope(*this, Class);
  571. for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
  572. LateD->ParseLexedAttributes();
  573. }
  574. /// Parse all attributes in LAs, and attach them to Decl D.
  575. void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
  576. bool EnterScope, bool OnDefinition) {
  577. assert(LAs.parseSoon() &&
  578. "Attribute list should be marked for immediate parsing.");
  579. for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
  580. if (D)
  581. LAs[i]->addDecl(D);
  582. ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
  583. delete LAs[i];
  584. }
  585. LAs.clear();
  586. }
  587. /// Finish parsing an attribute for which parsing was delayed.
  588. /// This will be called at the end of parsing a class declaration
  589. /// for each LateParsedAttribute. We consume the saved tokens and
  590. /// create an attribute with the arguments filled in. We add this
  591. /// to the Attribute list for the decl.
  592. void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
  593. bool EnterScope, bool OnDefinition) {
  594. // Create a fake EOF so that attribute parsing won't go off the end of the
  595. // attribute.
  596. Token AttrEnd;
  597. AttrEnd.startToken();
  598. AttrEnd.setKind(tok::eof);
  599. AttrEnd.setLocation(Tok.getLocation());
  600. AttrEnd.setEofData(LA.Toks.data());
  601. LA.Toks.push_back(AttrEnd);
  602. // Append the current token at the end of the new token stream so that it
  603. // doesn't get lost.
  604. LA.Toks.push_back(Tok);
  605. PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
  606. // Consume the previously pushed token.
  607. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  608. ParsedAttributes Attrs(AttrFactory);
  609. SourceLocation endLoc;
  610. if (LA.Decls.size() > 0) {
  611. Decl *D = LA.Decls[0];
  612. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  613. RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
  614. // Allow 'this' within late-parsed attributes.
  615. Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
  616. ND && ND->isCXXInstanceMember());
  617. if (LA.Decls.size() == 1) {
  618. // If the Decl is templatized, add template parameters to scope.
  619. ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope);
  620. // If the Decl is on a function, add function parameters to the scope.
  621. bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
  622. if (HasFunScope) {
  623. InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
  624. Scope::CompoundStmtScope);
  625. Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
  626. }
  627. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
  628. nullptr, SourceLocation(), ParsedAttr::AS_GNU,
  629. nullptr);
  630. if (HasFunScope)
  631. Actions.ActOnExitFunctionContext();
  632. } else {
  633. // If there are multiple decls, then the decl cannot be within the
  634. // function scope.
  635. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
  636. nullptr, SourceLocation(), ParsedAttr::AS_GNU,
  637. nullptr);
  638. }
  639. } else {
  640. Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
  641. }
  642. if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
  643. Attrs.begin()->isKnownToGCC())
  644. Diag(Tok, diag::warn_attribute_on_function_definition)
  645. << &LA.AttrName;
  646. for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
  647. Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
  648. // Due to a parsing error, we either went over the cached tokens or
  649. // there are still cached tokens left, so we skip the leftover tokens.
  650. while (Tok.isNot(tok::eof))
  651. ConsumeAnyToken();
  652. if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
  653. ConsumeAnyToken();
  654. }
  655. void Parser::ParseLexedPragmas(ParsingClass &Class) {
  656. ReenterClassScopeRAII InClassScope(*this, Class);
  657. for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
  658. D->ParseLexedPragmas();
  659. }
  660. void Parser::ParseLexedPragma(LateParsedPragma &LP) {
  661. PP.EnterToken(Tok, /*IsReinject=*/true);
  662. PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true,
  663. /*IsReinject=*/true);
  664. // Consume the previously pushed token.
  665. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  666. assert(Tok.isAnnotation() && "Expected annotation token.");
  667. switch (Tok.getKind()) {
  668. case tok::annot_attr_openmp:
  669. case tok::annot_pragma_openmp: {
  670. AccessSpecifier AS = LP.getAccessSpecifier();
  671. ParsedAttributesWithRange Attrs(AttrFactory);
  672. (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
  673. break;
  674. }
  675. default:
  676. llvm_unreachable("Unexpected token.");
  677. }
  678. }
  679. /// ConsumeAndStoreUntil - Consume and store the token at the passed token
  680. /// container until the token 'T' is reached (which gets
  681. /// consumed/stored too, if ConsumeFinalToken).
  682. /// If StopAtSemi is true, then we will stop early at a ';' character.
  683. /// Returns true if token 'T1' or 'T2' was found.
  684. /// NOTE: This is a specialized version of Parser::SkipUntil.
  685. bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
  686. CachedTokens &Toks,
  687. bool StopAtSemi, bool ConsumeFinalToken) {
  688. // We always want this function to consume at least one token if the first
  689. // token isn't T and if not at EOF.
  690. bool isFirstTokenConsumed = true;
  691. while (true) {
  692. // If we found one of the tokens, stop and return true.
  693. if (Tok.is(T1) || Tok.is(T2)) {
  694. if (ConsumeFinalToken) {
  695. Toks.push_back(Tok);
  696. ConsumeAnyToken();
  697. }
  698. return true;
  699. }
  700. switch (Tok.getKind()) {
  701. case tok::eof:
  702. case tok::annot_module_begin:
  703. case tok::annot_module_end:
  704. case tok::annot_module_include:
  705. // Ran out of tokens.
  706. return false;
  707. case tok::l_paren:
  708. // Recursively consume properly-nested parens.
  709. Toks.push_back(Tok);
  710. ConsumeParen();
  711. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  712. break;
  713. case tok::l_square:
  714. // Recursively consume properly-nested square brackets.
  715. Toks.push_back(Tok);
  716. ConsumeBracket();
  717. ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
  718. break;
  719. case tok::l_brace:
  720. // Recursively consume properly-nested braces.
  721. Toks.push_back(Tok);
  722. ConsumeBrace();
  723. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  724. break;
  725. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  726. // Since the user wasn't looking for this token (if they were, it would
  727. // already be handled), this isn't balanced. If there is a LHS token at a
  728. // higher level, we will assume that this matches the unbalanced token
  729. // and return it. Otherwise, this is a spurious RHS token, which we skip.
  730. case tok::r_paren:
  731. if (ParenCount && !isFirstTokenConsumed)
  732. return false; // Matches something.
  733. Toks.push_back(Tok);
  734. ConsumeParen();
  735. break;
  736. case tok::r_square:
  737. if (BracketCount && !isFirstTokenConsumed)
  738. return false; // Matches something.
  739. Toks.push_back(Tok);
  740. ConsumeBracket();
  741. break;
  742. case tok::r_brace:
  743. if (BraceCount && !isFirstTokenConsumed)
  744. return false; // Matches something.
  745. Toks.push_back(Tok);
  746. ConsumeBrace();
  747. break;
  748. case tok::semi:
  749. if (StopAtSemi)
  750. return false;
  751. LLVM_FALLTHROUGH;
  752. default:
  753. // consume this token.
  754. Toks.push_back(Tok);
  755. ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
  756. break;
  757. }
  758. isFirstTokenConsumed = false;
  759. }
  760. }
  761. /// Consume tokens and store them in the passed token container until
  762. /// we've passed the try keyword and constructor initializers and have consumed
  763. /// the opening brace of the function body. The opening brace will be consumed
  764. /// if and only if there was no error.
  765. ///
  766. /// \return True on error.
  767. bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
  768. if (Tok.is(tok::kw_try)) {
  769. Toks.push_back(Tok);
  770. ConsumeToken();
  771. }
  772. if (Tok.isNot(tok::colon)) {
  773. // Easy case, just a function body.
  774. // Grab any remaining garbage to be diagnosed later. We stop when we reach a
  775. // brace: an opening one is the function body, while a closing one probably
  776. // means we've reached the end of the class.
  777. ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
  778. /*StopAtSemi=*/true,
  779. /*ConsumeFinalToken=*/false);
  780. if (Tok.isNot(tok::l_brace))
  781. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
  782. Toks.push_back(Tok);
  783. ConsumeBrace();
  784. return false;
  785. }
  786. Toks.push_back(Tok);
  787. ConsumeToken();
  788. // We can't reliably skip over a mem-initializer-id, because it could be
  789. // a template-id involving not-yet-declared names. Given:
  790. //
  791. // S ( ) : a < b < c > ( e )
  792. //
  793. // 'e' might be an initializer or part of a template argument, depending
  794. // on whether 'b' is a template.
  795. // Track whether we might be inside a template argument. We can give
  796. // significantly better diagnostics if we know that we're not.
  797. bool MightBeTemplateArgument = false;
  798. while (true) {
  799. // Skip over the mem-initializer-id, if possible.
  800. if (Tok.is(tok::kw_decltype)) {
  801. Toks.push_back(Tok);
  802. SourceLocation OpenLoc = ConsumeToken();
  803. if (Tok.isNot(tok::l_paren))
  804. return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
  805. << "decltype";
  806. Toks.push_back(Tok);
  807. ConsumeParen();
  808. if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
  809. Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
  810. Diag(OpenLoc, diag::note_matching) << tok::l_paren;
  811. return true;
  812. }
  813. }
  814. do {
  815. // Walk over a component of a nested-name-specifier.
  816. if (Tok.is(tok::coloncolon)) {
  817. Toks.push_back(Tok);
  818. ConsumeToken();
  819. if (Tok.is(tok::kw_template)) {
  820. Toks.push_back(Tok);
  821. ConsumeToken();
  822. }
  823. }
  824. if (Tok.is(tok::identifier)) {
  825. Toks.push_back(Tok);
  826. ConsumeToken();
  827. } else {
  828. break;
  829. }
  830. } while (Tok.is(tok::coloncolon));
  831. if (Tok.is(tok::code_completion)) {
  832. Toks.push_back(Tok);
  833. ConsumeCodeCompletionToken();
  834. if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
  835. // Could be the start of another member initializer (the ',' has not
  836. // been written yet)
  837. continue;
  838. }
  839. }
  840. if (Tok.is(tok::comma)) {
  841. // The initialization is missing, we'll diagnose it later.
  842. Toks.push_back(Tok);
  843. ConsumeToken();
  844. continue;
  845. }
  846. if (Tok.is(tok::less))
  847. MightBeTemplateArgument = true;
  848. if (MightBeTemplateArgument) {
  849. // We may be inside a template argument list. Grab up to the start of the
  850. // next parenthesized initializer or braced-init-list. This *might* be the
  851. // initializer, or it might be a subexpression in the template argument
  852. // list.
  853. // FIXME: Count angle brackets, and clear MightBeTemplateArgument
  854. // if all angles are closed.
  855. if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
  856. /*StopAtSemi=*/true,
  857. /*ConsumeFinalToken=*/false)) {
  858. // We're not just missing the initializer, we're also missing the
  859. // function body!
  860. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
  861. }
  862. } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
  863. // We found something weird in a mem-initializer-id.
  864. if (getLangOpts().CPlusPlus11)
  865. return Diag(Tok.getLocation(), diag::err_expected_either)
  866. << tok::l_paren << tok::l_brace;
  867. else
  868. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
  869. }
  870. tok::TokenKind kind = Tok.getKind();
  871. Toks.push_back(Tok);
  872. bool IsLParen = (kind == tok::l_paren);
  873. SourceLocation OpenLoc = Tok.getLocation();
  874. if (IsLParen) {
  875. ConsumeParen();
  876. } else {
  877. assert(kind == tok::l_brace && "Must be left paren or brace here.");
  878. ConsumeBrace();
  879. // In C++03, this has to be the start of the function body, which
  880. // means the initializer is malformed; we'll diagnose it later.
  881. if (!getLangOpts().CPlusPlus11)
  882. return false;
  883. const Token &PreviousToken = Toks[Toks.size() - 2];
  884. if (!MightBeTemplateArgument &&
  885. !PreviousToken.isOneOf(tok::identifier, tok::greater,
  886. tok::greatergreater)) {
  887. // If the opening brace is not preceded by one of these tokens, we are
  888. // missing the mem-initializer-id. In order to recover better, we need
  889. // to use heuristics to determine if this '{' is most likely the
  890. // beginning of a brace-init-list or the function body.
  891. // Check the token after the corresponding '}'.
  892. TentativeParsingAction PA(*this);
  893. if (SkipUntil(tok::r_brace) &&
  894. !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
  895. // Consider there was a malformed initializer and this is the start
  896. // of the function body. We'll diagnose it later.
  897. PA.Revert();
  898. return false;
  899. }
  900. PA.Revert();
  901. }
  902. }
  903. // Grab the initializer (or the subexpression of the template argument).
  904. // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
  905. // if we might be inside the braces of a lambda-expression.
  906. tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
  907. if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
  908. Diag(Tok, diag::err_expected) << CloseKind;
  909. Diag(OpenLoc, diag::note_matching) << kind;
  910. return true;
  911. }
  912. // Grab pack ellipsis, if present.
  913. if (Tok.is(tok::ellipsis)) {
  914. Toks.push_back(Tok);
  915. ConsumeToken();
  916. }
  917. // If we know we just consumed a mem-initializer, we must have ',' or '{'
  918. // next.
  919. if (Tok.is(tok::comma)) {
  920. Toks.push_back(Tok);
  921. ConsumeToken();
  922. } else if (Tok.is(tok::l_brace)) {
  923. // This is the function body if the ')' or '}' is immediately followed by
  924. // a '{'. That cannot happen within a template argument, apart from the
  925. // case where a template argument contains a compound literal:
  926. //
  927. // S ( ) : a < b < c > ( d ) { }
  928. // // End of declaration, or still inside the template argument?
  929. //
  930. // ... and the case where the template argument contains a lambda:
  931. //
  932. // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
  933. // ( ) > ( ) { }
  934. //
  935. // FIXME: Disambiguate these cases. Note that the latter case is probably
  936. // going to be made ill-formed by core issue 1607.
  937. Toks.push_back(Tok);
  938. ConsumeBrace();
  939. return false;
  940. } else if (!MightBeTemplateArgument) {
  941. return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
  942. << tok::comma;
  943. }
  944. }
  945. }
  946. /// Consume and store tokens from the '?' to the ':' in a conditional
  947. /// expression.
  948. bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
  949. // Consume '?'.
  950. assert(Tok.is(tok::question));
  951. Toks.push_back(Tok);
  952. ConsumeToken();
  953. while (Tok.isNot(tok::colon)) {
  954. if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
  955. /*StopAtSemi=*/true,
  956. /*ConsumeFinalToken=*/false))
  957. return false;
  958. // If we found a nested conditional, consume it.
  959. if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
  960. return false;
  961. }
  962. // Consume ':'.
  963. Toks.push_back(Tok);
  964. ConsumeToken();
  965. return true;
  966. }
  967. /// A tentative parsing action that can also revert token annotations.
  968. class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
  969. public:
  970. explicit UnannotatedTentativeParsingAction(Parser &Self,
  971. tok::TokenKind EndKind)
  972. : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
  973. // Stash away the old token stream, so we can restore it once the
  974. // tentative parse is complete.
  975. TentativeParsingAction Inner(Self);
  976. Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
  977. Inner.Revert();
  978. }
  979. void RevertAnnotations() {
  980. Revert();
  981. // Put back the original tokens.
  982. Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
  983. if (Toks.size()) {
  984. auto Buffer = std::make_unique<Token[]>(Toks.size());
  985. std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
  986. Buffer[Toks.size() - 1] = Self.Tok;
  987. Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true,
  988. /*IsReinject*/ true);
  989. Self.Tok = Toks.front();
  990. }
  991. }
  992. private:
  993. Parser &Self;
  994. CachedTokens Toks;
  995. tok::TokenKind EndKind;
  996. };
  997. /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
  998. /// container until the end of the current initializer expression (either a
  999. /// default argument or an in-class initializer for a non-static data member).
  1000. ///
  1001. /// Returns \c true if we reached the end of something initializer-shaped,
  1002. /// \c false if we bailed out.
  1003. bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
  1004. CachedInitKind CIK) {
  1005. // We always want this function to consume at least one token if not at EOF.
  1006. bool IsFirstToken = true;
  1007. // Number of possible unclosed <s we've seen so far. These might be templates,
  1008. // and might not, but if there were none of them (or we know for sure that
  1009. // we're within a template), we can avoid a tentative parse.
  1010. unsigned AngleCount = 0;
  1011. unsigned KnownTemplateCount = 0;
  1012. while (true) {
  1013. switch (Tok.getKind()) {
  1014. case tok::comma:
  1015. // If we might be in a template, perform a tentative parse to check.
  1016. if (!AngleCount)
  1017. // Not a template argument: this is the end of the initializer.
  1018. return true;
  1019. if (KnownTemplateCount)
  1020. goto consume_token;
  1021. // We hit a comma inside angle brackets. This is the hard case. The
  1022. // rule we follow is:
  1023. // * For a default argument, if the tokens after the comma form a
  1024. // syntactically-valid parameter-declaration-clause, in which each
  1025. // parameter has an initializer, then this comma ends the default
  1026. // argument.
  1027. // * For a default initializer, if the tokens after the comma form a
  1028. // syntactically-valid init-declarator-list, then this comma ends
  1029. // the default initializer.
  1030. {
  1031. UnannotatedTentativeParsingAction PA(*this,
  1032. CIK == CIK_DefaultInitializer
  1033. ? tok::semi : tok::r_paren);
  1034. Sema::TentativeAnalysisScope Scope(Actions);
  1035. TPResult Result = TPResult::Error;
  1036. ConsumeToken();
  1037. switch (CIK) {
  1038. case CIK_DefaultInitializer:
  1039. Result = TryParseInitDeclaratorList();
  1040. // If we parsed a complete, ambiguous init-declarator-list, this
  1041. // is only syntactically-valid if it's followed by a semicolon.
  1042. if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
  1043. Result = TPResult::False;
  1044. break;
  1045. case CIK_DefaultArgument:
  1046. bool InvalidAsDeclaration = false;
  1047. Result = TryParseParameterDeclarationClause(
  1048. &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
  1049. // If this is an expression or a declaration with a missing
  1050. // 'typename', assume it's not a declaration.
  1051. if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
  1052. Result = TPResult::False;
  1053. break;
  1054. }
  1055. // Put the token stream back and undo any annotations we performed
  1056. // after the comma. They may reflect a different parse than the one
  1057. // we will actually perform at the end of the class.
  1058. PA.RevertAnnotations();
  1059. // If what follows could be a declaration, it is a declaration.
  1060. if (Result != TPResult::False && Result != TPResult::Error)
  1061. return true;
  1062. }
  1063. // Keep going. We know we're inside a template argument list now.
  1064. ++KnownTemplateCount;
  1065. goto consume_token;
  1066. case tok::eof:
  1067. case tok::annot_module_begin:
  1068. case tok::annot_module_end:
  1069. case tok::annot_module_include:
  1070. // Ran out of tokens.
  1071. return false;
  1072. case tok::less:
  1073. // FIXME: A '<' can only start a template-id if it's preceded by an
  1074. // identifier, an operator-function-id, or a literal-operator-id.
  1075. ++AngleCount;
  1076. goto consume_token;
  1077. case tok::question:
  1078. // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
  1079. // that is *never* the end of the initializer. Skip to the ':'.
  1080. if (!ConsumeAndStoreConditional(Toks))
  1081. return false;
  1082. break;
  1083. case tok::greatergreatergreater:
  1084. if (!getLangOpts().CPlusPlus11)
  1085. goto consume_token;
  1086. if (AngleCount) --AngleCount;
  1087. if (KnownTemplateCount) --KnownTemplateCount;
  1088. LLVM_FALLTHROUGH;
  1089. case tok::greatergreater:
  1090. if (!getLangOpts().CPlusPlus11)
  1091. goto consume_token;
  1092. if (AngleCount) --AngleCount;
  1093. if (KnownTemplateCount) --KnownTemplateCount;
  1094. LLVM_FALLTHROUGH;
  1095. case tok::greater:
  1096. if (AngleCount) --AngleCount;
  1097. if (KnownTemplateCount) --KnownTemplateCount;
  1098. goto consume_token;
  1099. case tok::kw_template:
  1100. // 'template' identifier '<' is known to start a template argument list,
  1101. // and can be used to disambiguate the parse.
  1102. // FIXME: Support all forms of 'template' unqualified-id '<'.
  1103. Toks.push_back(Tok);
  1104. ConsumeToken();
  1105. if (Tok.is(tok::identifier)) {
  1106. Toks.push_back(Tok);
  1107. ConsumeToken();
  1108. if (Tok.is(tok::less)) {
  1109. ++AngleCount;
  1110. ++KnownTemplateCount;
  1111. Toks.push_back(Tok);
  1112. ConsumeToken();
  1113. }
  1114. }
  1115. break;
  1116. case tok::kw_operator:
  1117. // If 'operator' precedes other punctuation, that punctuation loses
  1118. // its special behavior.
  1119. Toks.push_back(Tok);
  1120. ConsumeToken();
  1121. switch (Tok.getKind()) {
  1122. case tok::comma:
  1123. case tok::greatergreatergreater:
  1124. case tok::greatergreater:
  1125. case tok::greater:
  1126. case tok::less:
  1127. Toks.push_back(Tok);
  1128. ConsumeToken();
  1129. break;
  1130. default:
  1131. break;
  1132. }
  1133. break;
  1134. case tok::l_paren:
  1135. // Recursively consume properly-nested parens.
  1136. Toks.push_back(Tok);
  1137. ConsumeParen();
  1138. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  1139. break;
  1140. case tok::l_square:
  1141. // Recursively consume properly-nested square brackets.
  1142. Toks.push_back(Tok);
  1143. ConsumeBracket();
  1144. ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
  1145. break;
  1146. case tok::l_brace:
  1147. // Recursively consume properly-nested braces.
  1148. Toks.push_back(Tok);
  1149. ConsumeBrace();
  1150. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1151. break;
  1152. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  1153. // Since the user wasn't looking for this token (if they were, it would
  1154. // already be handled), this isn't balanced. If there is a LHS token at a
  1155. // higher level, we will assume that this matches the unbalanced token
  1156. // and return it. Otherwise, this is a spurious RHS token, which we
  1157. // consume and pass on to downstream code to diagnose.
  1158. case tok::r_paren:
  1159. if (CIK == CIK_DefaultArgument)
  1160. return true; // End of the default argument.
  1161. if (ParenCount && !IsFirstToken)
  1162. return false;
  1163. Toks.push_back(Tok);
  1164. ConsumeParen();
  1165. continue;
  1166. case tok::r_square:
  1167. if (BracketCount && !IsFirstToken)
  1168. return false;
  1169. Toks.push_back(Tok);
  1170. ConsumeBracket();
  1171. continue;
  1172. case tok::r_brace:
  1173. if (BraceCount && !IsFirstToken)
  1174. return false;
  1175. Toks.push_back(Tok);
  1176. ConsumeBrace();
  1177. continue;
  1178. case tok::code_completion:
  1179. Toks.push_back(Tok);
  1180. ConsumeCodeCompletionToken();
  1181. break;
  1182. case tok::string_literal:
  1183. case tok::wide_string_literal:
  1184. case tok::utf8_string_literal:
  1185. case tok::utf16_string_literal:
  1186. case tok::utf32_string_literal:
  1187. Toks.push_back(Tok);
  1188. ConsumeStringToken();
  1189. break;
  1190. case tok::semi:
  1191. if (CIK == CIK_DefaultInitializer)
  1192. return true; // End of the default initializer.
  1193. LLVM_FALLTHROUGH;
  1194. default:
  1195. consume_token:
  1196. Toks.push_back(Tok);
  1197. ConsumeToken();
  1198. break;
  1199. }
  1200. IsFirstToken = false;
  1201. }
  1202. }