ParseTemplate.cpp 71 KB

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