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