ParseCXXInlineMethods.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  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, const ParsedAttributesView &AccessAttrs,
  24. ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo,
  25. const VirtSpecifiers &VS, 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. // The initializer isn't actually potentially evaluated unless it is
  547. // used.
  548. EnterExpressionEvaluationContext Eval(
  549. Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed);
  550. ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
  551. EqualLoc);
  552. Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
  553. Init.get());
  554. // The next token should be our artificial terminating EOF token.
  555. if (Tok.isNot(tok::eof)) {
  556. if (!Init.isInvalid()) {
  557. SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
  558. if (!EndLoc.isValid())
  559. EndLoc = Tok.getLocation();
  560. // No fixit; we can't recover as if there were a semicolon here.
  561. Diag(EndLoc, diag::err_expected_semi_decl_list);
  562. }
  563. // Consume tokens until we hit the artificial EOF.
  564. while (Tok.isNot(tok::eof))
  565. ConsumeAnyToken();
  566. }
  567. // Make sure this is *our* artificial EOF token.
  568. if (Tok.getEofData() == MI.Field)
  569. ConsumeAnyToken();
  570. }
  571. /// Wrapper class which calls ParseLexedAttribute, after setting up the
  572. /// scope appropriately.
  573. void Parser::ParseLexedAttributes(ParsingClass &Class) {
  574. ReenterClassScopeRAII InClassScope(*this, Class);
  575. for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
  576. LateD->ParseLexedAttributes();
  577. }
  578. /// Parse all attributes in LAs, and attach them to Decl D.
  579. void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
  580. bool EnterScope, bool OnDefinition) {
  581. assert(LAs.parseSoon() &&
  582. "Attribute list should be marked for immediate parsing.");
  583. for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
  584. if (D)
  585. LAs[i]->addDecl(D);
  586. ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
  587. delete LAs[i];
  588. }
  589. LAs.clear();
  590. }
  591. /// Finish parsing an attribute for which parsing was delayed.
  592. /// This will be called at the end of parsing a class declaration
  593. /// for each LateParsedAttribute. We consume the saved tokens and
  594. /// create an attribute with the arguments filled in. We add this
  595. /// to the Attribute list for the decl.
  596. void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
  597. bool EnterScope, bool OnDefinition) {
  598. // Create a fake EOF so that attribute parsing won't go off the end of the
  599. // attribute.
  600. Token AttrEnd;
  601. AttrEnd.startToken();
  602. AttrEnd.setKind(tok::eof);
  603. AttrEnd.setLocation(Tok.getLocation());
  604. AttrEnd.setEofData(LA.Toks.data());
  605. LA.Toks.push_back(AttrEnd);
  606. // Append the current token at the end of the new token stream so that it
  607. // doesn't get lost.
  608. LA.Toks.push_back(Tok);
  609. PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
  610. // Consume the previously pushed token.
  611. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  612. ParsedAttributes Attrs(AttrFactory);
  613. if (LA.Decls.size() > 0) {
  614. Decl *D = LA.Decls[0];
  615. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  616. RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
  617. // Allow 'this' within late-parsed attributes.
  618. Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
  619. ND && ND->isCXXInstanceMember());
  620. if (LA.Decls.size() == 1) {
  621. // If the Decl is templatized, add template parameters to scope.
  622. ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope);
  623. // If the Decl is on a function, add function parameters to the scope.
  624. bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
  625. if (HasFunScope) {
  626. InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
  627. Scope::CompoundStmtScope);
  628. Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
  629. }
  630. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
  631. nullptr, SourceLocation(), ParsedAttr::AS_GNU,
  632. nullptr);
  633. if (HasFunScope)
  634. Actions.ActOnExitFunctionContext();
  635. } else {
  636. // If there are multiple decls, then the decl cannot be within the
  637. // function scope.
  638. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
  639. nullptr, SourceLocation(), ParsedAttr::AS_GNU,
  640. nullptr);
  641. }
  642. } else {
  643. Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
  644. }
  645. if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
  646. Attrs.begin()->isKnownToGCC())
  647. Diag(Tok, diag::warn_attribute_on_function_definition)
  648. << &LA.AttrName;
  649. for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
  650. Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
  651. // Due to a parsing error, we either went over the cached tokens or
  652. // there are still cached tokens left, so we skip the leftover tokens.
  653. while (Tok.isNot(tok::eof))
  654. ConsumeAnyToken();
  655. if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
  656. ConsumeAnyToken();
  657. }
  658. void Parser::ParseLexedPragmas(ParsingClass &Class) {
  659. ReenterClassScopeRAII InClassScope(*this, Class);
  660. for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
  661. D->ParseLexedPragmas();
  662. }
  663. void Parser::ParseLexedPragma(LateParsedPragma &LP) {
  664. PP.EnterToken(Tok, /*IsReinject=*/true);
  665. PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true,
  666. /*IsReinject=*/true);
  667. // Consume the previously pushed token.
  668. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  669. assert(Tok.isAnnotation() && "Expected annotation token.");
  670. switch (Tok.getKind()) {
  671. case tok::annot_attr_openmp:
  672. case tok::annot_pragma_openmp: {
  673. AccessSpecifier AS = LP.getAccessSpecifier();
  674. ParsedAttributes Attrs(AttrFactory);
  675. (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
  676. break;
  677. }
  678. default:
  679. llvm_unreachable("Unexpected token.");
  680. }
  681. }
  682. /// ConsumeAndStoreUntil - Consume and store the token at the passed token
  683. /// container until the token 'T' is reached (which gets
  684. /// consumed/stored too, if ConsumeFinalToken).
  685. /// If StopAtSemi is true, then we will stop early at a ';' character.
  686. /// Returns true if token 'T1' or 'T2' was found.
  687. /// NOTE: This is a specialized version of Parser::SkipUntil.
  688. bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
  689. CachedTokens &Toks,
  690. bool StopAtSemi, bool ConsumeFinalToken) {
  691. // We always want this function to consume at least one token if the first
  692. // token isn't T and if not at EOF.
  693. bool isFirstTokenConsumed = true;
  694. while (true) {
  695. // If we found one of the tokens, stop and return true.
  696. if (Tok.is(T1) || Tok.is(T2)) {
  697. if (ConsumeFinalToken) {
  698. Toks.push_back(Tok);
  699. ConsumeAnyToken();
  700. }
  701. return true;
  702. }
  703. switch (Tok.getKind()) {
  704. case tok::eof:
  705. case tok::annot_module_begin:
  706. case tok::annot_module_end:
  707. case tok::annot_module_include:
  708. // Ran out of tokens.
  709. return false;
  710. case tok::l_paren:
  711. // Recursively consume properly-nested parens.
  712. Toks.push_back(Tok);
  713. ConsumeParen();
  714. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  715. break;
  716. case tok::l_square:
  717. // Recursively consume properly-nested square brackets.
  718. Toks.push_back(Tok);
  719. ConsumeBracket();
  720. ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
  721. break;
  722. case tok::l_brace:
  723. // Recursively consume properly-nested braces.
  724. Toks.push_back(Tok);
  725. ConsumeBrace();
  726. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  727. break;
  728. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  729. // Since the user wasn't looking for this token (if they were, it would
  730. // already be handled), this isn't balanced. If there is a LHS token at a
  731. // higher level, we will assume that this matches the unbalanced token
  732. // and return it. Otherwise, this is a spurious RHS token, which we skip.
  733. case tok::r_paren:
  734. if (ParenCount && !isFirstTokenConsumed)
  735. return false; // Matches something.
  736. Toks.push_back(Tok);
  737. ConsumeParen();
  738. break;
  739. case tok::r_square:
  740. if (BracketCount && !isFirstTokenConsumed)
  741. return false; // Matches something.
  742. Toks.push_back(Tok);
  743. ConsumeBracket();
  744. break;
  745. case tok::r_brace:
  746. if (BraceCount && !isFirstTokenConsumed)
  747. return false; // Matches something.
  748. Toks.push_back(Tok);
  749. ConsumeBrace();
  750. break;
  751. case tok::semi:
  752. if (StopAtSemi)
  753. return false;
  754. [[fallthrough]];
  755. default:
  756. // consume this token.
  757. Toks.push_back(Tok);
  758. ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
  759. break;
  760. }
  761. isFirstTokenConsumed = false;
  762. }
  763. }
  764. /// Consume tokens and store them in the passed token container until
  765. /// we've passed the try keyword and constructor initializers and have consumed
  766. /// the opening brace of the function body. The opening brace will be consumed
  767. /// if and only if there was no error.
  768. ///
  769. /// \return True on error.
  770. bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
  771. if (Tok.is(tok::kw_try)) {
  772. Toks.push_back(Tok);
  773. ConsumeToken();
  774. }
  775. if (Tok.isNot(tok::colon)) {
  776. // Easy case, just a function body.
  777. // Grab any remaining garbage to be diagnosed later. We stop when we reach a
  778. // brace: an opening one is the function body, while a closing one probably
  779. // means we've reached the end of the class.
  780. ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
  781. /*StopAtSemi=*/true,
  782. /*ConsumeFinalToken=*/false);
  783. if (Tok.isNot(tok::l_brace))
  784. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
  785. Toks.push_back(Tok);
  786. ConsumeBrace();
  787. return false;
  788. }
  789. Toks.push_back(Tok);
  790. ConsumeToken();
  791. // We can't reliably skip over a mem-initializer-id, because it could be
  792. // a template-id involving not-yet-declared names. Given:
  793. //
  794. // S ( ) : a < b < c > ( e )
  795. //
  796. // 'e' might be an initializer or part of a template argument, depending
  797. // on whether 'b' is a template.
  798. // Track whether we might be inside a template argument. We can give
  799. // significantly better diagnostics if we know that we're not.
  800. bool MightBeTemplateArgument = false;
  801. while (true) {
  802. // Skip over the mem-initializer-id, if possible.
  803. if (Tok.is(tok::kw_decltype)) {
  804. Toks.push_back(Tok);
  805. SourceLocation OpenLoc = ConsumeToken();
  806. if (Tok.isNot(tok::l_paren))
  807. return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
  808. << "decltype";
  809. Toks.push_back(Tok);
  810. ConsumeParen();
  811. if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
  812. Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
  813. Diag(OpenLoc, diag::note_matching) << tok::l_paren;
  814. return true;
  815. }
  816. }
  817. do {
  818. // Walk over a component of a nested-name-specifier.
  819. if (Tok.is(tok::coloncolon)) {
  820. Toks.push_back(Tok);
  821. ConsumeToken();
  822. if (Tok.is(tok::kw_template)) {
  823. Toks.push_back(Tok);
  824. ConsumeToken();
  825. }
  826. }
  827. if (Tok.is(tok::identifier)) {
  828. Toks.push_back(Tok);
  829. ConsumeToken();
  830. } else {
  831. break;
  832. }
  833. } while (Tok.is(tok::coloncolon));
  834. if (Tok.is(tok::code_completion)) {
  835. Toks.push_back(Tok);
  836. ConsumeCodeCompletionToken();
  837. if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
  838. // Could be the start of another member initializer (the ',' has not
  839. // been written yet)
  840. continue;
  841. }
  842. }
  843. if (Tok.is(tok::comma)) {
  844. // The initialization is missing, we'll diagnose it later.
  845. Toks.push_back(Tok);
  846. ConsumeToken();
  847. continue;
  848. }
  849. if (Tok.is(tok::less))
  850. MightBeTemplateArgument = true;
  851. if (MightBeTemplateArgument) {
  852. // We may be inside a template argument list. Grab up to the start of the
  853. // next parenthesized initializer or braced-init-list. This *might* be the
  854. // initializer, or it might be a subexpression in the template argument
  855. // list.
  856. // FIXME: Count angle brackets, and clear MightBeTemplateArgument
  857. // if all angles are closed.
  858. if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
  859. /*StopAtSemi=*/true,
  860. /*ConsumeFinalToken=*/false)) {
  861. // We're not just missing the initializer, we're also missing the
  862. // function body!
  863. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
  864. }
  865. } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
  866. // We found something weird in a mem-initializer-id.
  867. if (getLangOpts().CPlusPlus11)
  868. return Diag(Tok.getLocation(), diag::err_expected_either)
  869. << tok::l_paren << tok::l_brace;
  870. else
  871. return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
  872. }
  873. tok::TokenKind kind = Tok.getKind();
  874. Toks.push_back(Tok);
  875. bool IsLParen = (kind == tok::l_paren);
  876. SourceLocation OpenLoc = Tok.getLocation();
  877. if (IsLParen) {
  878. ConsumeParen();
  879. } else {
  880. assert(kind == tok::l_brace && "Must be left paren or brace here.");
  881. ConsumeBrace();
  882. // In C++03, this has to be the start of the function body, which
  883. // means the initializer is malformed; we'll diagnose it later.
  884. if (!getLangOpts().CPlusPlus11)
  885. return false;
  886. const Token &PreviousToken = Toks[Toks.size() - 2];
  887. if (!MightBeTemplateArgument &&
  888. !PreviousToken.isOneOf(tok::identifier, tok::greater,
  889. tok::greatergreater)) {
  890. // If the opening brace is not preceded by one of these tokens, we are
  891. // missing the mem-initializer-id. In order to recover better, we need
  892. // to use heuristics to determine if this '{' is most likely the
  893. // beginning of a brace-init-list or the function body.
  894. // Check the token after the corresponding '}'.
  895. TentativeParsingAction PA(*this);
  896. if (SkipUntil(tok::r_brace) &&
  897. !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
  898. // Consider there was a malformed initializer and this is the start
  899. // of the function body. We'll diagnose it later.
  900. PA.Revert();
  901. return false;
  902. }
  903. PA.Revert();
  904. }
  905. }
  906. // Grab the initializer (or the subexpression of the template argument).
  907. // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
  908. // if we might be inside the braces of a lambda-expression.
  909. tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
  910. if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
  911. Diag(Tok, diag::err_expected) << CloseKind;
  912. Diag(OpenLoc, diag::note_matching) << kind;
  913. return true;
  914. }
  915. // Grab pack ellipsis, if present.
  916. if (Tok.is(tok::ellipsis)) {
  917. Toks.push_back(Tok);
  918. ConsumeToken();
  919. }
  920. // If we know we just consumed a mem-initializer, we must have ',' or '{'
  921. // next.
  922. if (Tok.is(tok::comma)) {
  923. Toks.push_back(Tok);
  924. ConsumeToken();
  925. } else if (Tok.is(tok::l_brace)) {
  926. // This is the function body if the ')' or '}' is immediately followed by
  927. // a '{'. That cannot happen within a template argument, apart from the
  928. // case where a template argument contains a compound literal:
  929. //
  930. // S ( ) : a < b < c > ( d ) { }
  931. // // End of declaration, or still inside the template argument?
  932. //
  933. // ... and the case where the template argument contains a lambda:
  934. //
  935. // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
  936. // ( ) > ( ) { }
  937. //
  938. // FIXME: Disambiguate these cases. Note that the latter case is probably
  939. // going to be made ill-formed by core issue 1607.
  940. Toks.push_back(Tok);
  941. ConsumeBrace();
  942. return false;
  943. } else if (!MightBeTemplateArgument) {
  944. return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
  945. << tok::comma;
  946. }
  947. }
  948. }
  949. /// Consume and store tokens from the '?' to the ':' in a conditional
  950. /// expression.
  951. bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
  952. // Consume '?'.
  953. assert(Tok.is(tok::question));
  954. Toks.push_back(Tok);
  955. ConsumeToken();
  956. while (Tok.isNot(tok::colon)) {
  957. if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
  958. /*StopAtSemi=*/true,
  959. /*ConsumeFinalToken=*/false))
  960. return false;
  961. // If we found a nested conditional, consume it.
  962. if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
  963. return false;
  964. }
  965. // Consume ':'.
  966. Toks.push_back(Tok);
  967. ConsumeToken();
  968. return true;
  969. }
  970. /// A tentative parsing action that can also revert token annotations.
  971. class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
  972. public:
  973. explicit UnannotatedTentativeParsingAction(Parser &Self,
  974. tok::TokenKind EndKind)
  975. : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
  976. // Stash away the old token stream, so we can restore it once the
  977. // tentative parse is complete.
  978. TentativeParsingAction Inner(Self);
  979. Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
  980. Inner.Revert();
  981. }
  982. void RevertAnnotations() {
  983. Revert();
  984. // Put back the original tokens.
  985. Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
  986. if (Toks.size()) {
  987. auto Buffer = std::make_unique<Token[]>(Toks.size());
  988. std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
  989. Buffer[Toks.size() - 1] = Self.Tok;
  990. Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true,
  991. /*IsReinject*/ true);
  992. Self.Tok = Toks.front();
  993. }
  994. }
  995. private:
  996. Parser &Self;
  997. CachedTokens Toks;
  998. tok::TokenKind EndKind;
  999. };
  1000. /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
  1001. /// container until the end of the current initializer expression (either a
  1002. /// default argument or an in-class initializer for a non-static data member).
  1003. ///
  1004. /// Returns \c true if we reached the end of something initializer-shaped,
  1005. /// \c false if we bailed out.
  1006. bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
  1007. CachedInitKind CIK) {
  1008. // We always want this function to consume at least one token if not at EOF.
  1009. bool IsFirstToken = true;
  1010. // Number of possible unclosed <s we've seen so far. These might be templates,
  1011. // and might not, but if there were none of them (or we know for sure that
  1012. // we're within a template), we can avoid a tentative parse.
  1013. unsigned AngleCount = 0;
  1014. unsigned KnownTemplateCount = 0;
  1015. while (true) {
  1016. switch (Tok.getKind()) {
  1017. case tok::comma:
  1018. // If we might be in a template, perform a tentative parse to check.
  1019. if (!AngleCount)
  1020. // Not a template argument: this is the end of the initializer.
  1021. return true;
  1022. if (KnownTemplateCount)
  1023. goto consume_token;
  1024. // We hit a comma inside angle brackets. This is the hard case. The
  1025. // rule we follow is:
  1026. // * For a default argument, if the tokens after the comma form a
  1027. // syntactically-valid parameter-declaration-clause, in which each
  1028. // parameter has an initializer, then this comma ends the default
  1029. // argument.
  1030. // * For a default initializer, if the tokens after the comma form a
  1031. // syntactically-valid init-declarator-list, then this comma ends
  1032. // the default initializer.
  1033. {
  1034. UnannotatedTentativeParsingAction PA(*this,
  1035. CIK == CIK_DefaultInitializer
  1036. ? tok::semi : tok::r_paren);
  1037. Sema::TentativeAnalysisScope Scope(Actions);
  1038. TPResult Result = TPResult::Error;
  1039. ConsumeToken();
  1040. switch (CIK) {
  1041. case CIK_DefaultInitializer:
  1042. Result = TryParseInitDeclaratorList();
  1043. // If we parsed a complete, ambiguous init-declarator-list, this
  1044. // is only syntactically-valid if it's followed by a semicolon.
  1045. if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
  1046. Result = TPResult::False;
  1047. break;
  1048. case CIK_DefaultArgument:
  1049. bool InvalidAsDeclaration = false;
  1050. Result = TryParseParameterDeclarationClause(
  1051. &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
  1052. // If this is an expression or a declaration with a missing
  1053. // 'typename', assume it's not a declaration.
  1054. if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
  1055. Result = TPResult::False;
  1056. break;
  1057. }
  1058. // Put the token stream back and undo any annotations we performed
  1059. // after the comma. They may reflect a different parse than the one
  1060. // we will actually perform at the end of the class.
  1061. PA.RevertAnnotations();
  1062. // If what follows could be a declaration, it is a declaration.
  1063. if (Result != TPResult::False && Result != TPResult::Error)
  1064. return true;
  1065. }
  1066. // Keep going. We know we're inside a template argument list now.
  1067. ++KnownTemplateCount;
  1068. goto consume_token;
  1069. case tok::eof:
  1070. case tok::annot_module_begin:
  1071. case tok::annot_module_end:
  1072. case tok::annot_module_include:
  1073. // Ran out of tokens.
  1074. return false;
  1075. case tok::less:
  1076. // FIXME: A '<' can only start a template-id if it's preceded by an
  1077. // identifier, an operator-function-id, or a literal-operator-id.
  1078. ++AngleCount;
  1079. goto consume_token;
  1080. case tok::question:
  1081. // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
  1082. // that is *never* the end of the initializer. Skip to the ':'.
  1083. if (!ConsumeAndStoreConditional(Toks))
  1084. return false;
  1085. break;
  1086. case tok::greatergreatergreater:
  1087. if (!getLangOpts().CPlusPlus11)
  1088. goto consume_token;
  1089. if (AngleCount) --AngleCount;
  1090. if (KnownTemplateCount) --KnownTemplateCount;
  1091. [[fallthrough]];
  1092. case tok::greatergreater:
  1093. if (!getLangOpts().CPlusPlus11)
  1094. goto consume_token;
  1095. if (AngleCount) --AngleCount;
  1096. if (KnownTemplateCount) --KnownTemplateCount;
  1097. [[fallthrough]];
  1098. case tok::greater:
  1099. if (AngleCount) --AngleCount;
  1100. if (KnownTemplateCount) --KnownTemplateCount;
  1101. goto consume_token;
  1102. case tok::kw_template:
  1103. // 'template' identifier '<' is known to start a template argument list,
  1104. // and can be used to disambiguate the parse.
  1105. // FIXME: Support all forms of 'template' unqualified-id '<'.
  1106. Toks.push_back(Tok);
  1107. ConsumeToken();
  1108. if (Tok.is(tok::identifier)) {
  1109. Toks.push_back(Tok);
  1110. ConsumeToken();
  1111. if (Tok.is(tok::less)) {
  1112. ++AngleCount;
  1113. ++KnownTemplateCount;
  1114. Toks.push_back(Tok);
  1115. ConsumeToken();
  1116. }
  1117. }
  1118. break;
  1119. case tok::kw_operator:
  1120. // If 'operator' precedes other punctuation, that punctuation loses
  1121. // its special behavior.
  1122. Toks.push_back(Tok);
  1123. ConsumeToken();
  1124. switch (Tok.getKind()) {
  1125. case tok::comma:
  1126. case tok::greatergreatergreater:
  1127. case tok::greatergreater:
  1128. case tok::greater:
  1129. case tok::less:
  1130. Toks.push_back(Tok);
  1131. ConsumeToken();
  1132. break;
  1133. default:
  1134. break;
  1135. }
  1136. break;
  1137. case tok::l_paren:
  1138. // Recursively consume properly-nested parens.
  1139. Toks.push_back(Tok);
  1140. ConsumeParen();
  1141. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  1142. break;
  1143. case tok::l_square:
  1144. // Recursively consume properly-nested square brackets.
  1145. Toks.push_back(Tok);
  1146. ConsumeBracket();
  1147. ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
  1148. break;
  1149. case tok::l_brace:
  1150. // Recursively consume properly-nested braces.
  1151. Toks.push_back(Tok);
  1152. ConsumeBrace();
  1153. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1154. break;
  1155. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  1156. // Since the user wasn't looking for this token (if they were, it would
  1157. // already be handled), this isn't balanced. If there is a LHS token at a
  1158. // higher level, we will assume that this matches the unbalanced token
  1159. // and return it. Otherwise, this is a spurious RHS token, which we
  1160. // consume and pass on to downstream code to diagnose.
  1161. case tok::r_paren:
  1162. if (CIK == CIK_DefaultArgument)
  1163. return true; // End of the default argument.
  1164. if (ParenCount && !IsFirstToken)
  1165. return false;
  1166. Toks.push_back(Tok);
  1167. ConsumeParen();
  1168. continue;
  1169. case tok::r_square:
  1170. if (BracketCount && !IsFirstToken)
  1171. return false;
  1172. Toks.push_back(Tok);
  1173. ConsumeBracket();
  1174. continue;
  1175. case tok::r_brace:
  1176. if (BraceCount && !IsFirstToken)
  1177. return false;
  1178. Toks.push_back(Tok);
  1179. ConsumeBrace();
  1180. continue;
  1181. case tok::code_completion:
  1182. Toks.push_back(Tok);
  1183. ConsumeCodeCompletionToken();
  1184. break;
  1185. case tok::string_literal:
  1186. case tok::wide_string_literal:
  1187. case tok::utf8_string_literal:
  1188. case tok::utf16_string_literal:
  1189. case tok::utf32_string_literal:
  1190. Toks.push_back(Tok);
  1191. ConsumeStringToken();
  1192. break;
  1193. case tok::semi:
  1194. if (CIK == CIK_DefaultInitializer)
  1195. return true; // End of the default initializer.
  1196. [[fallthrough]];
  1197. default:
  1198. consume_token:
  1199. Toks.push_back(Tok);
  1200. ConsumeToken();
  1201. break;
  1202. }
  1203. IsFirstToken = false;
  1204. }
  1205. }