ParseCXXInlineMethods.cpp 45 KB

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