ParseTemplate.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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. Diag(EllipsisLoc,
  463. getLangOpts().CPlusPlus11
  464. ? diag::warn_cxx98_compat_variadic_templates
  465. : diag::ext_variadic_templates);
  466. }
  467. // Grab the template parameter name (if given)
  468. SourceLocation NameLoc;
  469. IdentifierInfo *ParamName = nullptr;
  470. if (Tok.is(tok::identifier)) {
  471. ParamName = Tok.getIdentifierInfo();
  472. NameLoc = ConsumeToken();
  473. } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  474. tok::greatergreater)) {
  475. // Unnamed template parameter. Don't have to do anything here, just
  476. // don't consume this token.
  477. } else {
  478. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  479. return nullptr;
  480. }
  481. // Recover from misplaced ellipsis.
  482. bool AlreadyHasEllipsis = EllipsisLoc.isValid();
  483. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  484. DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
  485. // Grab a default argument (if available).
  486. // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
  487. // we introduce the type parameter into the local scope.
  488. SourceLocation EqualLoc;
  489. ParsedType DefaultArg;
  490. if (TryConsumeToken(tok::equal, EqualLoc))
  491. DefaultArg = ParseTypeName(/*Range=*/nullptr,
  492. Declarator::TemplateTypeArgContext).get();
  493. return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
  494. KeyLoc, ParamName, NameLoc, Depth, Position,
  495. EqualLoc, DefaultArg);
  496. }
  497. /// ParseTemplateTemplateParameter - Handle the parsing of template
  498. /// template parameters.
  499. ///
  500. /// type-parameter: [C++ temp.param]
  501. /// 'template' '<' template-parameter-list '>' type-parameter-key
  502. /// ...[opt] identifier[opt]
  503. /// 'template' '<' template-parameter-list '>' type-parameter-key
  504. /// identifier[opt] = id-expression
  505. /// type-parameter-key:
  506. /// 'class'
  507. /// 'typename' [C++1z]
  508. Decl *
  509. Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
  510. assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
  511. // Handle the template <...> part.
  512. SourceLocation TemplateLoc = ConsumeToken();
  513. SmallVector<Decl*,8> TemplateParams;
  514. SourceLocation LAngleLoc, RAngleLoc;
  515. {
  516. ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
  517. if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
  518. RAngleLoc)) {
  519. return nullptr;
  520. }
  521. }
  522. // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
  523. // Generate a meaningful error if the user forgot to put class before the
  524. // identifier, comma, or greater. Provide a fixit if the identifier, comma,
  525. // or greater appear immediately or after 'struct'. In the latter case,
  526. // replace the keyword with 'class'.
  527. if (!TryConsumeToken(tok::kw_class)) {
  528. bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
  529. const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
  530. if (Tok.is(tok::kw_typename)) {
  531. Diag(Tok.getLocation(),
  532. getLangOpts().CPlusPlus1z
  533. ? diag::warn_cxx14_compat_template_template_param_typename
  534. : diag::ext_template_template_param_typename)
  535. << (!getLangOpts().CPlusPlus1z
  536. ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
  537. : FixItHint());
  538. } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
  539. tok::greatergreater, tok::ellipsis)) {
  540. Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
  541. << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
  542. : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
  543. } else
  544. Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
  545. if (Replace)
  546. ConsumeToken();
  547. }
  548. // Parse the ellipsis, if given.
  549. SourceLocation EllipsisLoc;
  550. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  551. Diag(EllipsisLoc,
  552. getLangOpts().CPlusPlus11
  553. ? diag::warn_cxx98_compat_variadic_templates
  554. : diag::ext_variadic_templates);
  555. // Get the identifier, if given.
  556. SourceLocation NameLoc;
  557. IdentifierInfo *ParamName = nullptr;
  558. if (Tok.is(tok::identifier)) {
  559. ParamName = Tok.getIdentifierInfo();
  560. NameLoc = ConsumeToken();
  561. } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  562. tok::greatergreater)) {
  563. // Unnamed template parameter. Don't have to do anything here, just
  564. // don't consume this token.
  565. } else {
  566. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  567. return nullptr;
  568. }
  569. // Recover from misplaced ellipsis.
  570. bool AlreadyHasEllipsis = EllipsisLoc.isValid();
  571. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  572. DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
  573. TemplateParameterList *ParamList =
  574. Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
  575. TemplateLoc, LAngleLoc,
  576. TemplateParams.data(),
  577. TemplateParams.size(),
  578. RAngleLoc);
  579. // Grab a default argument (if available).
  580. // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
  581. // we introduce the template parameter into the local scope.
  582. SourceLocation EqualLoc;
  583. ParsedTemplateArgument DefaultArg;
  584. if (TryConsumeToken(tok::equal, EqualLoc)) {
  585. DefaultArg = ParseTemplateTemplateArgument();
  586. if (DefaultArg.isInvalid()) {
  587. Diag(Tok.getLocation(),
  588. diag::err_default_template_template_parameter_not_template);
  589. SkipUntil(tok::comma, tok::greater, tok::greatergreater,
  590. StopAtSemi | StopBeforeMatch);
  591. }
  592. }
  593. return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
  594. ParamList, EllipsisLoc,
  595. ParamName, NameLoc, Depth,
  596. Position, EqualLoc, DefaultArg);
  597. }
  598. /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
  599. /// template parameters (e.g., in "template<int Size> class array;").
  600. ///
  601. /// template-parameter:
  602. /// ...
  603. /// parameter-declaration
  604. Decl *
  605. Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
  606. // Parse the declaration-specifiers (i.e., the type).
  607. // FIXME: The type should probably be restricted in some way... Not all
  608. // declarators (parts of declarators?) are accepted for parameters.
  609. DeclSpec DS(AttrFactory);
  610. ParseDeclarationSpecifiers(DS);
  611. // Parse this as a typename.
  612. Declarator ParamDecl(DS, Declarator::TemplateParamContext);
  613. ParseDeclarator(ParamDecl);
  614. if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
  615. Diag(Tok.getLocation(), diag::err_expected_template_parameter);
  616. return nullptr;
  617. }
  618. // Recover from misplaced ellipsis.
  619. SourceLocation EllipsisLoc;
  620. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  621. DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
  622. // If there is a default value, parse it.
  623. // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
  624. // we introduce the template parameter into the local scope.
  625. SourceLocation EqualLoc;
  626. ExprResult DefaultArg;
  627. if (TryConsumeToken(tok::equal, EqualLoc)) {
  628. // C++ [temp.param]p15:
  629. // When parsing a default template-argument for a non-type
  630. // template-parameter, the first non-nested > is taken as the
  631. // end of the template-parameter-list rather than a greater-than
  632. // operator.
  633. GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
  634. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  635. DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
  636. if (DefaultArg.isInvalid())
  637. SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
  638. }
  639. // Create the parameter.
  640. return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
  641. Depth, Position, EqualLoc,
  642. DefaultArg.get());
  643. }
  644. void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
  645. SourceLocation CorrectLoc,
  646. bool AlreadyHasEllipsis,
  647. bool IdentifierHasName) {
  648. FixItHint Insertion;
  649. if (!AlreadyHasEllipsis)
  650. Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
  651. Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
  652. << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
  653. << !IdentifierHasName;
  654. }
  655. void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
  656. Declarator &D) {
  657. assert(EllipsisLoc.isValid());
  658. bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
  659. if (!AlreadyHasEllipsis)
  660. D.setEllipsisLoc(EllipsisLoc);
  661. DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
  662. AlreadyHasEllipsis, D.hasName());
  663. }
  664. /// \brief Parses a '>' at the end of a template list.
  665. ///
  666. /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
  667. /// to determine if these tokens were supposed to be a '>' followed by
  668. /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
  669. ///
  670. /// \param RAngleLoc the location of the consumed '>'.
  671. ///
  672. /// \param ConsumeLastToken if true, the '>' is consumed.
  673. ///
  674. /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
  675. /// type parameter or type argument list, rather than a C++ template parameter
  676. /// or argument list.
  677. ///
  678. /// \returns true, if current token does not start with '>', false otherwise.
  679. bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
  680. bool ConsumeLastToken,
  681. bool ObjCGenericList) {
  682. // What will be left once we've consumed the '>'.
  683. tok::TokenKind RemainingToken;
  684. const char *ReplacementStr = "> >";
  685. switch (Tok.getKind()) {
  686. default:
  687. Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
  688. return true;
  689. case tok::greater:
  690. // Determine the location of the '>' token. Only consume this token
  691. // if the caller asked us to.
  692. RAngleLoc = Tok.getLocation();
  693. if (ConsumeLastToken)
  694. ConsumeToken();
  695. return false;
  696. case tok::greatergreater:
  697. RemainingToken = tok::greater;
  698. break;
  699. case tok::greatergreatergreater:
  700. RemainingToken = tok::greatergreater;
  701. break;
  702. case tok::greaterequal:
  703. RemainingToken = tok::equal;
  704. ReplacementStr = "> =";
  705. break;
  706. case tok::greatergreaterequal:
  707. RemainingToken = tok::greaterequal;
  708. break;
  709. }
  710. // This template-id is terminated by a token which starts with a '>'. Outside
  711. // C++11, this is now error recovery, and in C++11, this is error recovery if
  712. // the token isn't '>>' or '>>>'.
  713. // '>>>' is for CUDA, where this sequence of characters is parsed into
  714. // tok::greatergreatergreater, rather than two separate tokens.
  715. //
  716. // We always allow this for Objective-C type parameter and type argument
  717. // lists.
  718. RAngleLoc = Tok.getLocation();
  719. Token Next = NextToken();
  720. if (!ObjCGenericList) {
  721. // The source range of the '>>' or '>=' at the start of the token.
  722. CharSourceRange ReplacementRange =
  723. CharSourceRange::getCharRange(RAngleLoc,
  724. Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
  725. getLangOpts()));
  726. // A hint to put a space between the '>>'s. In order to make the hint as
  727. // clear as possible, we include the characters either side of the space in
  728. // the replacement, rather than just inserting a space at SecondCharLoc.
  729. FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
  730. ReplacementStr);
  731. // A hint to put another space after the token, if it would otherwise be
  732. // lexed differently.
  733. FixItHint Hint2;
  734. if ((RemainingToken == tok::greater ||
  735. RemainingToken == tok::greatergreater) &&
  736. (Next.isOneOf(tok::greater, tok::greatergreater,
  737. tok::greatergreatergreater, tok::equal,
  738. tok::greaterequal, tok::greatergreaterequal,
  739. tok::equalequal)) &&
  740. areTokensAdjacent(Tok, Next))
  741. Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
  742. unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
  743. if (getLangOpts().CPlusPlus11 &&
  744. (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
  745. DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
  746. else if (Tok.is(tok::greaterequal))
  747. DiagId = diag::err_right_angle_bracket_equal_needs_space;
  748. Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
  749. }
  750. // Strip the initial '>' from the token.
  751. if (RemainingToken == tok::equal && Next.is(tok::equal) &&
  752. areTokensAdjacent(Tok, Next)) {
  753. // Join two adjacent '=' tokens into one, for cases like:
  754. // void (*p)() = f<int>;
  755. // return f<int>==p;
  756. ConsumeToken();
  757. Tok.setKind(tok::equalequal);
  758. Tok.setLength(Tok.getLength() + 1);
  759. } else {
  760. Tok.setKind(RemainingToken);
  761. Tok.setLength(Tok.getLength() - 1);
  762. }
  763. Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
  764. PP.getSourceManager(),
  765. getLangOpts()));
  766. if (!ConsumeLastToken) {
  767. // Since we're not supposed to consume the '>' token, we need to push
  768. // this token and revert the current token back to the '>'.
  769. PP.EnterToken(Tok);
  770. Tok.setKind(tok::greater);
  771. Tok.setLength(1);
  772. Tok.setLocation(RAngleLoc);
  773. }
  774. return false;
  775. }
  776. /// \brief Parses a template-id that after the template name has
  777. /// already been parsed.
  778. ///
  779. /// This routine takes care of parsing the enclosed template argument
  780. /// list ('<' template-parameter-list [opt] '>') and placing the
  781. /// results into a form that can be transferred to semantic analysis.
  782. ///
  783. /// \param Template the template declaration produced by isTemplateName
  784. ///
  785. /// \param TemplateNameLoc the source location of the template name
  786. ///
  787. /// \param SS if non-NULL, the nested-name-specifier preceding the
  788. /// template name.
  789. ///
  790. /// \param ConsumeLastToken if true, then we will consume the last
  791. /// token that forms the template-id. Otherwise, we will leave the
  792. /// last token in the stream (e.g., so that it can be replaced with an
  793. /// annotation token).
  794. bool
  795. Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
  796. SourceLocation TemplateNameLoc,
  797. const CXXScopeSpec &SS,
  798. bool ConsumeLastToken,
  799. SourceLocation &LAngleLoc,
  800. TemplateArgList &TemplateArgs,
  801. SourceLocation &RAngleLoc) {
  802. assert(Tok.is(tok::less) && "Must have already parsed the template-name");
  803. // Consume the '<'.
  804. LAngleLoc = ConsumeToken();
  805. // Parse the optional template-argument-list.
  806. bool Invalid = false;
  807. {
  808. GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
  809. if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
  810. Invalid = ParseTemplateArgumentList(TemplateArgs);
  811. if (Invalid) {
  812. // Try to find the closing '>'.
  813. if (ConsumeLastToken)
  814. SkipUntil(tok::greater, StopAtSemi);
  815. else
  816. SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
  817. return true;
  818. }
  819. }
  820. return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
  821. /*ObjCGenericList=*/false);
  822. }
  823. /// \brief Replace the tokens that form a simple-template-id with an
  824. /// annotation token containing the complete template-id.
  825. ///
  826. /// The first token in the stream must be the name of a template that
  827. /// is followed by a '<'. This routine will parse the complete
  828. /// simple-template-id and replace the tokens with a single annotation
  829. /// token with one of two different kinds: if the template-id names a
  830. /// type (and \p AllowTypeAnnotation is true), the annotation token is
  831. /// a type annotation that includes the optional nested-name-specifier
  832. /// (\p SS). Otherwise, the annotation token is a template-id
  833. /// annotation that does not include the optional
  834. /// nested-name-specifier.
  835. ///
  836. /// \param Template the declaration of the template named by the first
  837. /// token (an identifier), as returned from \c Action::isTemplateName().
  838. ///
  839. /// \param TNK the kind of template that \p Template
  840. /// refers to, as returned from \c Action::isTemplateName().
  841. ///
  842. /// \param SS if non-NULL, the nested-name-specifier that precedes
  843. /// this template name.
  844. ///
  845. /// \param TemplateKWLoc if valid, specifies that this template-id
  846. /// annotation was preceded by the 'template' keyword and gives the
  847. /// location of that keyword. If invalid (the default), then this
  848. /// template-id was not preceded by a 'template' keyword.
  849. ///
  850. /// \param AllowTypeAnnotation if true (the default), then a
  851. /// simple-template-id that refers to a class template, template
  852. /// template parameter, or other template that produces a type will be
  853. /// replaced with a type annotation token. Otherwise, the
  854. /// simple-template-id is always replaced with a template-id
  855. /// annotation token.
  856. ///
  857. /// If an unrecoverable parse error occurs and no annotation token can be
  858. /// formed, this function returns true.
  859. ///
  860. bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
  861. CXXScopeSpec &SS,
  862. SourceLocation TemplateKWLoc,
  863. UnqualifiedId &TemplateName,
  864. bool AllowTypeAnnotation) {
  865. assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
  866. assert(Template && (Tok.is(tok::less) || getLangOpts().HLSL) && // HLSL Change
  867. "Parser isn't at the beginning of a template-id");
  868. // Consume the template-name.
  869. SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
  870. // Parse the enclosed template argument list.
  871. SourceLocation LAngleLoc, RAngleLoc;
  872. TemplateArgList TemplateArgs;
  873. // HLSL Change Starts - allow template names without '<>'
  874. bool Invalid;
  875. bool ShouldParse = Tok.is(tok::less) || !getLangOpts().HLSL;
  876. if (ShouldParse) { // HLSL Change - make following conditional
  877. Invalid = ParseTemplateIdAfterTemplateName(Template,
  878. TemplateNameLoc,
  879. SS, false, LAngleLoc,
  880. TemplateArgs,
  881. RAngleLoc);
  882. }
  883. else {
  884. Invalid = false;
  885. RAngleLoc = LAngleLoc = Tok.getLocation();
  886. }
  887. // HLSL Change Ends
  888. if (Invalid) {
  889. // If we failed to parse the template ID but skipped ahead to a >, we're not
  890. // going to be able to form a token annotation. Eat the '>' if present.
  891. TryConsumeToken(tok::greater);
  892. return true;
  893. }
  894. ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
  895. // Build the annotation token.
  896. if (TNK == TNK_Type_template && AllowTypeAnnotation) {
  897. TypeResult Type
  898. = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
  899. Template, TemplateNameLoc,
  900. LAngleLoc, TemplateArgsPtr, RAngleLoc);
  901. if (Type.isInvalid()) {
  902. // If we failed to parse the template ID but skipped ahead to a >, we're not
  903. // going to be able to form a token annotation. Eat the '>' if present.
  904. TryConsumeToken(tok::greater);
  905. return true;
  906. }
  907. Tok.setKind(tok::annot_typename);
  908. setTypeAnnotation(Tok, Type.get());
  909. if (SS.isNotEmpty())
  910. Tok.setLocation(SS.getBeginLoc());
  911. else if (TemplateKWLoc.isValid())
  912. Tok.setLocation(TemplateKWLoc);
  913. else
  914. Tok.setLocation(TemplateNameLoc);
  915. } else {
  916. // Build a template-id annotation token that can be processed
  917. // later.
  918. Tok.setKind(tok::annot_template_id);
  919. TemplateIdAnnotation *TemplateId
  920. = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
  921. TemplateId->TemplateNameLoc = TemplateNameLoc;
  922. if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
  923. TemplateId->Name = TemplateName.Identifier;
  924. TemplateId->Operator = OO_None;
  925. } else {
  926. TemplateId->Name = nullptr;
  927. TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
  928. }
  929. TemplateId->SS = SS;
  930. TemplateId->TemplateKWLoc = TemplateKWLoc;
  931. TemplateId->Template = Template;
  932. TemplateId->Kind = TNK;
  933. TemplateId->LAngleLoc = LAngleLoc;
  934. TemplateId->RAngleLoc = RAngleLoc;
  935. ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
  936. for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
  937. Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
  938. Tok.setAnnotationValue(TemplateId);
  939. if (TemplateKWLoc.isValid())
  940. Tok.setLocation(TemplateKWLoc);
  941. else
  942. Tok.setLocation(TemplateNameLoc);
  943. }
  944. // Common fields for the annotation token
  945. Tok.setAnnotationEndLoc(RAngleLoc);
  946. // In case the tokens were cached, have Preprocessor replace them with the
  947. // annotation token.
  948. PP.AnnotateCachedTokens(Tok);
  949. return false;
  950. }
  951. /// \brief Replaces a template-id annotation token with a type
  952. /// annotation token.
  953. ///
  954. /// If there was a failure when forming the type from the template-id,
  955. /// a type annotation token will still be created, but will have a
  956. /// NULL type pointer to signify an error.
  957. void Parser::AnnotateTemplateIdTokenAsType() {
  958. assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
  959. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  960. assert((TemplateId->Kind == TNK_Type_template ||
  961. TemplateId->Kind == TNK_Dependent_template_name) &&
  962. "Only works for type and dependent templates");
  963. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  964. TemplateId->NumArgs);
  965. TypeResult Type
  966. = Actions.ActOnTemplateIdType(TemplateId->SS,
  967. TemplateId->TemplateKWLoc,
  968. TemplateId->Template,
  969. TemplateId->TemplateNameLoc,
  970. TemplateId->LAngleLoc,
  971. TemplateArgsPtr,
  972. TemplateId->RAngleLoc);
  973. // Create the new "type" annotation token.
  974. Tok.setKind(tok::annot_typename);
  975. setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
  976. if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
  977. Tok.setLocation(TemplateId->SS.getBeginLoc());
  978. // End location stays the same
  979. // Replace the template-id annotation token, and possible the scope-specifier
  980. // that precedes it, with the typename annotation token.
  981. PP.AnnotateCachedTokens(Tok);
  982. }
  983. /// \brief Determine whether the given token can end a template argument.
  984. static bool isEndOfTemplateArgument(Token Tok) {
  985. return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
  986. }
  987. /// \brief Parse a C++ template template argument.
  988. ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
  989. if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
  990. !Tok.is(tok::annot_cxxscope))
  991. return ParsedTemplateArgument();
  992. // C++0x [temp.arg.template]p1:
  993. // A template-argument for a template template-parameter shall be the name
  994. // of a class template or an alias template, expressed as id-expression.
  995. //
  996. // We parse an id-expression that refers to a class template or alias
  997. // template. The grammar we parse is:
  998. //
  999. // nested-name-specifier[opt] template[opt] identifier ...[opt]
  1000. //
  1001. // followed by a token that terminates a template argument, such as ',',
  1002. // '>', or (in some cases) '>>'.
  1003. CXXScopeSpec SS; // nested-name-specifier, if present
  1004. ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  1005. /*EnteringContext=*/false);
  1006. ParsedTemplateArgument Result;
  1007. SourceLocation EllipsisLoc;
  1008. if (SS.isSet() && Tok.is(tok::kw_template)) {
  1009. // HLSL Change Starts
  1010. if (getLangOpts().HLSL) {
  1011. Diag(Tok, diag::err_hlsl_unsupported_construct) << "template template argument";
  1012. return Result;
  1013. }
  1014. // HLSL Change Ends
  1015. // Parse the optional 'template' keyword following the
  1016. // nested-name-specifier.
  1017. SourceLocation TemplateKWLoc = ConsumeToken();
  1018. if (Tok.is(tok::identifier)) {
  1019. // We appear to have a dependent template name.
  1020. UnqualifiedId Name;
  1021. Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1022. ConsumeToken(); // the identifier
  1023. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  1024. // If the next token signals the end of a template argument,
  1025. // then we have a dependent template name that could be a template
  1026. // template argument.
  1027. TemplateTy Template;
  1028. if (isEndOfTemplateArgument(Tok) &&
  1029. Actions.ActOnDependentTemplateName(getCurScope(),
  1030. SS, TemplateKWLoc, Name,
  1031. /*ObjectType=*/ ParsedType(),
  1032. /*EnteringContext=*/false,
  1033. Template))
  1034. Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
  1035. }
  1036. } else if (Tok.is(tok::identifier)) {
  1037. // We may have a (non-dependent) template name.
  1038. TemplateTy Template;
  1039. UnqualifiedId Name;
  1040. Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1041. ConsumeToken(); // the identifier
  1042. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  1043. if (isEndOfTemplateArgument(Tok)) {
  1044. bool MemberOfUnknownSpecialization;
  1045. TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
  1046. /*hasTemplateKeyword=*/false,
  1047. Name,
  1048. /*ObjectType=*/ ParsedType(),
  1049. /*EnteringContext=*/false,
  1050. Template,
  1051. MemberOfUnknownSpecialization);
  1052. if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
  1053. // We have an id-expression that refers to a class template or
  1054. // (C++0x) alias template.
  1055. Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
  1056. }
  1057. }
  1058. }
  1059. // If this is a pack expansion, build it as such.
  1060. if (EllipsisLoc.isValid() && !Result.isInvalid())
  1061. Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
  1062. return Result;
  1063. }
  1064. /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
  1065. ///
  1066. /// template-argument: [C++ 14.2]
  1067. /// constant-expression
  1068. /// type-id
  1069. /// id-expression
  1070. ParsedTemplateArgument Parser::ParseTemplateArgument() {
  1071. // C++ [temp.arg]p2:
  1072. // In a template-argument, an ambiguity between a type-id and an
  1073. // expression is resolved to a type-id, regardless of the form of
  1074. // the corresponding template-parameter.
  1075. //
  1076. // Therefore, we initially try to parse a type-id.
  1077. if (isCXXTypeId(TypeIdAsTemplateArgument)) {
  1078. SourceLocation Loc = Tok.getLocation();
  1079. TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
  1080. Declarator::TemplateTypeArgContext);
  1081. if (TypeArg.isInvalid())
  1082. return ParsedTemplateArgument();
  1083. return ParsedTemplateArgument(ParsedTemplateArgument::Type,
  1084. TypeArg.get().getAsOpaquePtr(),
  1085. Loc);
  1086. }
  1087. // Try to parse a template template argument.
  1088. if (!getLangOpts().HLSL) // HLSL Change - HLSL does not support template template arguments
  1089. {
  1090. TentativeParsingAction TPA(*this);
  1091. ParsedTemplateArgument TemplateTemplateArgument
  1092. = ParseTemplateTemplateArgument();
  1093. if (!TemplateTemplateArgument.isInvalid()) {
  1094. TPA.Commit();
  1095. return TemplateTemplateArgument;
  1096. }
  1097. // Revert this tentative parse to parse a non-type template argument.
  1098. TPA.Revert();
  1099. }
  1100. // Parse a non-type template argument.
  1101. SourceLocation Loc = Tok.getLocation();
  1102. ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
  1103. if (ExprArg.isInvalid() || !ExprArg.get())
  1104. return ParsedTemplateArgument();
  1105. return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
  1106. ExprArg.get(), Loc);
  1107. }
  1108. /// \brief Determine whether the current tokens can only be parsed as a
  1109. /// template argument list (starting with the '<') and never as a '<'
  1110. /// expression.
  1111. bool Parser::IsTemplateArgumentList(unsigned Skip) {
  1112. struct AlwaysRevertAction : TentativeParsingAction {
  1113. AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
  1114. ~AlwaysRevertAction() { Revert(); }
  1115. } Tentative(*this);
  1116. while (Skip) {
  1117. ConsumeToken();
  1118. --Skip;
  1119. }
  1120. // '<'
  1121. if (!TryConsumeToken(tok::less))
  1122. return false;
  1123. // An empty template argument list.
  1124. if (Tok.is(tok::greater))
  1125. return true;
  1126. // See whether we have declaration specifiers, which indicate a type.
  1127. while (isCXXDeclarationSpecifier() == TPResult::True)
  1128. ConsumeToken();
  1129. // If we have a '>' or a ',' then this is a template argument list.
  1130. return Tok.isOneOf(tok::greater, tok::comma);
  1131. }
  1132. /// ParseTemplateArgumentList - Parse a C++ template-argument-list
  1133. /// (C++ [temp.names]). Returns true if there was an error.
  1134. ///
  1135. /// template-argument-list: [C++ 14.2]
  1136. /// template-argument
  1137. /// template-argument-list ',' template-argument
  1138. bool
  1139. Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
  1140. // Template argument lists are constant-evaluation contexts.
  1141. EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
  1142. ColonProtectionRAIIObject ColonProtection(*this, false);
  1143. do {
  1144. ParsedTemplateArgument Arg = ParseTemplateArgument();
  1145. SourceLocation EllipsisLoc;
  1146. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  1147. { // HLSL Change Starts
  1148. if (getLangOpts().HLSL) {
  1149. Diag(EllipsisLoc, diag::err_hlsl_unsupported_construct) << "ellipsis";
  1150. SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
  1151. return true;
  1152. }
  1153. // HLSL Change Ends
  1154. Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
  1155. } // HLSL Change - end conditional block
  1156. if (Arg.isInvalid()) {
  1157. SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
  1158. return true;
  1159. }
  1160. // Save this template argument.
  1161. TemplateArgs.push_back(Arg);
  1162. // If the next token is a comma, consume it and keep reading
  1163. // arguments.
  1164. } while (TryConsumeToken(tok::comma));
  1165. return false;
  1166. }
  1167. /// \brief Parse a C++ explicit template instantiation
  1168. /// (C++ [temp.explicit]).
  1169. ///
  1170. /// explicit-instantiation:
  1171. /// 'extern' [opt] 'template' declaration
  1172. ///
  1173. /// Note that the 'extern' is a GNU extension and C++11 feature.
  1174. Decl *Parser::ParseExplicitInstantiation(unsigned Context,
  1175. SourceLocation ExternLoc,
  1176. SourceLocation TemplateLoc,
  1177. SourceLocation &DeclEnd,
  1178. AccessSpecifier AS) {
  1179. // This isn't really required here.
  1180. ParsingDeclRAIIObject
  1181. ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
  1182. return ParseSingleDeclarationAfterTemplate(Context,
  1183. ParsedTemplateInfo(ExternLoc,
  1184. TemplateLoc),
  1185. ParsingTemplateParams,
  1186. DeclEnd, AS);
  1187. }
  1188. SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
  1189. if (TemplateParams)
  1190. return getTemplateParamsRange(TemplateParams->data(),
  1191. TemplateParams->size());
  1192. SourceRange R(TemplateLoc);
  1193. if (ExternLoc.isValid())
  1194. R.setBegin(ExternLoc);
  1195. return R;
  1196. }
  1197. void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
  1198. ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
  1199. }
  1200. /// \brief Late parse a C++ function template in Microsoft mode.
  1201. void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
  1202. if (!LPT.D)
  1203. return;
  1204. // Get the FunctionDecl.
  1205. FunctionDecl *FunD = LPT.D->getAsFunction();
  1206. // Track template parameter depth.
  1207. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  1208. // To restore the context after late parsing.
  1209. Sema::ContextRAII GlobalSavedContext(
  1210. Actions, Actions.Context.getTranslationUnitDecl());
  1211. SmallVector<ParseScope*, 4> TemplateParamScopeStack;
  1212. // Get the list of DeclContexts to reenter.
  1213. SmallVector<DeclContext*, 4> DeclContextsToReenter;
  1214. DeclContext *DD = FunD;
  1215. while (DD && !DD->isTranslationUnit()) {
  1216. DeclContextsToReenter.push_back(DD);
  1217. DD = DD->getLexicalParent();
  1218. }
  1219. // Reenter template scopes from outermost to innermost.
  1220. SmallVectorImpl<DeclContext *>::reverse_iterator II =
  1221. DeclContextsToReenter.rbegin();
  1222. for (; II != DeclContextsToReenter.rend(); ++II) {
  1223. TemplateParamScopeStack.push_back(new ParseScope(this,
  1224. Scope::TemplateParamScope));
  1225. unsigned NumParamLists =
  1226. Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
  1227. CurTemplateDepthTracker.addDepth(NumParamLists);
  1228. if (*II != FunD) {
  1229. TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
  1230. Actions.PushDeclContext(Actions.getCurScope(), *II);
  1231. }
  1232. }
  1233. assert(!LPT.Toks.empty() && "Empty body!");
  1234. // Append the current token at the end of the new token stream so that it
  1235. // doesn't get lost.
  1236. LPT.Toks.push_back(Tok);
  1237. PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
  1238. // Consume the previously pushed token.
  1239. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  1240. assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
  1241. "Inline method not starting with '{', ':' or 'try'");
  1242. // Parse the method body. Function body parsing code is similar enough
  1243. // to be re-used for method bodies as well.
  1244. ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
  1245. // Recreate the containing function DeclContext.
  1246. Sema::ContextRAII FunctionSavedContext(Actions,
  1247. Actions.getContainingDC(FunD));
  1248. Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
  1249. if (Tok.is(tok::kw_try)) {
  1250. ParseFunctionTryBlock(LPT.D, FnScope);
  1251. } else {
  1252. if (Tok.is(tok::colon))
  1253. ParseConstructorInitializer(LPT.D);
  1254. else
  1255. Actions.ActOnDefaultCtorInitializers(LPT.D);
  1256. if (Tok.is(tok::l_brace)) {
  1257. assert((!isa<FunctionTemplateDecl>(LPT.D) ||
  1258. cast<FunctionTemplateDecl>(LPT.D)
  1259. ->getTemplateParameters()
  1260. ->getDepth() == TemplateParameterDepth - 1) &&
  1261. "TemplateParameterDepth should be greater than the depth of "
  1262. "current template being instantiated!");
  1263. ParseFunctionStatementBody(LPT.D, FnScope);
  1264. Actions.UnmarkAsLateParsedTemplate(FunD);
  1265. } else
  1266. Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
  1267. }
  1268. // Exit scopes.
  1269. FnScope.Exit();
  1270. SmallVectorImpl<ParseScope *>::reverse_iterator I =
  1271. TemplateParamScopeStack.rbegin();
  1272. for (; I != TemplateParamScopeStack.rend(); ++I)
  1273. delete *I;
  1274. }
  1275. /// \brief Lex a delayed template function for late parsing.
  1276. void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
  1277. tok::TokenKind kind = Tok.getKind();
  1278. if (!ConsumeAndStoreFunctionPrologue(Toks)) {
  1279. // Consume everything up to (and including) the matching right brace.
  1280. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1281. }
  1282. // If we're in a function-try-block, we need to store all the catch blocks.
  1283. if (kind == tok::kw_try) {
  1284. while (Tok.is(tok::kw_catch)) {
  1285. ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
  1286. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1287. }
  1288. }
  1289. }