ParseTemplate.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. //===--- ParseTemplate.cpp - Template 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 of C++ templates.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/DeclTemplate.h"
  14. #include "clang/Parse/ParseDiagnostic.h"
  15. #include "clang/Parse/Parser.h"
  16. #include "clang/Parse/RAIIObjectsForParser.h"
  17. #include "clang/Sema/DeclSpec.h"
  18. #include "clang/Sema/ParsedTemplate.h"
  19. #include "clang/Sema/Scope.h"
  20. #include "llvm/Support/TimeProfiler.h"
  21. using namespace clang;
  22. /// Parse a template declaration, explicit instantiation, or
  23. /// explicit specialization.
  24. Decl *Parser::ParseDeclarationStartingWithTemplate(
  25. DeclaratorContext Context, SourceLocation &DeclEnd,
  26. ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
  27. ObjCDeclContextSwitch ObjCDC(*this);
  28. if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
  29. return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
  30. DeclEnd, AccessAttrs, AS);
  31. }
  32. return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
  33. AS);
  34. }
  35. /// Parse a template declaration or an explicit specialization.
  36. ///
  37. /// Template declarations include one or more template parameter lists
  38. /// and either the function or class template declaration. Explicit
  39. /// specializations contain one or more 'template < >' prefixes
  40. /// followed by a (possibly templated) declaration. Since the
  41. /// syntactic form of both features is nearly identical, we parse all
  42. /// of the template headers together and let semantic analysis sort
  43. /// the declarations from the explicit specializations.
  44. ///
  45. /// template-declaration: [C++ temp]
  46. /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
  47. ///
  48. /// template-declaration: [C++2a]
  49. /// template-head declaration
  50. /// template-head concept-definition
  51. ///
  52. /// TODO: requires-clause
  53. /// template-head: [C++2a]
  54. /// 'template' '<' template-parameter-list '>'
  55. /// requires-clause[opt]
  56. ///
  57. /// explicit-specialization: [ C++ temp.expl.spec]
  58. /// 'template' '<' '>' declaration
  59. Decl *Parser::ParseTemplateDeclarationOrSpecialization(
  60. DeclaratorContext Context, SourceLocation &DeclEnd,
  61. ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
  62. assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
  63. "Token does not start a template declaration.");
  64. // Enter template-parameter scope.
  65. ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
  66. // Tell the action that names should be checked in the context of
  67. // the declaration to come.
  68. ParsingDeclRAIIObject
  69. ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
  70. // Parse multiple levels of template headers within this template
  71. // parameter scope, e.g.,
  72. //
  73. // template<typename T>
  74. // template<typename U>
  75. // class A<T>::B { ... };
  76. //
  77. // We parse multiple levels non-recursively so that we can build a
  78. // single data structure containing all of the template parameter
  79. // lists to easily differentiate between the case above and:
  80. //
  81. // template<typename T>
  82. // class A {
  83. // template<typename U> class B;
  84. // };
  85. //
  86. // In the first case, the action for declaring A<T>::B receives
  87. // both template parameter lists. In the second case, the action for
  88. // defining A<T>::B receives just the inner template parameter list
  89. // (and retrieves the outer template parameter list from its
  90. // context).
  91. bool isSpecialization = true;
  92. bool LastParamListWasEmpty = false;
  93. TemplateParameterLists ParamLists;
  94. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  95. do {
  96. // Consume the 'export', if any.
  97. SourceLocation ExportLoc;
  98. TryConsumeToken(tok::kw_export, ExportLoc);
  99. // Consume the 'template', which should be here.
  100. SourceLocation TemplateLoc;
  101. if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
  102. Diag(Tok.getLocation(), diag::err_expected_template);
  103. return nullptr;
  104. }
  105. // Parse the '<' template-parameter-list '>'
  106. SourceLocation LAngleLoc, RAngleLoc;
  107. SmallVector<NamedDecl*, 4> TemplateParams;
  108. if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
  109. TemplateParams, LAngleLoc, RAngleLoc)) {
  110. // Skip until the semi-colon or a '}'.
  111. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  112. TryConsumeToken(tok::semi);
  113. return nullptr;
  114. }
  115. ExprResult OptionalRequiresClauseConstraintER;
  116. if (!TemplateParams.empty()) {
  117. isSpecialization = false;
  118. ++CurTemplateDepthTracker;
  119. if (TryConsumeToken(tok::kw_requires)) {
  120. OptionalRequiresClauseConstraintER =
  121. Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
  122. if (!OptionalRequiresClauseConstraintER.isUsable()) {
  123. // Skip until the semi-colon or a '}'.
  124. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  125. TryConsumeToken(tok::semi);
  126. return nullptr;
  127. }
  128. }
  129. } else {
  130. LastParamListWasEmpty = true;
  131. }
  132. ParamLists.push_back(Actions.ActOnTemplateParameterList(
  133. CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
  134. TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
  135. } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
  136. unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
  137. ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
  138. // Parse the actual template declaration.
  139. if (Tok.is(tok::kw_concept))
  140. return ParseConceptDefinition(
  141. ParsedTemplateInfo(&ParamLists, isSpecialization,
  142. LastParamListWasEmpty),
  143. DeclEnd);
  144. return ParseSingleDeclarationAfterTemplate(
  145. Context,
  146. ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
  147. ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
  148. }
  149. /// Parse a single declaration that declares a template,
  150. /// template specialization, or explicit instantiation of a template.
  151. ///
  152. /// \param DeclEnd will receive the source location of the last token
  153. /// within this declaration.
  154. ///
  155. /// \param AS the access specifier associated with this
  156. /// declaration. Will be AS_none for namespace-scope declarations.
  157. ///
  158. /// \returns the new declaration.
  159. Decl *Parser::ParseSingleDeclarationAfterTemplate(
  160. DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
  161. ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
  162. ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
  163. assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
  164. "Template information required");
  165. if (Tok.is(tok::kw_static_assert)) {
  166. // A static_assert declaration may not be templated.
  167. Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
  168. << TemplateInfo.getSourceRange();
  169. // Parse the static_assert declaration to improve error recovery.
  170. return ParseStaticAssertDeclaration(DeclEnd);
  171. }
  172. if (Context == DeclaratorContext::MemberContext) {
  173. // We are parsing a member template.
  174. ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
  175. &DiagsFromTParams);
  176. return nullptr;
  177. }
  178. ParsedAttributesWithRange prefixAttrs(AttrFactory);
  179. MaybeParseCXX11Attributes(prefixAttrs);
  180. if (Tok.is(tok::kw_using)) {
  181. auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
  182. prefixAttrs);
  183. if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
  184. return nullptr;
  185. return usingDeclPtr.get().getSingleDecl();
  186. }
  187. // Parse the declaration specifiers, stealing any diagnostics from
  188. // the template parameters.
  189. ParsingDeclSpec DS(*this, &DiagsFromTParams);
  190. ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
  191. getDeclSpecContextFromDeclaratorContext(Context));
  192. if (Tok.is(tok::semi)) {
  193. ProhibitAttributes(prefixAttrs);
  194. DeclEnd = ConsumeToken();
  195. RecordDecl *AnonRecord = nullptr;
  196. Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
  197. getCurScope(), AS, DS,
  198. TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
  199. : MultiTemplateParamsArg(),
  200. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
  201. AnonRecord);
  202. assert(!AnonRecord &&
  203. "Anonymous unions/structs should not be valid with template");
  204. DS.complete(Decl);
  205. return Decl;
  206. }
  207. // Move the attributes from the prefix into the DS.
  208. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  209. ProhibitAttributes(prefixAttrs);
  210. else
  211. DS.takeAttributesFrom(prefixAttrs);
  212. // Parse the declarator.
  213. ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
  214. ParseDeclarator(DeclaratorInfo);
  215. // Error parsing the declarator?
  216. if (!DeclaratorInfo.hasName()) {
  217. // If so, skip until the semi-colon or a }.
  218. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  219. if (Tok.is(tok::semi))
  220. ConsumeToken();
  221. return nullptr;
  222. }
  223. llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
  224. return DeclaratorInfo.getIdentifier() != nullptr
  225. ? DeclaratorInfo.getIdentifier()->getName()
  226. : "<unknown>";
  227. });
  228. LateParsedAttrList LateParsedAttrs(true);
  229. if (DeclaratorInfo.isFunctionDeclarator())
  230. MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
  231. if (DeclaratorInfo.isFunctionDeclarator() &&
  232. isStartOfFunctionDefinition(DeclaratorInfo)) {
  233. // Function definitions are only allowed at file scope and in C++ classes.
  234. // The C++ inline method definition case is handled elsewhere, so we only
  235. // need to handle the file scope definition case.
  236. if (Context != DeclaratorContext::FileContext) {
  237. Diag(Tok, diag::err_function_definition_not_allowed);
  238. SkipMalformedDecl();
  239. return nullptr;
  240. }
  241. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  242. // Recover by ignoring the 'typedef'. This was probably supposed to be
  243. // the 'typename' keyword, which we should have already suggested adding
  244. // if it's appropriate.
  245. Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
  246. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  247. DS.ClearStorageClassSpecs();
  248. }
  249. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  250. if (DeclaratorInfo.getName().getKind() !=
  251. UnqualifiedIdKind::IK_TemplateId) {
  252. // If the declarator-id is not a template-id, issue a diagnostic and
  253. // recover by ignoring the 'template' keyword.
  254. Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
  255. return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
  256. &LateParsedAttrs);
  257. } else {
  258. SourceLocation LAngleLoc
  259. = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
  260. Diag(DeclaratorInfo.getIdentifierLoc(),
  261. diag::err_explicit_instantiation_with_definition)
  262. << SourceRange(TemplateInfo.TemplateLoc)
  263. << FixItHint::CreateInsertion(LAngleLoc, "<>");
  264. // Recover as if it were an explicit specialization.
  265. TemplateParameterLists FakedParamLists;
  266. FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
  267. 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
  268. LAngleLoc, nullptr));
  269. return ParseFunctionDefinition(
  270. DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
  271. /*isSpecialization=*/true,
  272. /*lastParameterListWasEmpty=*/true),
  273. &LateParsedAttrs);
  274. }
  275. }
  276. return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
  277. &LateParsedAttrs);
  278. }
  279. // Parse this declaration.
  280. Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
  281. TemplateInfo);
  282. if (Tok.is(tok::comma)) {
  283. Diag(Tok, diag::err_multiple_template_declarators)
  284. << (int)TemplateInfo.Kind;
  285. SkipUntil(tok::semi);
  286. return ThisDecl;
  287. }
  288. // Eat the semi colon after the declaration.
  289. ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
  290. if (LateParsedAttrs.size() > 0)
  291. ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
  292. DeclaratorInfo.complete(ThisDecl);
  293. return ThisDecl;
  294. }
  295. /// \brief Parse a single declaration that declares a concept.
  296. ///
  297. /// \param DeclEnd will receive the source location of the last token
  298. /// within this declaration.
  299. ///
  300. /// \returns the new declaration.
  301. Decl *
  302. Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
  303. SourceLocation &DeclEnd) {
  304. assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
  305. "Template information required");
  306. assert(Tok.is(tok::kw_concept) &&
  307. "ParseConceptDefinition must be called when at a 'concept' keyword");
  308. ConsumeToken(); // Consume 'concept'
  309. SourceLocation BoolKWLoc;
  310. if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
  311. Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) <<
  312. FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
  313. DiagnoseAndSkipCXX11Attributes();
  314. CXXScopeSpec SS;
  315. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  316. /*EnteringContext=*/false, /*MayBePseudoDestructor=*/nullptr,
  317. /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
  318. SS.isInvalid()) {
  319. SkipUntil(tok::semi);
  320. return nullptr;
  321. }
  322. if (SS.isNotEmpty())
  323. Diag(SS.getBeginLoc(),
  324. diag::err_concept_definition_not_identifier);
  325. UnqualifiedId Result;
  326. if (ParseUnqualifiedId(SS, /*EnteringContext=*/false,
  327. /*AllowDestructorName=*/false,
  328. /*AllowConstructorName=*/false,
  329. /*AllowDeductionGuide=*/false,
  330. /*ObjectType=*/ParsedType(), /*TemplateKWLoc=*/nullptr,
  331. Result)) {
  332. SkipUntil(tok::semi);
  333. return nullptr;
  334. }
  335. if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
  336. Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
  337. SkipUntil(tok::semi);
  338. return nullptr;
  339. }
  340. IdentifierInfo *Id = Result.Identifier;
  341. SourceLocation IdLoc = Result.getBeginLoc();
  342. DiagnoseAndSkipCXX11Attributes();
  343. if (!TryConsumeToken(tok::equal)) {
  344. Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
  345. SkipUntil(tok::semi);
  346. return nullptr;
  347. }
  348. ExprResult ConstraintExprResult =
  349. Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
  350. if (ConstraintExprResult.isInvalid()) {
  351. SkipUntil(tok::semi);
  352. return nullptr;
  353. }
  354. DeclEnd = Tok.getLocation();
  355. ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
  356. Expr *ConstraintExpr = ConstraintExprResult.get();
  357. return Actions.ActOnConceptDefinition(getCurScope(),
  358. *TemplateInfo.TemplateParams,
  359. Id, IdLoc, ConstraintExpr);
  360. }
  361. /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
  362. /// angle brackets. Depth is the depth of this template-parameter-list, which
  363. /// is the number of template headers directly enclosing this template header.
  364. /// TemplateParams is the current list of template parameters we're building.
  365. /// The template parameter we parse will be added to this list. LAngleLoc and
  366. /// RAngleLoc will receive the positions of the '<' and '>', respectively,
  367. /// that enclose this template parameter list.
  368. ///
  369. /// \returns true if an error occurred, false otherwise.
  370. bool Parser::ParseTemplateParameters(
  371. unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
  372. SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
  373. // Get the template parameter list.
  374. if (!TryConsumeToken(tok::less, LAngleLoc)) {
  375. Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
  376. return true;
  377. }
  378. // Try to parse the template parameter list.
  379. bool Failed = false;
  380. if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
  381. Failed = ParseTemplateParameterList(Depth, TemplateParams);
  382. if (Tok.is(tok::greatergreater)) {
  383. // No diagnostic required here: a template-parameter-list can only be
  384. // followed by a declaration or, for a template template parameter, the
  385. // 'class' keyword. Therefore, the second '>' will be diagnosed later.
  386. // This matters for elegant diagnosis of:
  387. // template<template<typename>> struct S;
  388. Tok.setKind(tok::greater);
  389. RAngleLoc = Tok.getLocation();
  390. Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
  391. } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
  392. Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
  393. return true;
  394. }
  395. return false;
  396. }
  397. /// ParseTemplateParameterList - Parse a template parameter list. If
  398. /// the parsing fails badly (i.e., closing bracket was left out), this
  399. /// will try to put the token stream in a reasonable position (closing
  400. /// a statement, etc.) and return false.
  401. ///
  402. /// template-parameter-list: [C++ temp]
  403. /// template-parameter
  404. /// template-parameter-list ',' template-parameter
  405. bool
  406. Parser::ParseTemplateParameterList(const unsigned Depth,
  407. SmallVectorImpl<NamedDecl*> &TemplateParams) {
  408. while (1) {
  409. if (NamedDecl *TmpParam
  410. = ParseTemplateParameter(Depth, TemplateParams.size())) {
  411. TemplateParams.push_back(TmpParam);
  412. } else {
  413. // If we failed to parse a template parameter, skip until we find
  414. // a comma or closing brace.
  415. SkipUntil(tok::comma, tok::greater, tok::greatergreater,
  416. StopAtSemi | StopBeforeMatch);
  417. }
  418. // Did we find a comma or the end of the template parameter list?
  419. if (Tok.is(tok::comma)) {
  420. ConsumeToken();
  421. } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
  422. // Don't consume this... that's done by template parser.
  423. break;
  424. } else {
  425. // Somebody probably forgot to close the template. Skip ahead and
  426. // try to get out of the expression. This error is currently
  427. // subsumed by whatever goes on in ParseTemplateParameter.
  428. Diag(Tok.getLocation(), diag::err_expected_comma_greater);
  429. SkipUntil(tok::comma, tok::greater, tok::greatergreater,
  430. StopAtSemi | StopBeforeMatch);
  431. return false;
  432. }
  433. }
  434. return true;
  435. }
  436. /// Determine whether the parser is at the start of a template
  437. /// type parameter.
  438. bool Parser::isStartOfTemplateTypeParameter() {
  439. if (Tok.is(tok::kw_class)) {
  440. // "class" may be the start of an elaborated-type-specifier or a
  441. // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
  442. switch (NextToken().getKind()) {
  443. case tok::equal:
  444. case tok::comma:
  445. case tok::greater:
  446. case tok::greatergreater:
  447. case tok::ellipsis:
  448. return true;
  449. case tok::identifier:
  450. // This may be either a type-parameter or an elaborated-type-specifier.
  451. // We have to look further.
  452. break;
  453. default:
  454. return false;
  455. }
  456. switch (GetLookAheadToken(2).getKind()) {
  457. case tok::equal:
  458. case tok::comma:
  459. case tok::greater:
  460. case tok::greatergreater:
  461. return true;
  462. default:
  463. return false;
  464. }
  465. }
  466. // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
  467. // ill-formed otherwise.
  468. if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
  469. return false;
  470. // C++ [temp.param]p2:
  471. // There is no semantic difference between class and typename in a
  472. // template-parameter. typename followed by an unqualified-id
  473. // names a template type parameter. typename followed by a
  474. // qualified-id denotes the type in a non-type
  475. // parameter-declaration.
  476. Token Next = NextToken();
  477. // If we have an identifier, skip over it.
  478. if (Next.getKind() == tok::identifier)
  479. Next = GetLookAheadToken(2);
  480. switch (Next.getKind()) {
  481. case tok::equal:
  482. case tok::comma:
  483. case tok::greater:
  484. case tok::greatergreater:
  485. case tok::ellipsis:
  486. return true;
  487. case tok::kw_typename:
  488. case tok::kw_typedef:
  489. case tok::kw_class:
  490. // These indicate that a comma was missed after a type parameter, not that
  491. // we have found a non-type parameter.
  492. return true;
  493. default:
  494. return false;
  495. }
  496. }
  497. /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
  498. ///
  499. /// template-parameter: [C++ temp.param]
  500. /// type-parameter
  501. /// parameter-declaration
  502. ///
  503. /// type-parameter: (see below)
  504. /// 'class' ...[opt] identifier[opt]
  505. /// 'class' identifier[opt] '=' type-id
  506. /// 'typename' ...[opt] identifier[opt]
  507. /// 'typename' identifier[opt] '=' type-id
  508. /// 'template' '<' template-parameter-list '>'
  509. /// 'class' ...[opt] identifier[opt]
  510. /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
  511. /// = id-expression
  512. NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
  513. if (isStartOfTemplateTypeParameter()) {
  514. // Is there just a typo in the input code? ('typedef' instead of 'typename')
  515. if (Tok.is(tok::kw_typedef)) {
  516. Diag(Tok.getLocation(), diag::err_expected_template_parameter);
  517. Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
  518. << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
  519. Tok.getLocation(), Tok.getEndLoc()),
  520. "typename");
  521. Tok.setKind(tok::kw_typename);
  522. }
  523. return ParseTypeParameter(Depth, Position);
  524. }
  525. if (Tok.is(tok::kw_template))
  526. return ParseTemplateTemplateParameter(Depth, Position);
  527. // If it's none of the above, then it must be a parameter declaration.
  528. // NOTE: This will pick up errors in the closure of the template parameter
  529. // list (e.g., template < ; Check here to implement >> style closures.
  530. return ParseNonTypeTemplateParameter(Depth, Position);
  531. }
  532. /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
  533. /// Other kinds of template parameters are parsed in
  534. /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
  535. ///
  536. /// type-parameter: [C++ temp.param]
  537. /// 'class' ...[opt][C++0x] identifier[opt]
  538. /// 'class' identifier[opt] '=' type-id
  539. /// 'typename' ...[opt][C++0x] identifier[opt]
  540. /// 'typename' identifier[opt] '=' type-id
  541. NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
  542. assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
  543. "A type-parameter starts with 'class' or 'typename'");
  544. // Consume the 'class' or 'typename' keyword.
  545. bool TypenameKeyword = Tok.is(tok::kw_typename);
  546. SourceLocation KeyLoc = ConsumeToken();
  547. // Grab the ellipsis (if given).
  548. SourceLocation EllipsisLoc;
  549. if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
  550. Diag(EllipsisLoc,
  551. getLangOpts().CPlusPlus11
  552. ? diag::warn_cxx98_compat_variadic_templates
  553. : diag::ext_variadic_templates);
  554. }
  555. // Grab the template parameter name (if given)
  556. SourceLocation NameLoc = Tok.getLocation();
  557. IdentifierInfo *ParamName = nullptr;
  558. if (Tok.is(tok::identifier)) {
  559. ParamName = Tok.getIdentifierInfo();
  560. ConsumeToken();
  561. } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  562. tok::greatergreater)) {
  563. // Unnamed template parameter. Don't have to do anything here, just
  564. // don't consume this token.
  565. } else {
  566. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  567. return nullptr;
  568. }
  569. // Recover from misplaced ellipsis.
  570. bool AlreadyHasEllipsis = EllipsisLoc.isValid();
  571. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  572. DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
  573. // Grab a default argument (if available).
  574. // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
  575. // we introduce the type parameter into the local scope.
  576. SourceLocation EqualLoc;
  577. ParsedType DefaultArg;
  578. if (TryConsumeToken(tok::equal, EqualLoc))
  579. DefaultArg = ParseTypeName(/*Range=*/nullptr,
  580. DeclaratorContext::TemplateTypeArgContext).get();
  581. return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
  582. KeyLoc, ParamName, NameLoc, Depth, Position,
  583. EqualLoc, DefaultArg);
  584. }
  585. /// ParseTemplateTemplateParameter - Handle the parsing of template
  586. /// template parameters.
  587. ///
  588. /// type-parameter: [C++ temp.param]
  589. /// 'template' '<' template-parameter-list '>' type-parameter-key
  590. /// ...[opt] identifier[opt]
  591. /// 'template' '<' template-parameter-list '>' type-parameter-key
  592. /// identifier[opt] = id-expression
  593. /// type-parameter-key:
  594. /// 'class'
  595. /// 'typename' [C++1z]
  596. NamedDecl *
  597. Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
  598. assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
  599. // Handle the template <...> part.
  600. SourceLocation TemplateLoc = ConsumeToken();
  601. SmallVector<NamedDecl*,8> TemplateParams;
  602. SourceLocation LAngleLoc, RAngleLoc;
  603. {
  604. ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
  605. if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
  606. RAngleLoc)) {
  607. return nullptr;
  608. }
  609. }
  610. // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
  611. // Generate a meaningful error if the user forgot to put class before the
  612. // identifier, comma, or greater. Provide a fixit if the identifier, comma,
  613. // or greater appear immediately or after 'struct'. In the latter case,
  614. // replace the keyword with 'class'.
  615. if (!TryConsumeToken(tok::kw_class)) {
  616. bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
  617. const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
  618. if (Tok.is(tok::kw_typename)) {
  619. Diag(Tok.getLocation(),
  620. getLangOpts().CPlusPlus17
  621. ? diag::warn_cxx14_compat_template_template_param_typename
  622. : diag::ext_template_template_param_typename)
  623. << (!getLangOpts().CPlusPlus17
  624. ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
  625. : FixItHint());
  626. } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
  627. tok::greatergreater, tok::ellipsis)) {
  628. Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
  629. << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
  630. : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
  631. } else
  632. Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
  633. if (Replace)
  634. ConsumeToken();
  635. }
  636. // Parse the ellipsis, if given.
  637. SourceLocation EllipsisLoc;
  638. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  639. Diag(EllipsisLoc,
  640. getLangOpts().CPlusPlus11
  641. ? diag::warn_cxx98_compat_variadic_templates
  642. : diag::ext_variadic_templates);
  643. // Get the identifier, if given.
  644. SourceLocation NameLoc = Tok.getLocation();
  645. IdentifierInfo *ParamName = nullptr;
  646. if (Tok.is(tok::identifier)) {
  647. ParamName = Tok.getIdentifierInfo();
  648. ConsumeToken();
  649. } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  650. tok::greatergreater)) {
  651. // Unnamed template parameter. Don't have to do anything here, just
  652. // don't consume this token.
  653. } else {
  654. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  655. return nullptr;
  656. }
  657. // Recover from misplaced ellipsis.
  658. bool AlreadyHasEllipsis = EllipsisLoc.isValid();
  659. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  660. DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
  661. TemplateParameterList *ParamList =
  662. Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
  663. TemplateLoc, LAngleLoc,
  664. TemplateParams,
  665. RAngleLoc, nullptr);
  666. // Grab a default argument (if available).
  667. // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
  668. // we introduce the template parameter into the local scope.
  669. SourceLocation EqualLoc;
  670. ParsedTemplateArgument DefaultArg;
  671. if (TryConsumeToken(tok::equal, EqualLoc)) {
  672. DefaultArg = ParseTemplateTemplateArgument();
  673. if (DefaultArg.isInvalid()) {
  674. Diag(Tok.getLocation(),
  675. diag::err_default_template_template_parameter_not_template);
  676. SkipUntil(tok::comma, tok::greater, tok::greatergreater,
  677. StopAtSemi | StopBeforeMatch);
  678. }
  679. }
  680. return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
  681. ParamList, EllipsisLoc,
  682. ParamName, NameLoc, Depth,
  683. Position, EqualLoc, DefaultArg);
  684. }
  685. /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
  686. /// template parameters (e.g., in "template<int Size> class array;").
  687. ///
  688. /// template-parameter:
  689. /// ...
  690. /// parameter-declaration
  691. NamedDecl *
  692. Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
  693. // Parse the declaration-specifiers (i.e., the type).
  694. // FIXME: The type should probably be restricted in some way... Not all
  695. // declarators (parts of declarators?) are accepted for parameters.
  696. DeclSpec DS(AttrFactory);
  697. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
  698. DeclSpecContext::DSC_template_param);
  699. // Parse this as a typename.
  700. Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
  701. ParseDeclarator(ParamDecl);
  702. if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
  703. Diag(Tok.getLocation(), diag::err_expected_template_parameter);
  704. return nullptr;
  705. }
  706. // Recover from misplaced ellipsis.
  707. SourceLocation EllipsisLoc;
  708. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  709. DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
  710. // If there is a default value, parse it.
  711. // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
  712. // we introduce the template parameter into the local scope.
  713. SourceLocation EqualLoc;
  714. ExprResult DefaultArg;
  715. if (TryConsumeToken(tok::equal, EqualLoc)) {
  716. // C++ [temp.param]p15:
  717. // When parsing a default template-argument for a non-type
  718. // template-parameter, the first non-nested > is taken as the
  719. // end of the template-parameter-list rather than a greater-than
  720. // operator.
  721. GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
  722. EnterExpressionEvaluationContext ConstantEvaluated(
  723. Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  724. DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
  725. if (DefaultArg.isInvalid())
  726. SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
  727. }
  728. // Create the parameter.
  729. return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
  730. Depth, Position, EqualLoc,
  731. DefaultArg.get());
  732. }
  733. void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
  734. SourceLocation CorrectLoc,
  735. bool AlreadyHasEllipsis,
  736. bool IdentifierHasName) {
  737. FixItHint Insertion;
  738. if (!AlreadyHasEllipsis)
  739. Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
  740. Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
  741. << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
  742. << !IdentifierHasName;
  743. }
  744. void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
  745. Declarator &D) {
  746. assert(EllipsisLoc.isValid());
  747. bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
  748. if (!AlreadyHasEllipsis)
  749. D.setEllipsisLoc(EllipsisLoc);
  750. DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
  751. AlreadyHasEllipsis, D.hasName());
  752. }
  753. /// Parses a '>' at the end of a template list.
  754. ///
  755. /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
  756. /// to determine if these tokens were supposed to be a '>' followed by
  757. /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
  758. ///
  759. /// \param RAngleLoc the location of the consumed '>'.
  760. ///
  761. /// \param ConsumeLastToken if true, the '>' is consumed.
  762. ///
  763. /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
  764. /// type parameter or type argument list, rather than a C++ template parameter
  765. /// or argument list.
  766. ///
  767. /// \returns true, if current token does not start with '>', false otherwise.
  768. bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
  769. bool ConsumeLastToken,
  770. bool ObjCGenericList) {
  771. // What will be left once we've consumed the '>'.
  772. tok::TokenKind RemainingToken;
  773. const char *ReplacementStr = "> >";
  774. bool MergeWithNextToken = false;
  775. switch (Tok.getKind()) {
  776. default:
  777. Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
  778. return true;
  779. case tok::greater:
  780. // Determine the location of the '>' token. Only consume this token
  781. // if the caller asked us to.
  782. RAngleLoc = Tok.getLocation();
  783. if (ConsumeLastToken)
  784. ConsumeToken();
  785. return false;
  786. case tok::greatergreater:
  787. RemainingToken = tok::greater;
  788. break;
  789. case tok::greatergreatergreater:
  790. RemainingToken = tok::greatergreater;
  791. break;
  792. case tok::greaterequal:
  793. RemainingToken = tok::equal;
  794. ReplacementStr = "> =";
  795. // Join two adjacent '=' tokens into one, for cases like:
  796. // void (*p)() = f<int>;
  797. // return f<int>==p;
  798. if (NextToken().is(tok::equal) &&
  799. areTokensAdjacent(Tok, NextToken())) {
  800. RemainingToken = tok::equalequal;
  801. MergeWithNextToken = true;
  802. }
  803. break;
  804. case tok::greatergreaterequal:
  805. RemainingToken = tok::greaterequal;
  806. break;
  807. }
  808. // This template-id is terminated by a token that starts with a '>'.
  809. // Outside C++11 and Objective-C, this is now error recovery.
  810. //
  811. // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
  812. // extend that treatment to also apply to the '>>>' token.
  813. //
  814. // Objective-C allows this in its type parameter / argument lists.
  815. SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
  816. SourceLocation TokLoc = Tok.getLocation();
  817. Token Next = NextToken();
  818. // Whether splitting the current token after the '>' would undesirably result
  819. // in the remaining token pasting with the token after it. This excludes the
  820. // MergeWithNextToken cases, which we've already handled.
  821. bool PreventMergeWithNextToken =
  822. (RemainingToken == tok::greater ||
  823. RemainingToken == tok::greatergreater) &&
  824. (Next.isOneOf(tok::greater, tok::greatergreater,
  825. tok::greatergreatergreater, tok::equal, tok::greaterequal,
  826. tok::greatergreaterequal, tok::equalequal)) &&
  827. areTokensAdjacent(Tok, Next);
  828. // Diagnose this situation as appropriate.
  829. if (!ObjCGenericList) {
  830. // The source range of the replaced token(s).
  831. CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
  832. TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
  833. getLangOpts()));
  834. // A hint to put a space between the '>>'s. In order to make the hint as
  835. // clear as possible, we include the characters either side of the space in
  836. // the replacement, rather than just inserting a space at SecondCharLoc.
  837. FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
  838. ReplacementStr);
  839. // A hint to put another space after the token, if it would otherwise be
  840. // lexed differently.
  841. FixItHint Hint2;
  842. if (PreventMergeWithNextToken)
  843. Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
  844. unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
  845. if (getLangOpts().CPlusPlus11 &&
  846. (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
  847. DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
  848. else if (Tok.is(tok::greaterequal))
  849. DiagId = diag::err_right_angle_bracket_equal_needs_space;
  850. Diag(TokLoc, DiagId) << Hint1 << Hint2;
  851. }
  852. // Find the "length" of the resulting '>' token. This is not always 1, as it
  853. // can contain escaped newlines.
  854. unsigned GreaterLength = Lexer::getTokenPrefixLength(
  855. TokLoc, 1, PP.getSourceManager(), getLangOpts());
  856. // Annotate the source buffer to indicate that we split the token after the
  857. // '>'. This allows us to properly find the end of, and extract the spelling
  858. // of, the '>' token later.
  859. RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
  860. // Strip the initial '>' from the token.
  861. bool CachingTokens = PP.IsPreviousCachedToken(Tok);
  862. Token Greater = Tok;
  863. Greater.setLocation(RAngleLoc);
  864. Greater.setKind(tok::greater);
  865. Greater.setLength(GreaterLength);
  866. unsigned OldLength = Tok.getLength();
  867. if (MergeWithNextToken) {
  868. ConsumeToken();
  869. OldLength += Tok.getLength();
  870. }
  871. Tok.setKind(RemainingToken);
  872. Tok.setLength(OldLength - GreaterLength);
  873. // Split the second token if lexing it normally would lex a different token
  874. // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
  875. SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
  876. if (PreventMergeWithNextToken)
  877. AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
  878. Tok.setLocation(AfterGreaterLoc);
  879. // Update the token cache to match what we just did if necessary.
  880. if (CachingTokens) {
  881. // If the previous cached token is being merged, delete it.
  882. if (MergeWithNextToken)
  883. PP.ReplacePreviousCachedToken({});
  884. if (ConsumeLastToken)
  885. PP.ReplacePreviousCachedToken({Greater, Tok});
  886. else
  887. PP.ReplacePreviousCachedToken({Greater});
  888. }
  889. if (ConsumeLastToken) {
  890. PrevTokLocation = RAngleLoc;
  891. } else {
  892. PrevTokLocation = TokBeforeGreaterLoc;
  893. PP.EnterToken(Tok, /*IsReinject=*/true);
  894. Tok = Greater;
  895. }
  896. return false;
  897. }
  898. /// Parses a template-id that after the template name has
  899. /// already been parsed.
  900. ///
  901. /// This routine takes care of parsing the enclosed template argument
  902. /// list ('<' template-parameter-list [opt] '>') and placing the
  903. /// results into a form that can be transferred to semantic analysis.
  904. ///
  905. /// \param ConsumeLastToken if true, then we will consume the last
  906. /// token that forms the template-id. Otherwise, we will leave the
  907. /// last token in the stream (e.g., so that it can be replaced with an
  908. /// annotation token).
  909. bool
  910. Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
  911. SourceLocation &LAngleLoc,
  912. TemplateArgList &TemplateArgs,
  913. SourceLocation &RAngleLoc) {
  914. assert(Tok.is(tok::less) && "Must have already parsed the template-name");
  915. // Consume the '<'.
  916. LAngleLoc = ConsumeToken();
  917. // Parse the optional template-argument-list.
  918. bool Invalid = false;
  919. {
  920. GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
  921. if (!Tok.isOneOf(tok::greater, tok::greatergreater,
  922. tok::greatergreatergreater, tok::greaterequal,
  923. tok::greatergreaterequal))
  924. Invalid = ParseTemplateArgumentList(TemplateArgs);
  925. if (Invalid) {
  926. // Try to find the closing '>'.
  927. if (ConsumeLastToken)
  928. SkipUntil(tok::greater, StopAtSemi);
  929. else
  930. SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
  931. return true;
  932. }
  933. }
  934. return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
  935. /*ObjCGenericList=*/false);
  936. }
  937. /// Replace the tokens that form a simple-template-id with an
  938. /// annotation token containing the complete template-id.
  939. ///
  940. /// The first token in the stream must be the name of a template that
  941. /// is followed by a '<'. This routine will parse the complete
  942. /// simple-template-id and replace the tokens with a single annotation
  943. /// token with one of two different kinds: if the template-id names a
  944. /// type (and \p AllowTypeAnnotation is true), the annotation token is
  945. /// a type annotation that includes the optional nested-name-specifier
  946. /// (\p SS). Otherwise, the annotation token is a template-id
  947. /// annotation that does not include the optional
  948. /// nested-name-specifier.
  949. ///
  950. /// \param Template the declaration of the template named by the first
  951. /// token (an identifier), as returned from \c Action::isTemplateName().
  952. ///
  953. /// \param TNK the kind of template that \p Template
  954. /// refers to, as returned from \c Action::isTemplateName().
  955. ///
  956. /// \param SS if non-NULL, the nested-name-specifier that precedes
  957. /// this template name.
  958. ///
  959. /// \param TemplateKWLoc if valid, specifies that this template-id
  960. /// annotation was preceded by the 'template' keyword and gives the
  961. /// location of that keyword. If invalid (the default), then this
  962. /// template-id was not preceded by a 'template' keyword.
  963. ///
  964. /// \param AllowTypeAnnotation if true (the default), then a
  965. /// simple-template-id that refers to a class template, template
  966. /// template parameter, or other template that produces a type will be
  967. /// replaced with a type annotation token. Otherwise, the
  968. /// simple-template-id is always replaced with a template-id
  969. /// annotation token.
  970. ///
  971. /// If an unrecoverable parse error occurs and no annotation token can be
  972. /// formed, this function returns true.
  973. ///
  974. bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
  975. CXXScopeSpec &SS,
  976. SourceLocation TemplateKWLoc,
  977. UnqualifiedId &TemplateName,
  978. bool AllowTypeAnnotation) {
  979. assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
  980. assert(Template && Tok.is(tok::less) &&
  981. "Parser isn't at the beginning of a template-id");
  982. // Consume the template-name.
  983. SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
  984. // Parse the enclosed template argument list.
  985. SourceLocation LAngleLoc, RAngleLoc;
  986. TemplateArgList TemplateArgs;
  987. bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
  988. TemplateArgs,
  989. RAngleLoc);
  990. if (Invalid) {
  991. // If we failed to parse the template ID but skipped ahead to a >, we're not
  992. // going to be able to form a token annotation. Eat the '>' if present.
  993. TryConsumeToken(tok::greater);
  994. // FIXME: Annotate the token stream so we don't produce the same errors
  995. // again if we're doing this annotation as part of a tentative parse.
  996. return true;
  997. }
  998. ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
  999. // Build the annotation token.
  1000. if (TNK == TNK_Type_template && AllowTypeAnnotation) {
  1001. TypeResult Type = Actions.ActOnTemplateIdType(
  1002. getCurScope(), SS, TemplateKWLoc, Template, TemplateName.Identifier,
  1003. TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
  1004. if (Type.isInvalid()) {
  1005. // If we failed to parse the template ID but skipped ahead to a >, we're
  1006. // not going to be able to form a token annotation. Eat the '>' if
  1007. // present.
  1008. TryConsumeToken(tok::greater);
  1009. // FIXME: Annotate the token stream so we don't produce the same errors
  1010. // again if we're doing this annotation as part of a tentative parse.
  1011. return true;
  1012. }
  1013. Tok.setKind(tok::annot_typename);
  1014. setTypeAnnotation(Tok, Type.get());
  1015. if (SS.isNotEmpty())
  1016. Tok.setLocation(SS.getBeginLoc());
  1017. else if (TemplateKWLoc.isValid())
  1018. Tok.setLocation(TemplateKWLoc);
  1019. else
  1020. Tok.setLocation(TemplateNameLoc);
  1021. } else {
  1022. // Build a template-id annotation token that can be processed
  1023. // later.
  1024. Tok.setKind(tok::annot_template_id);
  1025. IdentifierInfo *TemplateII =
  1026. TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
  1027. ? TemplateName.Identifier
  1028. : nullptr;
  1029. OverloadedOperatorKind OpKind =
  1030. TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
  1031. ? OO_None
  1032. : TemplateName.OperatorFunctionId.Operator;
  1033. TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
  1034. SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
  1035. LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
  1036. Tok.setAnnotationValue(TemplateId);
  1037. if (TemplateKWLoc.isValid())
  1038. Tok.setLocation(TemplateKWLoc);
  1039. else
  1040. Tok.setLocation(TemplateNameLoc);
  1041. }
  1042. // Common fields for the annotation token
  1043. Tok.setAnnotationEndLoc(RAngleLoc);
  1044. // In case the tokens were cached, have Preprocessor replace them with the
  1045. // annotation token.
  1046. PP.AnnotateCachedTokens(Tok);
  1047. return false;
  1048. }
  1049. /// Replaces a template-id annotation token with a type
  1050. /// annotation token.
  1051. ///
  1052. /// If there was a failure when forming the type from the template-id,
  1053. /// a type annotation token will still be created, but will have a
  1054. /// NULL type pointer to signify an error.
  1055. ///
  1056. /// \param IsClassName Is this template-id appearing in a context where we
  1057. /// know it names a class, such as in an elaborated-type-specifier or
  1058. /// base-specifier? ('typename' and 'template' are unneeded and disallowed
  1059. /// in those contexts.)
  1060. void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
  1061. assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
  1062. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1063. assert((TemplateId->Kind == TNK_Type_template ||
  1064. TemplateId->Kind == TNK_Dependent_template_name ||
  1065. TemplateId->Kind == TNK_Undeclared_template) &&
  1066. "Only works for type and dependent templates");
  1067. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  1068. TemplateId->NumArgs);
  1069. TypeResult Type
  1070. = Actions.ActOnTemplateIdType(getCurScope(),
  1071. TemplateId->SS,
  1072. TemplateId->TemplateKWLoc,
  1073. TemplateId->Template,
  1074. TemplateId->Name,
  1075. TemplateId->TemplateNameLoc,
  1076. TemplateId->LAngleLoc,
  1077. TemplateArgsPtr,
  1078. TemplateId->RAngleLoc,
  1079. /*IsCtorOrDtorName*/false,
  1080. IsClassName);
  1081. // Create the new "type" annotation token.
  1082. Tok.setKind(tok::annot_typename);
  1083. setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
  1084. if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
  1085. Tok.setLocation(TemplateId->SS.getBeginLoc());
  1086. // End location stays the same
  1087. // Replace the template-id annotation token, and possible the scope-specifier
  1088. // that precedes it, with the typename annotation token.
  1089. PP.AnnotateCachedTokens(Tok);
  1090. }
  1091. /// Determine whether the given token can end a template argument.
  1092. static bool isEndOfTemplateArgument(Token Tok) {
  1093. return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
  1094. }
  1095. /// Parse a C++ template template argument.
  1096. ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
  1097. if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
  1098. !Tok.is(tok::annot_cxxscope))
  1099. return ParsedTemplateArgument();
  1100. // C++0x [temp.arg.template]p1:
  1101. // A template-argument for a template template-parameter shall be the name
  1102. // of a class template or an alias template, expressed as id-expression.
  1103. //
  1104. // We parse an id-expression that refers to a class template or alias
  1105. // template. The grammar we parse is:
  1106. //
  1107. // nested-name-specifier[opt] template[opt] identifier ...[opt]
  1108. //
  1109. // followed by a token that terminates a template argument, such as ',',
  1110. // '>', or (in some cases) '>>'.
  1111. CXXScopeSpec SS; // nested-name-specifier, if present
  1112. ParseOptionalCXXScopeSpecifier(SS, nullptr,
  1113. /*EnteringContext=*/false);
  1114. ParsedTemplateArgument Result;
  1115. SourceLocation EllipsisLoc;
  1116. if (SS.isSet() && Tok.is(tok::kw_template)) {
  1117. // Parse the optional 'template' keyword following the
  1118. // nested-name-specifier.
  1119. SourceLocation TemplateKWLoc = ConsumeToken();
  1120. if (Tok.is(tok::identifier)) {
  1121. // We appear to have a dependent template name.
  1122. UnqualifiedId Name;
  1123. Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1124. ConsumeToken(); // the identifier
  1125. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  1126. // If the next token signals the end of a template argument,
  1127. // then we have a dependent template name that could be a template
  1128. // template argument.
  1129. TemplateTy Template;
  1130. if (isEndOfTemplateArgument(Tok) &&
  1131. Actions.ActOnDependentTemplateName(
  1132. getCurScope(), SS, TemplateKWLoc, Name,
  1133. /*ObjectType=*/nullptr,
  1134. /*EnteringContext=*/false, Template))
  1135. Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
  1136. }
  1137. } else if (Tok.is(tok::identifier)) {
  1138. // We may have a (non-dependent) template name.
  1139. TemplateTy Template;
  1140. UnqualifiedId Name;
  1141. Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1142. ConsumeToken(); // the identifier
  1143. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  1144. if (isEndOfTemplateArgument(Tok)) {
  1145. bool MemberOfUnknownSpecialization;
  1146. TemplateNameKind TNK = Actions.isTemplateName(
  1147. getCurScope(), SS,
  1148. /*hasTemplateKeyword=*/false, Name,
  1149. /*ObjectType=*/nullptr,
  1150. /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
  1151. if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
  1152. // We have an id-expression that refers to a class template or
  1153. // (C++0x) alias template.
  1154. Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
  1155. }
  1156. }
  1157. }
  1158. // If this is a pack expansion, build it as such.
  1159. if (EllipsisLoc.isValid() && !Result.isInvalid())
  1160. Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
  1161. return Result;
  1162. }
  1163. /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
  1164. ///
  1165. /// template-argument: [C++ 14.2]
  1166. /// constant-expression
  1167. /// type-id
  1168. /// id-expression
  1169. ParsedTemplateArgument Parser::ParseTemplateArgument() {
  1170. // C++ [temp.arg]p2:
  1171. // In a template-argument, an ambiguity between a type-id and an
  1172. // expression is resolved to a type-id, regardless of the form of
  1173. // the corresponding template-parameter.
  1174. //
  1175. // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
  1176. // up and annotate an identifier as an id-expression during disambiguation,
  1177. // so enter the appropriate context for a constant expression template
  1178. // argument before trying to disambiguate.
  1179. EnterExpressionEvaluationContext EnterConstantEvaluated(
  1180. Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
  1181. /*LambdaContextDecl=*/nullptr,
  1182. /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
  1183. if (isCXXTypeId(TypeIdAsTemplateArgument)) {
  1184. TypeResult TypeArg = ParseTypeName(
  1185. /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
  1186. return Actions.ActOnTemplateTypeArgument(TypeArg);
  1187. }
  1188. // Try to parse a template template argument.
  1189. {
  1190. TentativeParsingAction TPA(*this);
  1191. ParsedTemplateArgument TemplateTemplateArgument
  1192. = ParseTemplateTemplateArgument();
  1193. if (!TemplateTemplateArgument.isInvalid()) {
  1194. TPA.Commit();
  1195. return TemplateTemplateArgument;
  1196. }
  1197. // Revert this tentative parse to parse a non-type template argument.
  1198. TPA.Revert();
  1199. }
  1200. // Parse a non-type template argument.
  1201. SourceLocation Loc = Tok.getLocation();
  1202. ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
  1203. if (ExprArg.isInvalid() || !ExprArg.get())
  1204. return ParsedTemplateArgument();
  1205. return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
  1206. ExprArg.get(), Loc);
  1207. }
  1208. /// ParseTemplateArgumentList - Parse a C++ template-argument-list
  1209. /// (C++ [temp.names]). Returns true if there was an error.
  1210. ///
  1211. /// template-argument-list: [C++ 14.2]
  1212. /// template-argument
  1213. /// template-argument-list ',' template-argument
  1214. bool
  1215. Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
  1216. ColonProtectionRAIIObject ColonProtection(*this, false);
  1217. do {
  1218. ParsedTemplateArgument Arg = ParseTemplateArgument();
  1219. SourceLocation EllipsisLoc;
  1220. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  1221. Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
  1222. if (Arg.isInvalid()) {
  1223. SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
  1224. return true;
  1225. }
  1226. // Save this template argument.
  1227. TemplateArgs.push_back(Arg);
  1228. // If the next token is a comma, consume it and keep reading
  1229. // arguments.
  1230. } while (TryConsumeToken(tok::comma));
  1231. return false;
  1232. }
  1233. /// Parse a C++ explicit template instantiation
  1234. /// (C++ [temp.explicit]).
  1235. ///
  1236. /// explicit-instantiation:
  1237. /// 'extern' [opt] 'template' declaration
  1238. ///
  1239. /// Note that the 'extern' is a GNU extension and C++11 feature.
  1240. Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
  1241. SourceLocation ExternLoc,
  1242. SourceLocation TemplateLoc,
  1243. SourceLocation &DeclEnd,
  1244. ParsedAttributes &AccessAttrs,
  1245. AccessSpecifier AS) {
  1246. // This isn't really required here.
  1247. ParsingDeclRAIIObject
  1248. ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
  1249. return ParseSingleDeclarationAfterTemplate(
  1250. Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
  1251. ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
  1252. }
  1253. SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
  1254. if (TemplateParams)
  1255. return getTemplateParamsRange(TemplateParams->data(),
  1256. TemplateParams->size());
  1257. SourceRange R(TemplateLoc);
  1258. if (ExternLoc.isValid())
  1259. R.setBegin(ExternLoc);
  1260. return R;
  1261. }
  1262. void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
  1263. ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
  1264. }
  1265. /// Late parse a C++ function template in Microsoft mode.
  1266. void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
  1267. if (!LPT.D)
  1268. return;
  1269. // Get the FunctionDecl.
  1270. FunctionDecl *FunD = LPT.D->getAsFunction();
  1271. // Track template parameter depth.
  1272. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  1273. // To restore the context after late parsing.
  1274. Sema::ContextRAII GlobalSavedContext(
  1275. Actions, Actions.Context.getTranslationUnitDecl());
  1276. SmallVector<ParseScope*, 4> TemplateParamScopeStack;
  1277. // Get the list of DeclContexts to reenter. For inline methods, we only want
  1278. // to push the DeclContext of the outermost class. This matches the way the
  1279. // parser normally parses bodies of inline methods when the outermost class is
  1280. // complete.
  1281. struct ContainingDC {
  1282. ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
  1283. llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
  1284. DeclContext *getDC() { return Pair.getPointer(); }
  1285. bool shouldPushDC() { return Pair.getInt(); }
  1286. };
  1287. SmallVector<ContainingDC, 4> DeclContextsToReenter;
  1288. DeclContext *DD = FunD;
  1289. DeclContext *NextContaining = Actions.getContainingDC(DD);
  1290. while (DD && !DD->isTranslationUnit()) {
  1291. bool ShouldPush = DD == NextContaining;
  1292. DeclContextsToReenter.push_back({DD, ShouldPush});
  1293. if (ShouldPush)
  1294. NextContaining = Actions.getContainingDC(DD);
  1295. DD = DD->getLexicalParent();
  1296. }
  1297. // Reenter template scopes from outermost to innermost.
  1298. for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
  1299. TemplateParamScopeStack.push_back(
  1300. new ParseScope(this, Scope::TemplateParamScope));
  1301. unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
  1302. getCurScope(), cast<Decl>(CDC.getDC()));
  1303. CurTemplateDepthTracker.addDepth(NumParamLists);
  1304. if (CDC.shouldPushDC()) {
  1305. TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
  1306. Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
  1307. }
  1308. }
  1309. assert(!LPT.Toks.empty() && "Empty body!");
  1310. // Append the current token at the end of the new token stream so that it
  1311. // doesn't get lost.
  1312. LPT.Toks.push_back(Tok);
  1313. PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
  1314. // Consume the previously pushed token.
  1315. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  1316. assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
  1317. "Inline method not starting with '{', ':' or 'try'");
  1318. // Parse the method body. Function body parsing code is similar enough
  1319. // to be re-used for method bodies as well.
  1320. ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
  1321. Scope::CompoundStmtScope);
  1322. // Recreate the containing function DeclContext.
  1323. Sema::ContextRAII FunctionSavedContext(Actions,
  1324. Actions.getContainingDC(FunD));
  1325. Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
  1326. if (Tok.is(tok::kw_try)) {
  1327. ParseFunctionTryBlock(LPT.D, FnScope);
  1328. } else {
  1329. if (Tok.is(tok::colon))
  1330. ParseConstructorInitializer(LPT.D);
  1331. else
  1332. Actions.ActOnDefaultCtorInitializers(LPT.D);
  1333. if (Tok.is(tok::l_brace)) {
  1334. assert((!isa<FunctionTemplateDecl>(LPT.D) ||
  1335. cast<FunctionTemplateDecl>(LPT.D)
  1336. ->getTemplateParameters()
  1337. ->getDepth() == TemplateParameterDepth - 1) &&
  1338. "TemplateParameterDepth should be greater than the depth of "
  1339. "current template being instantiated!");
  1340. ParseFunctionStatementBody(LPT.D, FnScope);
  1341. Actions.UnmarkAsLateParsedTemplate(FunD);
  1342. } else
  1343. Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
  1344. }
  1345. // Exit scopes.
  1346. FnScope.Exit();
  1347. SmallVectorImpl<ParseScope *>::reverse_iterator I =
  1348. TemplateParamScopeStack.rbegin();
  1349. for (; I != TemplateParamScopeStack.rend(); ++I)
  1350. delete *I;
  1351. }
  1352. /// Lex a delayed template function for late parsing.
  1353. void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
  1354. tok::TokenKind kind = Tok.getKind();
  1355. if (!ConsumeAndStoreFunctionPrologue(Toks)) {
  1356. // Consume everything up to (and including) the matching right brace.
  1357. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1358. }
  1359. // If we're in a function-try-block, we need to store all the catch blocks.
  1360. if (kind == tok::kw_try) {
  1361. while (Tok.is(tok::kw_catch)) {
  1362. ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
  1363. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1364. }
  1365. }
  1366. }
  1367. /// We've parsed something that could plausibly be intended to be a template
  1368. /// name (\p LHS) followed by a '<' token, and the following code can't possibly
  1369. /// be an expression. Determine if this is likely to be a template-id and if so,
  1370. /// diagnose it.
  1371. bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
  1372. TentativeParsingAction TPA(*this);
  1373. // FIXME: We could look at the token sequence in a lot more detail here.
  1374. if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
  1375. StopAtSemi | StopBeforeMatch)) {
  1376. TPA.Commit();
  1377. SourceLocation Greater;
  1378. ParseGreaterThanInTemplateList(Greater, true, false);
  1379. Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
  1380. Less, Greater);
  1381. return true;
  1382. }
  1383. // There's no matching '>' token, this probably isn't supposed to be
  1384. // interpreted as a template-id. Parse it as an (ill-formed) comparison.
  1385. TPA.Revert();
  1386. return false;
  1387. }
  1388. void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
  1389. assert(Tok.is(tok::less) && "not at a potential angle bracket");
  1390. bool DependentTemplateName = false;
  1391. if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
  1392. DependentTemplateName))
  1393. return;
  1394. // OK, this might be a name that the user intended to be parsed as a
  1395. // template-name, followed by a '<' token. Check for some easy cases.
  1396. // If we have potential_template<>, then it's supposed to be a template-name.
  1397. if (NextToken().is(tok::greater) ||
  1398. (getLangOpts().CPlusPlus11 &&
  1399. NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
  1400. SourceLocation Less = ConsumeToken();
  1401. SourceLocation Greater;
  1402. ParseGreaterThanInTemplateList(Greater, true, false);
  1403. Actions.diagnoseExprIntendedAsTemplateName(
  1404. getCurScope(), PotentialTemplateName, Less, Greater);
  1405. // FIXME: Perform error recovery.
  1406. PotentialTemplateName = ExprError();
  1407. return;
  1408. }
  1409. // If we have 'potential_template<type-id', assume it's supposed to be a
  1410. // template-name if there's a matching '>' later on.
  1411. {
  1412. // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
  1413. TentativeParsingAction TPA(*this);
  1414. SourceLocation Less = ConsumeToken();
  1415. if (isTypeIdUnambiguously() &&
  1416. diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
  1417. TPA.Commit();
  1418. // FIXME: Perform error recovery.
  1419. PotentialTemplateName = ExprError();
  1420. return;
  1421. }
  1422. TPA.Revert();
  1423. }
  1424. // Otherwise, remember that we saw this in case we see a potentially-matching
  1425. // '>' token later on.
  1426. AngleBracketTracker::Priority Priority =
  1427. (DependentTemplateName ? AngleBracketTracker::DependentName
  1428. : AngleBracketTracker::PotentialTypo) |
  1429. (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
  1430. : AngleBracketTracker::NoSpaceBeforeLess);
  1431. AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
  1432. Priority);
  1433. }
  1434. bool Parser::checkPotentialAngleBracketDelimiter(
  1435. const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
  1436. // If a comma in an expression context is followed by a type that can be a
  1437. // template argument and cannot be an expression, then this is ill-formed,
  1438. // but might be intended to be part of a template-id.
  1439. if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
  1440. diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
  1441. AngleBrackets.clear(*this);
  1442. return true;
  1443. }
  1444. // If a context that looks like a template-id is followed by '()', then
  1445. // this is ill-formed, but might be intended to be a template-id
  1446. // followed by '()'.
  1447. if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
  1448. NextToken().is(tok::r_paren)) {
  1449. Actions.diagnoseExprIntendedAsTemplateName(
  1450. getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
  1451. OpToken.getLocation());
  1452. AngleBrackets.clear(*this);
  1453. return true;
  1454. }
  1455. // After a '>' (etc), we're no longer potentially in a construct that's
  1456. // intended to be treated as a template-id.
  1457. if (OpToken.is(tok::greater) ||
  1458. (getLangOpts().CPlusPlus11 &&
  1459. OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
  1460. AngleBrackets.clear(*this);
  1461. return false;
  1462. }