ParseTemplate.cpp revision 1eb4433ac451dc16f4133a88af2d002ac26c58ef
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 "clang/Parse/ParseDiagnostic.h" 16#include "clang/Parse/DeclSpec.h" 17#include "clang/Parse/Scope.h" 18#include "llvm/Support/Compiler.h" 19using namespace clang; 20 21/// \brief Parse a template declaration, explicit instantiation, or 22/// explicit specialization. 23Parser::DeclPtrTy 24Parser::ParseDeclarationStartingWithTemplate(unsigned Context, 25 SourceLocation &DeclEnd, 26 AccessSpecifier AS) { 27 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) 28 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(), 29 DeclEnd); 30 31 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS); 32} 33 34/// \brief RAII class that manages the template parameter depth. 35namespace { 36 class VISIBILITY_HIDDEN TemplateParameterDepthCounter { 37 unsigned &Depth; 38 unsigned AddedLevels; 39 40 public: 41 explicit TemplateParameterDepthCounter(unsigned &Depth) 42 : Depth(Depth), AddedLevels(0) { } 43 44 ~TemplateParameterDepthCounter() { 45 Depth -= AddedLevels; 46 } 47 48 void operator++() { 49 ++Depth; 50 ++AddedLevels; 51 } 52 53 operator unsigned() const { return Depth; } 54 }; 55} 56 57/// \brief Parse a template declaration or an explicit specialization. 58/// 59/// Template declarations include one or more template parameter lists 60/// and either the function or class template declaration. Explicit 61/// specializations contain one or more 'template < >' prefixes 62/// followed by a (possibly templated) declaration. Since the 63/// syntactic form of both features is nearly identical, we parse all 64/// of the template headers together and let semantic analysis sort 65/// the declarations from the explicit specializations. 66/// 67/// template-declaration: [C++ temp] 68/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration 69/// 70/// explicit-specialization: [ C++ temp.expl.spec] 71/// 'template' '<' '>' declaration 72Parser::DeclPtrTy 73Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context, 74 SourceLocation &DeclEnd, 75 AccessSpecifier AS) { 76 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) && 77 "Token does not start a template declaration."); 78 79 // Enter template-parameter scope. 80 ParseScope TemplateParmScope(this, Scope::TemplateParamScope); 81 82 // Parse multiple levels of template headers within this template 83 // parameter scope, e.g., 84 // 85 // template<typename T> 86 // template<typename U> 87 // class A<T>::B { ... }; 88 // 89 // We parse multiple levels non-recursively so that we can build a 90 // single data structure containing all of the template parameter 91 // lists to easily differentiate between the case above and: 92 // 93 // template<typename T> 94 // class A { 95 // template<typename U> class B; 96 // }; 97 // 98 // In the first case, the action for declaring A<T>::B receives 99 // both template parameter lists. In the second case, the action for 100 // defining A<T>::B receives just the inner template parameter list 101 // (and retrieves the outer template parameter list from its 102 // context). 103 bool isSpecialization = true; 104 TemplateParameterLists ParamLists; 105 TemplateParameterDepthCounter Depth(TemplateParameterDepth); 106 do { 107 // Consume the 'export', if any. 108 SourceLocation ExportLoc; 109 if (Tok.is(tok::kw_export)) { 110 ExportLoc = ConsumeToken(); 111 } 112 113 // Consume the 'template', which should be here. 114 SourceLocation TemplateLoc; 115 if (Tok.is(tok::kw_template)) { 116 TemplateLoc = ConsumeToken(); 117 } else { 118 Diag(Tok.getLocation(), diag::err_expected_template); 119 return DeclPtrTy(); 120 } 121 122 // Parse the '<' template-parameter-list '>' 123 SourceLocation LAngleLoc, RAngleLoc; 124 TemplateParameterList TemplateParams; 125 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc, 126 RAngleLoc)) { 127 // Skip until the semi-colon or a }. 128 SkipUntil(tok::r_brace, true, true); 129 if (Tok.is(tok::semi)) 130 ConsumeToken(); 131 return DeclPtrTy(); 132 } 133 134 ParamLists.push_back( 135 Actions.ActOnTemplateParameterList(Depth, ExportLoc, 136 TemplateLoc, LAngleLoc, 137 TemplateParams.data(), 138 TemplateParams.size(), RAngleLoc)); 139 140 if (!TemplateParams.empty()) { 141 isSpecialization = false; 142 ++Depth; 143 } 144 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template)); 145 146 // Parse the actual template declaration. 147 return ParseSingleDeclarationAfterTemplate(Context, 148 ParsedTemplateInfo(&ParamLists, 149 isSpecialization), 150 DeclEnd, AS); 151} 152 153/// \brief Parse a single declaration that declares a template, 154/// template specialization, or explicit instantiation of a template. 155/// 156/// \param TemplateParams if non-NULL, the template parameter lists 157/// that preceded this declaration. In this case, the declaration is a 158/// template declaration, out-of-line definition of a template, or an 159/// explicit template specialization. When NULL, the declaration is an 160/// explicit template instantiation. 161/// 162/// \param TemplateLoc when TemplateParams is NULL, the location of 163/// the 'template' keyword that indicates that we have an explicit 164/// template instantiation. 165/// 166/// \param DeclEnd will receive the source location of the last token 167/// within this declaration. 168/// 169/// \param AS the access specifier associated with this 170/// declaration. Will be AS_none for namespace-scope declarations. 171/// 172/// \returns the new declaration. 173Parser::DeclPtrTy 174Parser::ParseSingleDeclarationAfterTemplate( 175 unsigned Context, 176 const ParsedTemplateInfo &TemplateInfo, 177 SourceLocation &DeclEnd, 178 AccessSpecifier AS) { 179 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 180 "Template information required"); 181 182 if (Context == Declarator::MemberContext) { 183 // We are parsing a member template. 184 ParseCXXClassMemberDeclaration(AS, TemplateInfo); 185 return DeclPtrTy::make((void*)0); 186 } 187 188 // Parse the declaration specifiers. 189 DeclSpec DS; 190 ParseDeclarationSpecifiers(DS, TemplateInfo, AS); 191 192 if (Tok.is(tok::semi)) { 193 DeclEnd = ConsumeToken(); 194 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 195 } 196 197 // Parse the declarator. 198 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context); 199 ParseDeclarator(DeclaratorInfo); 200 // Error parsing the declarator? 201 if (!DeclaratorInfo.hasName()) { 202 // If so, skip until the semi-colon or a }. 203 SkipUntil(tok::r_brace, true, true); 204 if (Tok.is(tok::semi)) 205 ConsumeToken(); 206 return DeclPtrTy(); 207 } 208 209 // If we have a declaration or declarator list, handle it. 210 if (isDeclarationAfterDeclarator()) { 211 // Parse this declaration. 212 DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo, 213 TemplateInfo); 214 215 if (Tok.is(tok::comma)) { 216 Diag(Tok, diag::err_multiple_template_declarators) 217 << (int)TemplateInfo.Kind; 218 SkipUntil(tok::semi, true, false); 219 return ThisDecl; 220 } 221 222 // Eat the semi colon after the declaration. 223 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration); 224 return ThisDecl; 225 } 226 227 if (DeclaratorInfo.isFunctionDeclarator() && 228 isStartOfFunctionDefinition()) { 229 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 230 Diag(Tok, diag::err_function_declared_typedef); 231 232 if (Tok.is(tok::l_brace)) { 233 // This recovery skips the entire function body. It would be nice 234 // to simply call ParseFunctionDefinition() below, however Sema 235 // assumes the declarator represents a function, not a typedef. 236 ConsumeBrace(); 237 SkipUntil(tok::r_brace, true); 238 } else { 239 SkipUntil(tok::semi); 240 } 241 return DeclPtrTy(); 242 } 243 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo); 244 } 245 246 if (DeclaratorInfo.isFunctionDeclarator()) 247 Diag(Tok, diag::err_expected_fn_body); 248 else 249 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator); 250 SkipUntil(tok::semi); 251 return DeclPtrTy(); 252} 253 254/// ParseTemplateParameters - Parses a template-parameter-list enclosed in 255/// angle brackets. Depth is the depth of this template-parameter-list, which 256/// is the number of template headers directly enclosing this template header. 257/// TemplateParams is the current list of template parameters we're building. 258/// The template parameter we parse will be added to this list. LAngleLoc and 259/// RAngleLoc will receive the positions of the '<' and '>', respectively, 260/// that enclose this template parameter list. 261/// 262/// \returns true if an error occurred, false otherwise. 263bool Parser::ParseTemplateParameters(unsigned Depth, 264 TemplateParameterList &TemplateParams, 265 SourceLocation &LAngleLoc, 266 SourceLocation &RAngleLoc) { 267 // Get the template parameter list. 268 if (!Tok.is(tok::less)) { 269 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template"; 270 return true; 271 } 272 LAngleLoc = ConsumeToken(); 273 274 // Try to parse the template parameter list. 275 if (Tok.is(tok::greater)) 276 RAngleLoc = ConsumeToken(); 277 else if (ParseTemplateParameterList(Depth, TemplateParams)) { 278 if (!Tok.is(tok::greater)) { 279 Diag(Tok.getLocation(), diag::err_expected_greater); 280 return true; 281 } 282 RAngleLoc = ConsumeToken(); 283 } 284 return false; 285} 286 287/// ParseTemplateParameterList - Parse a template parameter list. If 288/// the parsing fails badly (i.e., closing bracket was left out), this 289/// will try to put the token stream in a reasonable position (closing 290/// a statement, etc.) and return false. 291/// 292/// template-parameter-list: [C++ temp] 293/// template-parameter 294/// template-parameter-list ',' template-parameter 295bool 296Parser::ParseTemplateParameterList(unsigned Depth, 297 TemplateParameterList &TemplateParams) { 298 while (1) { 299 if (DeclPtrTy TmpParam 300 = ParseTemplateParameter(Depth, TemplateParams.size())) { 301 TemplateParams.push_back(TmpParam); 302 } else { 303 // If we failed to parse a template parameter, skip until we find 304 // a comma or closing brace. 305 SkipUntil(tok::comma, tok::greater, true, true); 306 } 307 308 // Did we find a comma or the end of the template parmeter list? 309 if (Tok.is(tok::comma)) { 310 ConsumeToken(); 311 } else if (Tok.is(tok::greater)) { 312 // Don't consume this... that's done by template parser. 313 break; 314 } else { 315 // Somebody probably forgot to close the template. Skip ahead and 316 // try to get out of the expression. This error is currently 317 // subsumed by whatever goes on in ParseTemplateParameter. 318 // TODO: This could match >>, and it would be nice to avoid those 319 // silly errors with template <vec<T>>. 320 // Diag(Tok.getLocation(), diag::err_expected_comma_greater); 321 SkipUntil(tok::greater, true, true); 322 return false; 323 } 324 } 325 return true; 326} 327 328/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]). 329/// 330/// template-parameter: [C++ temp.param] 331/// type-parameter 332/// parameter-declaration 333/// 334/// type-parameter: (see below) 335/// 'class' ...[opt][C++0x] identifier[opt] 336/// 'class' identifier[opt] '=' type-id 337/// 'typename' ...[opt][C++0x] identifier[opt] 338/// 'typename' identifier[opt] '=' type-id 339/// 'template' ...[opt][C++0x] '<' template-parameter-list '>' 'class' identifier[opt] 340/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression 341Parser::DeclPtrTy 342Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) { 343 if (Tok.is(tok::kw_class) || 344 (Tok.is(tok::kw_typename) && 345 // FIXME: Next token has not been annotated! 346 NextToken().isNot(tok::annot_typename))) { 347 return ParseTypeParameter(Depth, Position); 348 } 349 350 if (Tok.is(tok::kw_template)) 351 return ParseTemplateTemplateParameter(Depth, Position); 352 353 // If it's none of the above, then it must be a parameter declaration. 354 // NOTE: This will pick up errors in the closure of the template parameter 355 // list (e.g., template < ; Check here to implement >> style closures. 356 return ParseNonTypeTemplateParameter(Depth, Position); 357} 358 359/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]). 360/// Other kinds of template parameters are parsed in 361/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter. 362/// 363/// type-parameter: [C++ temp.param] 364/// 'class' ...[opt][C++0x] identifier[opt] 365/// 'class' identifier[opt] '=' type-id 366/// 'typename' ...[opt][C++0x] identifier[opt] 367/// 'typename' identifier[opt] '=' type-id 368Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){ 369 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) && 370 "A type-parameter starts with 'class' or 'typename'"); 371 372 // Consume the 'class' or 'typename' keyword. 373 bool TypenameKeyword = Tok.is(tok::kw_typename); 374 SourceLocation KeyLoc = ConsumeToken(); 375 376 // Grab the ellipsis (if given). 377 bool Ellipsis = false; 378 SourceLocation EllipsisLoc; 379 if (Tok.is(tok::ellipsis)) { 380 Ellipsis = true; 381 EllipsisLoc = ConsumeToken(); 382 383 if (!getLang().CPlusPlus0x) 384 Diag(EllipsisLoc, diag::err_variadic_templates); 385 } 386 387 // Grab the template parameter name (if given) 388 SourceLocation NameLoc; 389 IdentifierInfo* ParamName = 0; 390 if (Tok.is(tok::identifier)) { 391 ParamName = Tok.getIdentifierInfo(); 392 NameLoc = ConsumeToken(); 393 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || 394 Tok.is(tok::greater)) { 395 // Unnamed template parameter. Don't have to do anything here, just 396 // don't consume this token. 397 } else { 398 Diag(Tok.getLocation(), diag::err_expected_ident); 399 return DeclPtrTy(); 400 } 401 402 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword, 403 Ellipsis, EllipsisLoc, 404 KeyLoc, ParamName, NameLoc, 405 Depth, Position); 406 407 // Grab a default type id (if given). 408 if (Tok.is(tok::equal)) { 409 SourceLocation EqualLoc = ConsumeToken(); 410 SourceLocation DefaultLoc = Tok.getLocation(); 411 TypeResult DefaultType = ParseTypeName(); 412 if (!DefaultType.isInvalid()) 413 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc, 414 DefaultType.get()); 415 } 416 417 return TypeParam; 418} 419 420/// ParseTemplateTemplateParameter - Handle the parsing of template 421/// template parameters. 422/// 423/// type-parameter: [C++ temp.param] 424/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] 425/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression 426Parser::DeclPtrTy 427Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { 428 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword"); 429 430 // Handle the template <...> part. 431 SourceLocation TemplateLoc = ConsumeToken(); 432 TemplateParameterList TemplateParams; 433 SourceLocation LAngleLoc, RAngleLoc; 434 { 435 ParseScope TemplateParmScope(this, Scope::TemplateParamScope); 436 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc, 437 RAngleLoc)) { 438 return DeclPtrTy(); 439 } 440 } 441 442 // Generate a meaningful error if the user forgot to put class before the 443 // identifier, comma, or greater. 444 if (!Tok.is(tok::kw_class)) { 445 Diag(Tok.getLocation(), diag::err_expected_class_before) 446 << PP.getSpelling(Tok); 447 return DeclPtrTy(); 448 } 449 SourceLocation ClassLoc = ConsumeToken(); 450 451 // Get the identifier, if given. 452 SourceLocation NameLoc; 453 IdentifierInfo* ParamName = 0; 454 if (Tok.is(tok::identifier)) { 455 ParamName = Tok.getIdentifierInfo(); 456 NameLoc = ConsumeToken(); 457 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) { 458 // Unnamed template parameter. Don't have to do anything here, just 459 // don't consume this token. 460 } else { 461 Diag(Tok.getLocation(), diag::err_expected_ident); 462 return DeclPtrTy(); 463 } 464 465 TemplateParamsTy *ParamList = 466 Actions.ActOnTemplateParameterList(Depth, SourceLocation(), 467 TemplateLoc, LAngleLoc, 468 &TemplateParams[0], 469 TemplateParams.size(), 470 RAngleLoc); 471 472 Parser::DeclPtrTy Param 473 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc, 474 ParamList, ParamName, 475 NameLoc, Depth, Position); 476 477 // Get the a default value, if given. 478 if (Tok.is(tok::equal)) { 479 SourceLocation EqualLoc = ConsumeToken(); 480 OwningExprResult DefaultExpr = ParseCXXIdExpression(); 481 if (DefaultExpr.isInvalid()) 482 return Param; 483 else if (Param) 484 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc, 485 move(DefaultExpr)); 486 } 487 488 return Param; 489} 490 491/// ParseNonTypeTemplateParameter - Handle the parsing of non-type 492/// template parameters (e.g., in "template<int Size> class array;"). 493/// 494/// template-parameter: 495/// ... 496/// parameter-declaration 497/// 498/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(), 499/// but that didn't work out to well. Instead, this tries to recrate the basic 500/// parsing of parameter declarations, but tries to constrain it for template 501/// parameters. 502/// FIXME: We need to make a ParseParameterDeclaration that works for 503/// non-type template parameters and normal function parameters. 504Parser::DeclPtrTy 505Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { 506 SourceLocation StartLoc = Tok.getLocation(); 507 508 // Parse the declaration-specifiers (i.e., the type). 509 // FIXME: The type should probably be restricted in some way... Not all 510 // declarators (parts of declarators?) are accepted for parameters. 511 DeclSpec DS; 512 ParseDeclarationSpecifiers(DS); 513 514 // Parse this as a typename. 515 Declarator ParamDecl(DS, Declarator::TemplateParamContext); 516 ParseDeclarator(ParamDecl); 517 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) { 518 // This probably shouldn't happen - and it's more of a Sema thing, but 519 // basically we didn't parse the type name because we couldn't associate 520 // it with an AST node. we should just skip to the comma or greater. 521 // TODO: This is currently a placeholder for some kind of Sema Error. 522 Diag(Tok.getLocation(), diag::err_parse_error); 523 SkipUntil(tok::comma, tok::greater, true, true); 524 return DeclPtrTy(); 525 } 526 527 // Create the parameter. 528 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl, 529 Depth, Position); 530 531 // If there is a default value, parse it. 532 if (Tok.is(tok::equal)) { 533 SourceLocation EqualLoc = ConsumeToken(); 534 535 // C++ [temp.param]p15: 536 // When parsing a default template-argument for a non-type 537 // template-parameter, the first non-nested > is taken as the 538 // end of the template-parameter-list rather than a greater-than 539 // operator. 540 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); 541 542 OwningExprResult DefaultArg = ParseAssignmentExpression(); 543 if (DefaultArg.isInvalid()) 544 SkipUntil(tok::comma, tok::greater, true, true); 545 else if (Param) 546 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc, 547 move(DefaultArg)); 548 } 549 550 return Param; 551} 552 553/// \brief Parses a template-id that after the template name has 554/// already been parsed. 555/// 556/// This routine takes care of parsing the enclosed template argument 557/// list ('<' template-parameter-list [opt] '>') and placing the 558/// results into a form that can be transferred to semantic analysis. 559/// 560/// \param Template the template declaration produced by isTemplateName 561/// 562/// \param TemplateNameLoc the source location of the template name 563/// 564/// \param SS if non-NULL, the nested-name-specifier preceding the 565/// template name. 566/// 567/// \param ConsumeLastToken if true, then we will consume the last 568/// token that forms the template-id. Otherwise, we will leave the 569/// last token in the stream (e.g., so that it can be replaced with an 570/// annotation token). 571bool 572Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, 573 SourceLocation TemplateNameLoc, 574 const CXXScopeSpec *SS, 575 bool ConsumeLastToken, 576 SourceLocation &LAngleLoc, 577 TemplateArgList &TemplateArgs, 578 TemplateArgIsTypeList &TemplateArgIsType, 579 TemplateArgLocationList &TemplateArgLocations, 580 SourceLocation &RAngleLoc) { 581 assert(Tok.is(tok::less) && "Must have already parsed the template-name"); 582 583 // Consume the '<'. 584 LAngleLoc = ConsumeToken(); 585 586 // Parse the optional template-argument-list. 587 bool Invalid = false; 588 { 589 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); 590 if (Tok.isNot(tok::greater)) 591 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType, 592 TemplateArgLocations); 593 594 if (Invalid) { 595 // Try to find the closing '>'. 596 SkipUntil(tok::greater, true, !ConsumeLastToken); 597 598 return true; 599 } 600 } 601 602 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) 603 return true; 604 605 // Determine the location of the '>' or '>>'. Only consume this 606 // token if the caller asked us to. 607 RAngleLoc = Tok.getLocation(); 608 609 if (Tok.is(tok::greatergreater)) { 610 if (!getLang().CPlusPlus0x) { 611 const char *ReplaceStr = "> >"; 612 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater)) 613 ReplaceStr = "> > "; 614 615 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space) 616 << CodeModificationHint::CreateReplacement( 617 SourceRange(Tok.getLocation()), ReplaceStr); 618 } 619 620 Tok.setKind(tok::greater); 621 if (!ConsumeLastToken) { 622 // Since we're not supposed to consume the '>>' token, we need 623 // to insert a second '>' token after the first. 624 PP.EnterToken(Tok); 625 } 626 } else if (ConsumeLastToken) 627 ConsumeToken(); 628 629 return false; 630} 631 632/// \brief Replace the tokens that form a simple-template-id with an 633/// annotation token containing the complete template-id. 634/// 635/// The first token in the stream must be the name of a template that 636/// is followed by a '<'. This routine will parse the complete 637/// simple-template-id and replace the tokens with a single annotation 638/// token with one of two different kinds: if the template-id names a 639/// type (and \p AllowTypeAnnotation is true), the annotation token is 640/// a type annotation that includes the optional nested-name-specifier 641/// (\p SS). Otherwise, the annotation token is a template-id 642/// annotation that does not include the optional 643/// nested-name-specifier. 644/// 645/// \param Template the declaration of the template named by the first 646/// token (an identifier), as returned from \c Action::isTemplateName(). 647/// 648/// \param TemplateNameKind the kind of template that \p Template 649/// refers to, as returned from \c Action::isTemplateName(). 650/// 651/// \param SS if non-NULL, the nested-name-specifier that precedes 652/// this template name. 653/// 654/// \param TemplateKWLoc if valid, specifies that this template-id 655/// annotation was preceded by the 'template' keyword and gives the 656/// location of that keyword. If invalid (the default), then this 657/// template-id was not preceded by a 'template' keyword. 658/// 659/// \param AllowTypeAnnotation if true (the default), then a 660/// simple-template-id that refers to a class template, template 661/// template parameter, or other template that produces a type will be 662/// replaced with a type annotation token. Otherwise, the 663/// simple-template-id is always replaced with a template-id 664/// annotation token. 665/// 666/// If an unrecoverable parse error occurs and no annotation token can be 667/// formed, this function returns true. 668/// 669bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, 670 const CXXScopeSpec *SS, 671 SourceLocation TemplateKWLoc, 672 bool AllowTypeAnnotation) { 673 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++"); 674 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) && 675 "Parser isn't at the beginning of a template-id"); 676 677 // Consume the template-name. 678 IdentifierInfo *Name = Tok.getIdentifierInfo(); 679 SourceLocation TemplateNameLoc = ConsumeToken(); 680 681 // Parse the enclosed template argument list. 682 SourceLocation LAngleLoc, RAngleLoc; 683 TemplateArgList TemplateArgs; 684 TemplateArgIsTypeList TemplateArgIsType; 685 TemplateArgLocationList TemplateArgLocations; 686 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc, 687 SS, false, LAngleLoc, 688 TemplateArgs, 689 TemplateArgIsType, 690 TemplateArgLocations, 691 RAngleLoc); 692 693 if (Invalid) { 694 // If we failed to parse the template ID but skipped ahead to a >, we're not 695 // going to be able to form a token annotation. Eat the '>' if present. 696 if (Tok.is(tok::greater)) 697 ConsumeToken(); 698 return true; 699 } 700 701 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(), 702 TemplateArgIsType.data(), 703 TemplateArgs.size()); 704 705 // Build the annotation token. 706 if (TNK == TNK_Type_template && AllowTypeAnnotation) { 707 Action::TypeResult Type 708 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc, 709 LAngleLoc, TemplateArgsPtr, 710 &TemplateArgLocations[0], 711 RAngleLoc); 712 if (Type.isInvalid()) { 713 // If we failed to parse the template ID but skipped ahead to a >, we're not 714 // going to be able to form a token annotation. Eat the '>' if present. 715 if (Tok.is(tok::greater)) 716 ConsumeToken(); 717 return true; 718 } 719 720 Tok.setKind(tok::annot_typename); 721 Tok.setAnnotationValue(Type.get()); 722 if (SS && SS->isNotEmpty()) 723 Tok.setLocation(SS->getBeginLoc()); 724 else if (TemplateKWLoc.isValid()) 725 Tok.setLocation(TemplateKWLoc); 726 else 727 Tok.setLocation(TemplateNameLoc); 728 } else { 729 // Build a template-id annotation token that can be processed 730 // later. 731 Tok.setKind(tok::annot_template_id); 732 TemplateIdAnnotation *TemplateId 733 = TemplateIdAnnotation::Allocate(TemplateArgs.size()); 734 TemplateId->TemplateNameLoc = TemplateNameLoc; 735 TemplateId->Name = Name; 736 TemplateId->Template = Template.getAs<void*>(); 737 TemplateId->Kind = TNK; 738 TemplateId->LAngleLoc = LAngleLoc; 739 TemplateId->RAngleLoc = RAngleLoc; 740 void **Args = TemplateId->getTemplateArgs(); 741 bool *ArgIsType = TemplateId->getTemplateArgIsType(); 742 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations(); 743 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) { 744 Args[Arg] = TemplateArgs[Arg]; 745 ArgIsType[Arg] = TemplateArgIsType[Arg]; 746 ArgLocs[Arg] = TemplateArgLocations[Arg]; 747 } 748 Tok.setAnnotationValue(TemplateId); 749 if (TemplateKWLoc.isValid()) 750 Tok.setLocation(TemplateKWLoc); 751 else 752 Tok.setLocation(TemplateNameLoc); 753 754 TemplateArgsPtr.release(); 755 } 756 757 // Common fields for the annotation token 758 Tok.setAnnotationEndLoc(RAngleLoc); 759 760 // In case the tokens were cached, have Preprocessor replace them with the 761 // annotation token. 762 PP.AnnotateCachedTokens(Tok); 763 return false; 764} 765 766/// \brief Replaces a template-id annotation token with a type 767/// annotation token. 768/// 769/// If there was a failure when forming the type from the template-id, 770/// a type annotation token will still be created, but will have a 771/// NULL type pointer to signify an error. 772void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) { 773 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens"); 774 775 TemplateIdAnnotation *TemplateId 776 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 777 assert((TemplateId->Kind == TNK_Type_template || 778 TemplateId->Kind == TNK_Dependent_template_name) && 779 "Only works for type and dependent templates"); 780 781 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 782 TemplateId->getTemplateArgs(), 783 TemplateId->getTemplateArgIsType(), 784 TemplateId->NumArgs); 785 786 Action::TypeResult Type 787 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template), 788 TemplateId->TemplateNameLoc, 789 TemplateId->LAngleLoc, 790 TemplateArgsPtr, 791 TemplateId->getTemplateArgLocations(), 792 TemplateId->RAngleLoc); 793 // Create the new "type" annotation token. 794 Tok.setKind(tok::annot_typename); 795 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get()); 796 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name. 797 Tok.setLocation(SS->getBeginLoc()); 798 799 // We might be backtracking, in which case we need to replace the 800 // template-id annotation token with the type annotation within the 801 // set of cached tokens. That way, we won't try to form the same 802 // class template specialization again. 803 PP.ReplaceLastTokenWithAnnotation(Tok); 804 TemplateId->Destroy(); 805} 806 807/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]). 808/// 809/// template-argument: [C++ 14.2] 810/// constant-expression 811/// type-id 812/// id-expression 813void *Parser::ParseTemplateArgument(bool &ArgIsType) { 814 // C++ [temp.arg]p2: 815 // In a template-argument, an ambiguity between a type-id and an 816 // expression is resolved to a type-id, regardless of the form of 817 // the corresponding template-parameter. 818 // 819 // Therefore, we initially try to parse a type-id. 820 if (isCXXTypeId(TypeIdAsTemplateArgument)) { 821 ArgIsType = true; 822 TypeResult TypeArg = ParseTypeName(); 823 if (TypeArg.isInvalid()) 824 return 0; 825 return TypeArg.get(); 826 } 827 828 OwningExprResult ExprArg = ParseConstantExpression(); 829 if (ExprArg.isInvalid() || !ExprArg.get()) 830 return 0; 831 832 ArgIsType = false; 833 return ExprArg.release(); 834} 835 836/// ParseTemplateArgumentList - Parse a C++ template-argument-list 837/// (C++ [temp.names]). Returns true if there was an error. 838/// 839/// template-argument-list: [C++ 14.2] 840/// template-argument 841/// template-argument-list ',' template-argument 842bool 843Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs, 844 TemplateArgIsTypeList &TemplateArgIsType, 845 TemplateArgLocationList &TemplateArgLocations) { 846 while (true) { 847 bool IsType = false; 848 SourceLocation Loc = Tok.getLocation(); 849 void *Arg = ParseTemplateArgument(IsType); 850 if (Arg) { 851 TemplateArgs.push_back(Arg); 852 TemplateArgIsType.push_back(IsType); 853 TemplateArgLocations.push_back(Loc); 854 } else { 855 SkipUntil(tok::comma, tok::greater, true, true); 856 return true; 857 } 858 859 // If the next token is a comma, consume it and keep reading 860 // arguments. 861 if (Tok.isNot(tok::comma)) break; 862 863 // Consume the comma. 864 ConsumeToken(); 865 } 866 867 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater); 868} 869 870/// \brief Parse a C++ explicit template instantiation 871/// (C++ [temp.explicit]). 872/// 873/// explicit-instantiation: 874/// 'extern' [opt] 'template' declaration 875/// 876/// Note that the 'extern' is a GNU extension and C++0x feature. 877Parser::DeclPtrTy 878Parser::ParseExplicitInstantiation(SourceLocation ExternLoc, 879 SourceLocation TemplateLoc, 880 SourceLocation &DeclEnd) { 881 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext, 882 ParsedTemplateInfo(ExternLoc, 883 TemplateLoc), 884 DeclEnd, AS_none); 885} 886