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