ParseTemplate.cpp 56 KB

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