ParseTemplate.cpp 57 KB

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