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