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