ParseTemplate.cpp 73 KB

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