1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements parsing of C++ templates. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/DeclTemplate.h" 15 #include "clang/AST/ExprCXX.h" 16 #include "clang/Parse/ParseDiagnostic.h" 17 #include "clang/Parse/Parser.h" 18 #include "clang/Parse/RAIIObjectsForParser.h" 19 #include "clang/Sema/DeclSpec.h" 20 #include "clang/Sema/ParsedTemplate.h" 21 #include "clang/Sema/Scope.h" 22 #include "llvm/Support/TimeProfiler.h" 23 using namespace clang; 24 25 /// Re-enter a possible template scope, creating as many template parameter 26 /// scopes as necessary. 27 /// \return The number of template parameter scopes entered. 28 unsigned Parser::ReenterTemplateScopes(MultiParseScope &S, Decl *D) { 29 return Actions.ActOnReenterTemplateScope(D, [&] { 30 S.Enter(Scope::TemplateParamScope); 31 return Actions.getCurScope(); 32 }); 33 } 34 35 /// Parse a template declaration, explicit instantiation, or 36 /// explicit specialization. 37 Decl *Parser::ParseDeclarationStartingWithTemplate( 38 DeclaratorContext Context, SourceLocation &DeclEnd, 39 ParsedAttributes &AccessAttrs, AccessSpecifier AS) { 40 ObjCDeclContextSwitch ObjCDC(*this); 41 42 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) { 43 return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(), 44 DeclEnd, AccessAttrs, AS); 45 } 46 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs, 47 AS); 48 } 49 50 /// Parse a template declaration or an explicit specialization. 51 /// 52 /// Template declarations include one or more template parameter lists 53 /// and either the function or class template declaration. Explicit 54 /// specializations contain one or more 'template < >' prefixes 55 /// followed by a (possibly templated) declaration. Since the 56 /// syntactic form of both features is nearly identical, we parse all 57 /// of the template headers together and let semantic analysis sort 58 /// the declarations from the explicit specializations. 59 /// 60 /// template-declaration: [C++ temp] 61 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration 62 /// 63 /// template-declaration: [C++2a] 64 /// template-head declaration 65 /// template-head concept-definition 66 /// 67 /// TODO: requires-clause 68 /// template-head: [C++2a] 69 /// 'template' '<' template-parameter-list '>' 70 /// requires-clause[opt] 71 /// 72 /// explicit-specialization: [ C++ temp.expl.spec] 73 /// 'template' '<' '>' declaration 74 Decl *Parser::ParseTemplateDeclarationOrSpecialization( 75 DeclaratorContext Context, SourceLocation &DeclEnd, 76 ParsedAttributes &AccessAttrs, AccessSpecifier AS) { 77 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) && 78 "Token does not start a template declaration."); 79 80 MultiParseScope TemplateParamScopes(*this); 81 82 // Tell the action that names should be checked in the context of 83 // the declaration to come. 84 ParsingDeclRAIIObject 85 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); 86 87 // Parse multiple levels of template headers within this template 88 // parameter scope, e.g., 89 // 90 // template<typename T> 91 // template<typename U> 92 // class A<T>::B { ... }; 93 // 94 // We parse multiple levels non-recursively so that we can build a 95 // single data structure containing all of the template parameter 96 // lists to easily differentiate between the case above and: 97 // 98 // template<typename T> 99 // class A { 100 // template<typename U> class B; 101 // }; 102 // 103 // In the first case, the action for declaring A<T>::B receives 104 // both template parameter lists. In the second case, the action for 105 // defining A<T>::B receives just the inner template parameter list 106 // (and retrieves the outer template parameter list from its 107 // context). 108 bool isSpecialization = true; 109 bool LastParamListWasEmpty = false; 110 TemplateParameterLists ParamLists; 111 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 112 113 do { 114 // Consume the 'export', if any. 115 SourceLocation ExportLoc; 116 TryConsumeToken(tok::kw_export, ExportLoc); 117 118 // Consume the 'template', which should be here. 119 SourceLocation TemplateLoc; 120 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) { 121 Diag(Tok.getLocation(), diag::err_expected_template); 122 return nullptr; 123 } 124 125 // Parse the '<' template-parameter-list '>' 126 SourceLocation LAngleLoc, RAngleLoc; 127 SmallVector<NamedDecl*, 4> TemplateParams; 128 if (ParseTemplateParameters(TemplateParamScopes, 129 CurTemplateDepthTracker.getDepth(), 130 TemplateParams, LAngleLoc, RAngleLoc)) { 131 // Skip until the semi-colon or a '}'. 132 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 133 TryConsumeToken(tok::semi); 134 return nullptr; 135 } 136 137 ExprResult OptionalRequiresClauseConstraintER; 138 if (!TemplateParams.empty()) { 139 isSpecialization = false; 140 ++CurTemplateDepthTracker; 141 142 if (TryConsumeToken(tok::kw_requires)) { 143 OptionalRequiresClauseConstraintER = 144 Actions.CorrectDelayedTyposInExpr( 145 ParseConstraintLogicalOrExpression( 146 /*IsTrailingRequiresClause=*/false)); 147 if (!OptionalRequiresClauseConstraintER.isUsable()) { 148 // Skip until the semi-colon or a '}'. 149 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 150 TryConsumeToken(tok::semi); 151 return nullptr; 152 } 153 } 154 } else { 155 LastParamListWasEmpty = true; 156 } 157 158 ParamLists.push_back(Actions.ActOnTemplateParameterList( 159 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc, 160 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get())); 161 } while (Tok.isOneOf(tok::kw_export, tok::kw_template)); 162 163 // Parse the actual template declaration. 164 if (Tok.is(tok::kw_concept)) 165 return ParseConceptDefinition( 166 ParsedTemplateInfo(&ParamLists, isSpecialization, 167 LastParamListWasEmpty), 168 DeclEnd); 169 170 return ParseSingleDeclarationAfterTemplate( 171 Context, 172 ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty), 173 ParsingTemplateParams, DeclEnd, AccessAttrs, AS); 174 } 175 176 /// Parse a single declaration that declares a template, 177 /// template specialization, or explicit instantiation of a template. 178 /// 179 /// \param DeclEnd will receive the source location of the last token 180 /// within this declaration. 181 /// 182 /// \param AS the access specifier associated with this 183 /// declaration. Will be AS_none for namespace-scope declarations. 184 /// 185 /// \returns the new declaration. 186 Decl *Parser::ParseSingleDeclarationAfterTemplate( 187 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, 188 ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd, 189 ParsedAttributes &AccessAttrs, AccessSpecifier AS) { 190 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 191 "Template information required"); 192 193 if (Tok.is(tok::kw_static_assert)) { 194 // A static_assert declaration may not be templated. 195 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration) 196 << TemplateInfo.getSourceRange(); 197 // Parse the static_assert declaration to improve error recovery. 198 return ParseStaticAssertDeclaration(DeclEnd); 199 } 200 201 if (Context == DeclaratorContext::MemberContext) { 202 // We are parsing a member template. 203 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo, 204 &DiagsFromTParams); 205 return nullptr; 206 } 207 208 ParsedAttributesWithRange prefixAttrs(AttrFactory); 209 MaybeParseCXX11Attributes(prefixAttrs); 210 211 if (Tok.is(tok::kw_using)) { 212 auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd, 213 prefixAttrs); 214 if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl()) 215 return nullptr; 216 return usingDeclPtr.get().getSingleDecl(); 217 } 218 219 // Parse the declaration specifiers, stealing any diagnostics from 220 // the template parameters. 221 ParsingDeclSpec DS(*this, &DiagsFromTParams); 222 223 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, 224 getDeclSpecContextFromDeclaratorContext(Context)); 225 226 if (Tok.is(tok::semi)) { 227 ProhibitAttributes(prefixAttrs); 228 DeclEnd = ConsumeToken(); 229 RecordDecl *AnonRecord = nullptr; 230 Decl *Decl = Actions.ParsedFreeStandingDeclSpec( 231 getCurScope(), AS, DS, 232 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams 233 : MultiTemplateParamsArg(), 234 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation, 235 AnonRecord); 236 assert(!AnonRecord && 237 "Anonymous unions/structs should not be valid with template"); 238 DS.complete(Decl); 239 return Decl; 240 } 241 242 // Move the attributes from the prefix into the DS. 243 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 244 ProhibitAttributes(prefixAttrs); 245 else 246 DS.takeAttributesFrom(prefixAttrs); 247 248 // Parse the declarator. 249 ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context); 250 if (TemplateInfo.TemplateParams) 251 DeclaratorInfo.setTemplateParameterLists(*TemplateInfo.TemplateParams); 252 ParseDeclarator(DeclaratorInfo); 253 // Error parsing the declarator? 254 if (!DeclaratorInfo.hasName()) { 255 // If so, skip until the semi-colon or a }. 256 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 257 if (Tok.is(tok::semi)) 258 ConsumeToken(); 259 return nullptr; 260 } 261 262 llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() { 263 return std::string(DeclaratorInfo.getIdentifier() != nullptr 264 ? DeclaratorInfo.getIdentifier()->getName() 265 : "<unknown>"); 266 }); 267 268 LateParsedAttrList LateParsedAttrs(true); 269 if (DeclaratorInfo.isFunctionDeclarator()) { 270 if (Tok.is(tok::kw_requires)) 271 ParseTrailingRequiresClause(DeclaratorInfo); 272 273 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 274 } 275 276 if (DeclaratorInfo.isFunctionDeclarator() && 277 isStartOfFunctionDefinition(DeclaratorInfo)) { 278 279 // Function definitions are only allowed at file scope and in C++ classes. 280 // The C++ inline method definition case is handled elsewhere, so we only 281 // need to handle the file scope definition case. 282 if (Context != DeclaratorContext::FileContext) { 283 Diag(Tok, diag::err_function_definition_not_allowed); 284 SkipMalformedDecl(); 285 return nullptr; 286 } 287 288 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 289 // Recover by ignoring the 'typedef'. This was probably supposed to be 290 // the 'typename' keyword, which we should have already suggested adding 291 // if it's appropriate. 292 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef) 293 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 294 DS.ClearStorageClassSpecs(); 295 } 296 297 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 298 if (DeclaratorInfo.getName().getKind() != 299 UnqualifiedIdKind::IK_TemplateId) { 300 // If the declarator-id is not a template-id, issue a diagnostic and 301 // recover by ignoring the 'template' keyword. 302 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0; 303 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(), 304 &LateParsedAttrs); 305 } else { 306 SourceLocation LAngleLoc 307 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 308 Diag(DeclaratorInfo.getIdentifierLoc(), 309 diag::err_explicit_instantiation_with_definition) 310 << SourceRange(TemplateInfo.TemplateLoc) 311 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 312 313 // Recover as if it were an explicit specialization. 314 TemplateParameterLists FakedParamLists; 315 FakedParamLists.push_back(Actions.ActOnTemplateParameterList( 316 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None, 317 LAngleLoc, nullptr)); 318 319 return ParseFunctionDefinition( 320 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists, 321 /*isSpecialization=*/true, 322 /*lastParameterListWasEmpty=*/true), 323 &LateParsedAttrs); 324 } 325 } 326 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo, 327 &LateParsedAttrs); 328 } 329 330 // Parse this declaration. 331 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo, 332 TemplateInfo); 333 334 if (Tok.is(tok::comma)) { 335 Diag(Tok, diag::err_multiple_template_declarators) 336 << (int)TemplateInfo.Kind; 337 SkipUntil(tok::semi); 338 return ThisDecl; 339 } 340 341 // Eat the semi colon after the declaration. 342 ExpectAndConsumeSemi(diag::err_expected_semi_declaration); 343 if (LateParsedAttrs.size() > 0) 344 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false); 345 DeclaratorInfo.complete(ThisDecl); 346 return ThisDecl; 347 } 348 349 /// \brief Parse a single declaration that declares a concept. 350 /// 351 /// \param DeclEnd will receive the source location of the last token 352 /// within this declaration. 353 /// 354 /// \returns the new declaration. 355 Decl * 356 Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, 357 SourceLocation &DeclEnd) { 358 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 359 "Template information required"); 360 assert(Tok.is(tok::kw_concept) && 361 "ParseConceptDefinition must be called when at a 'concept' keyword"); 362 363 ConsumeToken(); // Consume 'concept' 364 365 SourceLocation BoolKWLoc; 366 if (TryConsumeToken(tok::kw_bool, BoolKWLoc)) 367 Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) << 368 FixItHint::CreateRemoval(SourceLocation(BoolKWLoc)); 369 370 DiagnoseAndSkipCXX11Attributes(); 371 372 CXXScopeSpec SS; 373 if (ParseOptionalCXXScopeSpecifier( 374 SS, /*ObjectType=*/nullptr, 375 /*ObjectHadErrors=*/false, /*EnteringContext=*/false, 376 /*MayBePseudoDestructor=*/nullptr, 377 /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) || 378 SS.isInvalid()) { 379 SkipUntil(tok::semi); 380 return nullptr; 381 } 382 383 if (SS.isNotEmpty()) 384 Diag(SS.getBeginLoc(), 385 diag::err_concept_definition_not_identifier); 386 387 UnqualifiedId Result; 388 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr, 389 /*ObjectHadErrors=*/false, /*EnteringContext=*/false, 390 /*AllowDestructorName=*/false, 391 /*AllowConstructorName=*/false, 392 /*AllowDeductionGuide=*/false, 393 /*TemplateKWLoc=*/nullptr, Result)) { 394 SkipUntil(tok::semi); 395 return nullptr; 396 } 397 398 if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) { 399 Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier); 400 SkipUntil(tok::semi); 401 return nullptr; 402 } 403 404 IdentifierInfo *Id = Result.Identifier; 405 SourceLocation IdLoc = Result.getBeginLoc(); 406 407 DiagnoseAndSkipCXX11Attributes(); 408 409 if (!TryConsumeToken(tok::equal)) { 410 Diag(Tok.getLocation(), diag::err_expected) << tok::equal; 411 SkipUntil(tok::semi); 412 return nullptr; 413 } 414 415 ExprResult ConstraintExprResult = 416 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression()); 417 if (ConstraintExprResult.isInvalid()) { 418 SkipUntil(tok::semi); 419 return nullptr; 420 } 421 422 DeclEnd = Tok.getLocation(); 423 ExpectAndConsumeSemi(diag::err_expected_semi_declaration); 424 Expr *ConstraintExpr = ConstraintExprResult.get(); 425 return Actions.ActOnConceptDefinition(getCurScope(), 426 *TemplateInfo.TemplateParams, 427 Id, IdLoc, ConstraintExpr); 428 } 429 430 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in 431 /// angle brackets. Depth is the depth of this template-parameter-list, which 432 /// is the number of template headers directly enclosing this template header. 433 /// TemplateParams is the current list of template parameters we're building. 434 /// The template parameter we parse will be added to this list. LAngleLoc and 435 /// RAngleLoc will receive the positions of the '<' and '>', respectively, 436 /// that enclose this template parameter list. 437 /// 438 /// \returns true if an error occurred, false otherwise. 439 bool Parser::ParseTemplateParameters( 440 MultiParseScope &TemplateScopes, unsigned Depth, 441 SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, 442 SourceLocation &RAngleLoc) { 443 // Get the template parameter list. 444 if (!TryConsumeToken(tok::less, LAngleLoc)) { 445 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template"; 446 return true; 447 } 448 449 // Try to parse the template parameter list. 450 bool Failed = false; 451 // FIXME: Missing greatergreatergreater support. 452 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater)) { 453 TemplateScopes.Enter(Scope::TemplateParamScope); 454 Failed = ParseTemplateParameterList(Depth, TemplateParams); 455 } 456 457 if (Tok.is(tok::greatergreater)) { 458 // No diagnostic required here: a template-parameter-list can only be 459 // followed by a declaration or, for a template template parameter, the 460 // 'class' keyword. Therefore, the second '>' will be diagnosed later. 461 // This matters for elegant diagnosis of: 462 // template<template<typename>> struct S; 463 Tok.setKind(tok::greater); 464 RAngleLoc = Tok.getLocation(); 465 Tok.setLocation(Tok.getLocation().getLocWithOffset(1)); 466 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) { 467 Diag(Tok.getLocation(), diag::err_expected) << tok::greater; 468 return true; 469 } 470 return false; 471 } 472 473 /// ParseTemplateParameterList - Parse a template parameter list. If 474 /// the parsing fails badly (i.e., closing bracket was left out), this 475 /// will try to put the token stream in a reasonable position (closing 476 /// a statement, etc.) and return false. 477 /// 478 /// template-parameter-list: [C++ temp] 479 /// template-parameter 480 /// template-parameter-list ',' template-parameter 481 bool 482 Parser::ParseTemplateParameterList(const unsigned Depth, 483 SmallVectorImpl<NamedDecl*> &TemplateParams) { 484 while (1) { 485 486 if (NamedDecl *TmpParam 487 = ParseTemplateParameter(Depth, TemplateParams.size())) { 488 TemplateParams.push_back(TmpParam); 489 } else { 490 // If we failed to parse a template parameter, skip until we find 491 // a comma or closing brace. 492 SkipUntil(tok::comma, tok::greater, tok::greatergreater, 493 StopAtSemi | StopBeforeMatch); 494 } 495 496 // Did we find a comma or the end of the template parameter list? 497 if (Tok.is(tok::comma)) { 498 ConsumeToken(); 499 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) { 500 // Don't consume this... that's done by template parser. 501 break; 502 } else { 503 // Somebody probably forgot to close the template. Skip ahead and 504 // try to get out of the expression. This error is currently 505 // subsumed by whatever goes on in ParseTemplateParameter. 506 Diag(Tok.getLocation(), diag::err_expected_comma_greater); 507 SkipUntil(tok::comma, tok::greater, tok::greatergreater, 508 StopAtSemi | StopBeforeMatch); 509 return false; 510 } 511 } 512 return true; 513 } 514 515 /// Determine whether the parser is at the start of a template 516 /// type parameter. 517 Parser::TPResult Parser::isStartOfTemplateTypeParameter() { 518 if (Tok.is(tok::kw_class)) { 519 // "class" may be the start of an elaborated-type-specifier or a 520 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter. 521 switch (NextToken().getKind()) { 522 case tok::equal: 523 case tok::comma: 524 case tok::greater: 525 case tok::greatergreater: 526 case tok::ellipsis: 527 return TPResult::True; 528 529 case tok::identifier: 530 // This may be either a type-parameter or an elaborated-type-specifier. 531 // We have to look further. 532 break; 533 534 default: 535 return TPResult::False; 536 } 537 538 switch (GetLookAheadToken(2).getKind()) { 539 case tok::equal: 540 case tok::comma: 541 case tok::greater: 542 case tok::greatergreater: 543 return TPResult::True; 544 545 default: 546 return TPResult::False; 547 } 548 } 549 550 if (TryAnnotateTypeConstraint()) 551 return TPResult::Error; 552 553 if (isTypeConstraintAnnotation() && 554 // Next token might be 'auto' or 'decltype', indicating that this 555 // type-constraint is in fact part of a placeholder-type-specifier of a 556 // non-type template parameter. 557 !GetLookAheadToken(Tok.is(tok::annot_cxxscope) ? 2 : 1) 558 .isOneOf(tok::kw_auto, tok::kw_decltype)) 559 return TPResult::True; 560 561 // 'typedef' is a reasonably-common typo/thinko for 'typename', and is 562 // ill-formed otherwise. 563 if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef)) 564 return TPResult::False; 565 566 // C++ [temp.param]p2: 567 // There is no semantic difference between class and typename in a 568 // template-parameter. typename followed by an unqualified-id 569 // names a template type parameter. typename followed by a 570 // qualified-id denotes the type in a non-type 571 // parameter-declaration. 572 Token Next = NextToken(); 573 574 // If we have an identifier, skip over it. 575 if (Next.getKind() == tok::identifier) 576 Next = GetLookAheadToken(2); 577 578 switch (Next.getKind()) { 579 case tok::equal: 580 case tok::comma: 581 case tok::greater: 582 case tok::greatergreater: 583 case tok::ellipsis: 584 return TPResult::True; 585 586 case tok::kw_typename: 587 case tok::kw_typedef: 588 case tok::kw_class: 589 // These indicate that a comma was missed after a type parameter, not that 590 // we have found a non-type parameter. 591 return TPResult::True; 592 593 default: 594 return TPResult::False; 595 } 596 } 597 598 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]). 599 /// 600 /// template-parameter: [C++ temp.param] 601 /// type-parameter 602 /// parameter-declaration 603 /// 604 /// type-parameter: (See below) 605 /// type-parameter-key ...[opt] identifier[opt] 606 /// type-parameter-key identifier[opt] = type-id 607 /// (C++2a) type-constraint ...[opt] identifier[opt] 608 /// (C++2a) type-constraint identifier[opt] = type-id 609 /// 'template' '<' template-parameter-list '>' type-parameter-key 610 /// ...[opt] identifier[opt] 611 /// 'template' '<' template-parameter-list '>' type-parameter-key 612 /// identifier[opt] '=' id-expression 613 /// 614 /// type-parameter-key: 615 /// class 616 /// typename 617 /// 618 NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) { 619 620 switch (isStartOfTemplateTypeParameter()) { 621 case TPResult::True: 622 // Is there just a typo in the input code? ('typedef' instead of 623 // 'typename') 624 if (Tok.is(tok::kw_typedef)) { 625 Diag(Tok.getLocation(), diag::err_expected_template_parameter); 626 627 Diag(Tok.getLocation(), diag::note_meant_to_use_typename) 628 << FixItHint::CreateReplacement(CharSourceRange::getCharRange( 629 Tok.getLocation(), 630 Tok.getEndLoc()), 631 "typename"); 632 633 Tok.setKind(tok::kw_typename); 634 } 635 636 return ParseTypeParameter(Depth, Position); 637 case TPResult::False: 638 break; 639 640 case TPResult::Error: { 641 // We return an invalid parameter as opposed to null to avoid having bogus 642 // diagnostics about an empty template parameter list. 643 // FIXME: Fix ParseTemplateParameterList to better handle nullptr results 644 // from here. 645 // Return a NTTP as if there was an error in a scope specifier, the user 646 // probably meant to write the type of a NTTP. 647 DeclSpec DS(getAttrFactory()); 648 DS.SetTypeSpecError(); 649 Declarator D(DS, DeclaratorContext::TemplateParamContext); 650 D.SetIdentifier(nullptr, Tok.getLocation()); 651 D.setInvalidType(true); 652 NamedDecl *ErrorParam = Actions.ActOnNonTypeTemplateParameter( 653 getCurScope(), D, Depth, Position, /*EqualLoc=*/SourceLocation(), 654 /*DefaultArg=*/nullptr); 655 ErrorParam->setInvalidDecl(true); 656 SkipUntil(tok::comma, tok::greater, tok::greatergreater, 657 StopAtSemi | StopBeforeMatch); 658 return ErrorParam; 659 } 660 661 case TPResult::Ambiguous: 662 llvm_unreachable("template param classification can't be ambiguous"); 663 } 664 665 if (Tok.is(tok::kw_template)) 666 return ParseTemplateTemplateParameter(Depth, Position); 667 668 // If it's none of the above, then it must be a parameter declaration. 669 // NOTE: This will pick up errors in the closure of the template parameter 670 // list (e.g., template < ; Check here to implement >> style closures. 671 return ParseNonTypeTemplateParameter(Depth, Position); 672 } 673 674 /// Check whether the current token is a template-id annotation denoting a 675 /// type-constraint. 676 bool Parser::isTypeConstraintAnnotation() { 677 const Token &T = Tok.is(tok::annot_cxxscope) ? NextToken() : Tok; 678 if (T.isNot(tok::annot_template_id)) 679 return false; 680 const auto *ExistingAnnot = 681 static_cast<TemplateIdAnnotation *>(T.getAnnotationValue()); 682 return ExistingAnnot->Kind == TNK_Concept_template; 683 } 684 685 /// Try parsing a type-constraint at the current location. 686 /// 687 /// type-constraint: 688 /// nested-name-specifier[opt] concept-name 689 /// nested-name-specifier[opt] concept-name 690 /// '<' template-argument-list[opt] '>'[opt] 691 /// 692 /// \returns true if an error occurred, and false otherwise. 693 bool Parser::TryAnnotateTypeConstraint() { 694 if (!getLangOpts().CPlusPlus20) 695 return false; 696 CXXScopeSpec SS; 697 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 698 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 699 /*ObjectHadErrors=*/false, 700 /*EnteringContext=*/false, 701 /*MayBePseudoDestructor=*/nullptr, 702 // If this is not a type-constraint, then 703 // this scope-spec is part of the typename 704 // of a non-type template parameter 705 /*IsTypename=*/true, /*LastII=*/nullptr, 706 // We won't find concepts in 707 // non-namespaces anyway, so might as well 708 // parse this correctly for possible type 709 // names. 710 /*OnlyNamespace=*/false)) 711 return true; 712 713 if (Tok.is(tok::identifier)) { 714 UnqualifiedId PossibleConceptName; 715 PossibleConceptName.setIdentifier(Tok.getIdentifierInfo(), 716 Tok.getLocation()); 717 718 TemplateTy PossibleConcept; 719 bool MemberOfUnknownSpecialization = false; 720 auto TNK = Actions.isTemplateName(getCurScope(), SS, 721 /*hasTemplateKeyword=*/false, 722 PossibleConceptName, 723 /*ObjectType=*/ParsedType(), 724 /*EnteringContext=*/false, 725 PossibleConcept, 726 MemberOfUnknownSpecialization, 727 /*Disambiguation=*/true); 728 if (MemberOfUnknownSpecialization || !PossibleConcept || 729 TNK != TNK_Concept_template) { 730 if (SS.isNotEmpty()) 731 AnnotateScopeToken(SS, !WasScopeAnnotation); 732 return false; 733 } 734 735 // At this point we're sure we're dealing with a constrained parameter. It 736 // may or may not have a template parameter list following the concept 737 // name. 738 if (AnnotateTemplateIdToken(PossibleConcept, TNK, SS, 739 /*TemplateKWLoc=*/SourceLocation(), 740 PossibleConceptName, 741 /*AllowTypeAnnotation=*/false, 742 /*TypeConstraint=*/true)) 743 return true; 744 } 745 746 if (SS.isNotEmpty()) 747 AnnotateScopeToken(SS, !WasScopeAnnotation); 748 return false; 749 } 750 751 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]). 752 /// Other kinds of template parameters are parsed in 753 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter. 754 /// 755 /// type-parameter: [C++ temp.param] 756 /// 'class' ...[opt][C++0x] identifier[opt] 757 /// 'class' identifier[opt] '=' type-id 758 /// 'typename' ...[opt][C++0x] identifier[opt] 759 /// 'typename' identifier[opt] '=' type-id 760 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) { 761 assert((Tok.isOneOf(tok::kw_class, tok::kw_typename) || 762 isTypeConstraintAnnotation()) && 763 "A type-parameter starts with 'class', 'typename' or a " 764 "type-constraint"); 765 766 CXXScopeSpec TypeConstraintSS; 767 TemplateIdAnnotation *TypeConstraint = nullptr; 768 bool TypenameKeyword = false; 769 SourceLocation KeyLoc; 770 ParseOptionalCXXScopeSpecifier(TypeConstraintSS, /*ObjectType=*/nullptr, 771 /*ObjectHadErrors=*/false, 772 /*EnteringContext*/ false); 773 if (Tok.is(tok::annot_template_id)) { 774 // Consume the 'type-constraint'. 775 TypeConstraint = 776 static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 777 assert(TypeConstraint->Kind == TNK_Concept_template && 778 "stray non-concept template-id annotation"); 779 KeyLoc = ConsumeAnnotationToken(); 780 } else { 781 assert(TypeConstraintSS.isEmpty() && 782 "expected type constraint after scope specifier"); 783 784 // Consume the 'class' or 'typename' keyword. 785 TypenameKeyword = Tok.is(tok::kw_typename); 786 KeyLoc = ConsumeToken(); 787 } 788 789 // Grab the ellipsis (if given). 790 SourceLocation EllipsisLoc; 791 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { 792 Diag(EllipsisLoc, 793 getLangOpts().CPlusPlus11 794 ? diag::warn_cxx98_compat_variadic_templates 795 : diag::ext_variadic_templates); 796 } 797 798 // Grab the template parameter name (if given) 799 SourceLocation NameLoc = Tok.getLocation(); 800 IdentifierInfo *ParamName = nullptr; 801 if (Tok.is(tok::identifier)) { 802 ParamName = Tok.getIdentifierInfo(); 803 ConsumeToken(); 804 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater, 805 tok::greatergreater)) { 806 // Unnamed template parameter. Don't have to do anything here, just 807 // don't consume this token. 808 } else { 809 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 810 return nullptr; 811 } 812 813 // Recover from misplaced ellipsis. 814 bool AlreadyHasEllipsis = EllipsisLoc.isValid(); 815 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 816 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true); 817 818 // Grab a default argument (if available). 819 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before 820 // we introduce the type parameter into the local scope. 821 SourceLocation EqualLoc; 822 ParsedType DefaultArg; 823 if (TryConsumeToken(tok::equal, EqualLoc)) 824 DefaultArg = ParseTypeName(/*Range=*/nullptr, 825 DeclaratorContext::TemplateTypeArgContext) 826 .get(); 827 828 NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(), 829 TypenameKeyword, EllipsisLoc, 830 KeyLoc, ParamName, NameLoc, 831 Depth, Position, EqualLoc, 832 DefaultArg, 833 TypeConstraint != nullptr); 834 835 if (TypeConstraint) { 836 Actions.ActOnTypeConstraint(TypeConstraintSS, TypeConstraint, 837 cast<TemplateTypeParmDecl>(NewDecl), 838 EllipsisLoc); 839 } 840 841 return NewDecl; 842 } 843 844 /// ParseTemplateTemplateParameter - Handle the parsing of template 845 /// template parameters. 846 /// 847 /// type-parameter: [C++ temp.param] 848 /// 'template' '<' template-parameter-list '>' type-parameter-key 849 /// ...[opt] identifier[opt] 850 /// 'template' '<' template-parameter-list '>' type-parameter-key 851 /// identifier[opt] = id-expression 852 /// type-parameter-key: 853 /// 'class' 854 /// 'typename' [C++1z] 855 NamedDecl * 856 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { 857 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword"); 858 859 // Handle the template <...> part. 860 SourceLocation TemplateLoc = ConsumeToken(); 861 SmallVector<NamedDecl*,8> TemplateParams; 862 SourceLocation LAngleLoc, RAngleLoc; 863 { 864 MultiParseScope TemplateParmScope(*this); 865 if (ParseTemplateParameters(TemplateParmScope, Depth + 1, TemplateParams, 866 LAngleLoc, RAngleLoc)) { 867 return nullptr; 868 } 869 } 870 871 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used. 872 // Generate a meaningful error if the user forgot to put class before the 873 // identifier, comma, or greater. Provide a fixit if the identifier, comma, 874 // or greater appear immediately or after 'struct'. In the latter case, 875 // replace the keyword with 'class'. 876 if (!TryConsumeToken(tok::kw_class)) { 877 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct); 878 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok; 879 if (Tok.is(tok::kw_typename)) { 880 Diag(Tok.getLocation(), 881 getLangOpts().CPlusPlus17 882 ? diag::warn_cxx14_compat_template_template_param_typename 883 : diag::ext_template_template_param_typename) 884 << (!getLangOpts().CPlusPlus17 885 ? FixItHint::CreateReplacement(Tok.getLocation(), "class") 886 : FixItHint()); 887 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater, 888 tok::greatergreater, tok::ellipsis)) { 889 Diag(Tok.getLocation(), diag::err_class_on_template_template_param) 890 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class") 891 : FixItHint::CreateInsertion(Tok.getLocation(), "class ")); 892 } else 893 Diag(Tok.getLocation(), diag::err_class_on_template_template_param); 894 895 if (Replace) 896 ConsumeToken(); 897 } 898 899 // Parse the ellipsis, if given. 900 SourceLocation EllipsisLoc; 901 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 902 Diag(EllipsisLoc, 903 getLangOpts().CPlusPlus11 904 ? diag::warn_cxx98_compat_variadic_templates 905 : diag::ext_variadic_templates); 906 907 // Get the identifier, if given. 908 SourceLocation NameLoc = Tok.getLocation(); 909 IdentifierInfo *ParamName = nullptr; 910 if (Tok.is(tok::identifier)) { 911 ParamName = Tok.getIdentifierInfo(); 912 ConsumeToken(); 913 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater, 914 tok::greatergreater)) { 915 // Unnamed template parameter. Don't have to do anything here, just 916 // don't consume this token. 917 } else { 918 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 919 return nullptr; 920 } 921 922 // Recover from misplaced ellipsis. 923 bool AlreadyHasEllipsis = EllipsisLoc.isValid(); 924 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 925 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true); 926 927 TemplateParameterList *ParamList = 928 Actions.ActOnTemplateParameterList(Depth, SourceLocation(), 929 TemplateLoc, LAngleLoc, 930 TemplateParams, 931 RAngleLoc, nullptr); 932 933 // Grab a default argument (if available). 934 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before 935 // we introduce the template parameter into the local scope. 936 SourceLocation EqualLoc; 937 ParsedTemplateArgument DefaultArg; 938 if (TryConsumeToken(tok::equal, EqualLoc)) { 939 DefaultArg = ParseTemplateTemplateArgument(); 940 if (DefaultArg.isInvalid()) { 941 Diag(Tok.getLocation(), 942 diag::err_default_template_template_parameter_not_template); 943 SkipUntil(tok::comma, tok::greater, tok::greatergreater, 944 StopAtSemi | StopBeforeMatch); 945 } 946 } 947 948 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc, 949 ParamList, EllipsisLoc, 950 ParamName, NameLoc, Depth, 951 Position, EqualLoc, DefaultArg); 952 } 953 954 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type 955 /// template parameters (e.g., in "template<int Size> class array;"). 956 /// 957 /// template-parameter: 958 /// ... 959 /// parameter-declaration 960 NamedDecl * 961 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { 962 // Parse the declaration-specifiers (i.e., the type). 963 // FIXME: The type should probably be restricted in some way... Not all 964 // declarators (parts of declarators?) are accepted for parameters. 965 DeclSpec DS(AttrFactory); 966 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, 967 DeclSpecContext::DSC_template_param); 968 969 // Parse this as a typename. 970 Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext); 971 ParseDeclarator(ParamDecl); 972 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 973 Diag(Tok.getLocation(), diag::err_expected_template_parameter); 974 return nullptr; 975 } 976 977 // Recover from misplaced ellipsis. 978 SourceLocation EllipsisLoc; 979 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 980 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl); 981 982 // If there is a default value, parse it. 983 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before 984 // we introduce the template parameter into the local scope. 985 SourceLocation EqualLoc; 986 ExprResult DefaultArg; 987 if (TryConsumeToken(tok::equal, EqualLoc)) { 988 // C++ [temp.param]p15: 989 // When parsing a default template-argument for a non-type 990 // template-parameter, the first non-nested > is taken as the 991 // end of the template-parameter-list rather than a greater-than 992 // operator. 993 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); 994 EnterExpressionEvaluationContext ConstantEvaluated( 995 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); 996 997 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 998 if (DefaultArg.isInvalid()) 999 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch); 1000 } 1001 1002 // Create the parameter. 1003 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, 1004 Depth, Position, EqualLoc, 1005 DefaultArg.get()); 1006 } 1007 1008 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, 1009 SourceLocation CorrectLoc, 1010 bool AlreadyHasEllipsis, 1011 bool IdentifierHasName) { 1012 FixItHint Insertion; 1013 if (!AlreadyHasEllipsis) 1014 Insertion = FixItHint::CreateInsertion(CorrectLoc, "..."); 1015 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration) 1016 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion 1017 << !IdentifierHasName; 1018 } 1019 1020 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, 1021 Declarator &D) { 1022 assert(EllipsisLoc.isValid()); 1023 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid(); 1024 if (!AlreadyHasEllipsis) 1025 D.setEllipsisLoc(EllipsisLoc); 1026 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(), 1027 AlreadyHasEllipsis, D.hasName()); 1028 } 1029 1030 /// Parses a '>' at the end of a template list. 1031 /// 1032 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries 1033 /// to determine if these tokens were supposed to be a '>' followed by 1034 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary. 1035 /// 1036 /// \param RAngleLoc the location of the consumed '>'. 1037 /// 1038 /// \param ConsumeLastToken if true, the '>' is consumed. 1039 /// 1040 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C 1041 /// type parameter or type argument list, rather than a C++ template parameter 1042 /// or argument list. 1043 /// 1044 /// \returns true, if current token does not start with '>', false otherwise. 1045 bool Parser::ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, 1046 SourceLocation &RAngleLoc, 1047 bool ConsumeLastToken, 1048 bool ObjCGenericList) { 1049 // What will be left once we've consumed the '>'. 1050 tok::TokenKind RemainingToken; 1051 const char *ReplacementStr = "> >"; 1052 bool MergeWithNextToken = false; 1053 1054 switch (Tok.getKind()) { 1055 default: 1056 Diag(getEndOfPreviousToken(), diag::err_expected) << tok::greater; 1057 Diag(LAngleLoc, diag::note_matching) << tok::less; 1058 return true; 1059 1060 case tok::greater: 1061 // Determine the location of the '>' token. Only consume this token 1062 // if the caller asked us to. 1063 RAngleLoc = Tok.getLocation(); 1064 if (ConsumeLastToken) 1065 ConsumeToken(); 1066 return false; 1067 1068 case tok::greatergreater: 1069 RemainingToken = tok::greater; 1070 break; 1071 1072 case tok::greatergreatergreater: 1073 RemainingToken = tok::greatergreater; 1074 break; 1075 1076 case tok::greaterequal: 1077 RemainingToken = tok::equal; 1078 ReplacementStr = "> ="; 1079 1080 // Join two adjacent '=' tokens into one, for cases like: 1081 // void (*p)() = f<int>; 1082 // return f<int>==p; 1083 if (NextToken().is(tok::equal) && 1084 areTokensAdjacent(Tok, NextToken())) { 1085 RemainingToken = tok::equalequal; 1086 MergeWithNextToken = true; 1087 } 1088 break; 1089 1090 case tok::greatergreaterequal: 1091 RemainingToken = tok::greaterequal; 1092 break; 1093 } 1094 1095 // This template-id is terminated by a token that starts with a '>'. 1096 // Outside C++11 and Objective-C, this is now error recovery. 1097 // 1098 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we 1099 // extend that treatment to also apply to the '>>>' token. 1100 // 1101 // Objective-C allows this in its type parameter / argument lists. 1102 1103 SourceLocation TokBeforeGreaterLoc = PrevTokLocation; 1104 SourceLocation TokLoc = Tok.getLocation(); 1105 Token Next = NextToken(); 1106 1107 // Whether splitting the current token after the '>' would undesirably result 1108 // in the remaining token pasting with the token after it. This excludes the 1109 // MergeWithNextToken cases, which we've already handled. 1110 bool PreventMergeWithNextToken = 1111 (RemainingToken == tok::greater || 1112 RemainingToken == tok::greatergreater) && 1113 (Next.isOneOf(tok::greater, tok::greatergreater, 1114 tok::greatergreatergreater, tok::equal, tok::greaterequal, 1115 tok::greatergreaterequal, tok::equalequal)) && 1116 areTokensAdjacent(Tok, Next); 1117 1118 // Diagnose this situation as appropriate. 1119 if (!ObjCGenericList) { 1120 // The source range of the replaced token(s). 1121 CharSourceRange ReplacementRange = CharSourceRange::getCharRange( 1122 TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(), 1123 getLangOpts())); 1124 1125 // A hint to put a space between the '>>'s. In order to make the hint as 1126 // clear as possible, we include the characters either side of the space in 1127 // the replacement, rather than just inserting a space at SecondCharLoc. 1128 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange, 1129 ReplacementStr); 1130 1131 // A hint to put another space after the token, if it would otherwise be 1132 // lexed differently. 1133 FixItHint Hint2; 1134 if (PreventMergeWithNextToken) 1135 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " "); 1136 1137 unsigned DiagId = diag::err_two_right_angle_brackets_need_space; 1138 if (getLangOpts().CPlusPlus11 && 1139 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater))) 1140 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets; 1141 else if (Tok.is(tok::greaterequal)) 1142 DiagId = diag::err_right_angle_bracket_equal_needs_space; 1143 Diag(TokLoc, DiagId) << Hint1 << Hint2; 1144 } 1145 1146 // Find the "length" of the resulting '>' token. This is not always 1, as it 1147 // can contain escaped newlines. 1148 unsigned GreaterLength = Lexer::getTokenPrefixLength( 1149 TokLoc, 1, PP.getSourceManager(), getLangOpts()); 1150 1151 // Annotate the source buffer to indicate that we split the token after the 1152 // '>'. This allows us to properly find the end of, and extract the spelling 1153 // of, the '>' token later. 1154 RAngleLoc = PP.SplitToken(TokLoc, GreaterLength); 1155 1156 // Strip the initial '>' from the token. 1157 bool CachingTokens = PP.IsPreviousCachedToken(Tok); 1158 1159 Token Greater = Tok; 1160 Greater.setLocation(RAngleLoc); 1161 Greater.setKind(tok::greater); 1162 Greater.setLength(GreaterLength); 1163 1164 unsigned OldLength = Tok.getLength(); 1165 if (MergeWithNextToken) { 1166 ConsumeToken(); 1167 OldLength += Tok.getLength(); 1168 } 1169 1170 Tok.setKind(RemainingToken); 1171 Tok.setLength(OldLength - GreaterLength); 1172 1173 // Split the second token if lexing it normally would lex a different token 1174 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>'). 1175 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength); 1176 if (PreventMergeWithNextToken) 1177 AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength()); 1178 Tok.setLocation(AfterGreaterLoc); 1179 1180 // Update the token cache to match what we just did if necessary. 1181 if (CachingTokens) { 1182 // If the previous cached token is being merged, delete it. 1183 if (MergeWithNextToken) 1184 PP.ReplacePreviousCachedToken({}); 1185 1186 if (ConsumeLastToken) 1187 PP.ReplacePreviousCachedToken({Greater, Tok}); 1188 else 1189 PP.ReplacePreviousCachedToken({Greater}); 1190 } 1191 1192 if (ConsumeLastToken) { 1193 PrevTokLocation = RAngleLoc; 1194 } else { 1195 PrevTokLocation = TokBeforeGreaterLoc; 1196 PP.EnterToken(Tok, /*IsReinject=*/true); 1197 Tok = Greater; 1198 } 1199 1200 return false; 1201 } 1202 1203 1204 /// Parses a template-id that after the template name has 1205 /// already been parsed. 1206 /// 1207 /// This routine takes care of parsing the enclosed template argument 1208 /// list ('<' template-parameter-list [opt] '>') and placing the 1209 /// results into a form that can be transferred to semantic analysis. 1210 /// 1211 /// \param ConsumeLastToken if true, then we will consume the last 1212 /// token that forms the template-id. Otherwise, we will leave the 1213 /// last token in the stream (e.g., so that it can be replaced with an 1214 /// annotation token). 1215 bool 1216 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, 1217 SourceLocation &LAngleLoc, 1218 TemplateArgList &TemplateArgs, 1219 SourceLocation &RAngleLoc) { 1220 assert(Tok.is(tok::less) && "Must have already parsed the template-name"); 1221 1222 // Consume the '<'. 1223 LAngleLoc = ConsumeToken(); 1224 1225 // Parse the optional template-argument-list. 1226 bool Invalid = false; 1227 { 1228 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); 1229 if (!Tok.isOneOf(tok::greater, tok::greatergreater, 1230 tok::greatergreatergreater, tok::greaterequal, 1231 tok::greatergreaterequal)) 1232 Invalid = ParseTemplateArgumentList(TemplateArgs); 1233 1234 if (Invalid) { 1235 // Try to find the closing '>'. 1236 if (getLangOpts().CPlusPlus11) 1237 SkipUntil(tok::greater, tok::greatergreater, 1238 tok::greatergreatergreater, StopAtSemi | StopBeforeMatch); 1239 else 1240 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch); 1241 } 1242 } 1243 1244 return ParseGreaterThanInTemplateList(LAngleLoc, RAngleLoc, ConsumeLastToken, 1245 /*ObjCGenericList=*/false) || 1246 Invalid; 1247 } 1248 1249 /// Replace the tokens that form a simple-template-id with an 1250 /// annotation token containing the complete template-id. 1251 /// 1252 /// The first token in the stream must be the name of a template that 1253 /// is followed by a '<'. This routine will parse the complete 1254 /// simple-template-id and replace the tokens with a single annotation 1255 /// token with one of two different kinds: if the template-id names a 1256 /// type (and \p AllowTypeAnnotation is true), the annotation token is 1257 /// a type annotation that includes the optional nested-name-specifier 1258 /// (\p SS). Otherwise, the annotation token is a template-id 1259 /// annotation that does not include the optional 1260 /// nested-name-specifier. 1261 /// 1262 /// \param Template the declaration of the template named by the first 1263 /// token (an identifier), as returned from \c Action::isTemplateName(). 1264 /// 1265 /// \param TNK the kind of template that \p Template 1266 /// refers to, as returned from \c Action::isTemplateName(). 1267 /// 1268 /// \param SS if non-NULL, the nested-name-specifier that precedes 1269 /// this template name. 1270 /// 1271 /// \param TemplateKWLoc if valid, specifies that this template-id 1272 /// annotation was preceded by the 'template' keyword and gives the 1273 /// location of that keyword. If invalid (the default), then this 1274 /// template-id was not preceded by a 'template' keyword. 1275 /// 1276 /// \param AllowTypeAnnotation if true (the default), then a 1277 /// simple-template-id that refers to a class template, template 1278 /// template parameter, or other template that produces a type will be 1279 /// replaced with a type annotation token. Otherwise, the 1280 /// simple-template-id is always replaced with a template-id 1281 /// annotation token. 1282 /// 1283 /// \param TypeConstraint if true, then this is actually a type-constraint, 1284 /// meaning that the template argument list can be omitted (and the template in 1285 /// question must be a concept). 1286 /// 1287 /// If an unrecoverable parse error occurs and no annotation token can be 1288 /// formed, this function returns true. 1289 /// 1290 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, 1291 CXXScopeSpec &SS, 1292 SourceLocation TemplateKWLoc, 1293 UnqualifiedId &TemplateName, 1294 bool AllowTypeAnnotation, 1295 bool TypeConstraint) { 1296 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++"); 1297 assert((Tok.is(tok::less) || TypeConstraint) && 1298 "Parser isn't at the beginning of a template-id"); 1299 assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be " 1300 "a type annotation"); 1301 assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint " 1302 "must accompany a concept name"); 1303 assert((Template || TNK == TNK_Non_template) && "missing template name"); 1304 1305 // Consume the template-name. 1306 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin(); 1307 1308 // Parse the enclosed template argument list. 1309 SourceLocation LAngleLoc, RAngleLoc; 1310 TemplateArgList TemplateArgs; 1311 bool ArgsInvalid = false; 1312 if (!TypeConstraint || Tok.is(tok::less)) { 1313 ArgsInvalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc, 1314 TemplateArgs, RAngleLoc); 1315 // If we couldn't recover from invalid arguments, don't form an annotation 1316 // token -- we don't know how much to annotate. 1317 // FIXME: This can lead to duplicate diagnostics if we retry parsing this 1318 // template-id in another context. Try to annotate anyway? 1319 if (RAngleLoc.isInvalid()) 1320 return true; 1321 } 1322 1323 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs); 1324 1325 // Build the annotation token. 1326 if (TNK == TNK_Type_template && AllowTypeAnnotation) { 1327 TypeResult Type = ArgsInvalid 1328 ? TypeError() 1329 : Actions.ActOnTemplateIdType( 1330 getCurScope(), SS, TemplateKWLoc, Template, 1331 TemplateName.Identifier, TemplateNameLoc, 1332 LAngleLoc, TemplateArgsPtr, RAngleLoc); 1333 1334 Tok.setKind(tok::annot_typename); 1335 setTypeAnnotation(Tok, Type); 1336 if (SS.isNotEmpty()) 1337 Tok.setLocation(SS.getBeginLoc()); 1338 else if (TemplateKWLoc.isValid()) 1339 Tok.setLocation(TemplateKWLoc); 1340 else 1341 Tok.setLocation(TemplateNameLoc); 1342 } else { 1343 // Build a template-id annotation token that can be processed 1344 // later. 1345 Tok.setKind(tok::annot_template_id); 1346 1347 IdentifierInfo *TemplateII = 1348 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier 1349 ? TemplateName.Identifier 1350 : nullptr; 1351 1352 OverloadedOperatorKind OpKind = 1353 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier 1354 ? OO_None 1355 : TemplateName.OperatorFunctionId.Operator; 1356 1357 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create( 1358 TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK, 1359 LAngleLoc, RAngleLoc, TemplateArgs, ArgsInvalid, TemplateIds); 1360 1361 Tok.setAnnotationValue(TemplateId); 1362 if (TemplateKWLoc.isValid()) 1363 Tok.setLocation(TemplateKWLoc); 1364 else 1365 Tok.setLocation(TemplateNameLoc); 1366 } 1367 1368 // Common fields for the annotation token 1369 Tok.setAnnotationEndLoc(RAngleLoc); 1370 1371 // In case the tokens were cached, have Preprocessor replace them with the 1372 // annotation token. 1373 PP.AnnotateCachedTokens(Tok); 1374 return false; 1375 } 1376 1377 /// Replaces a template-id annotation token with a type 1378 /// annotation token. 1379 /// 1380 /// If there was a failure when forming the type from the template-id, 1381 /// a type annotation token will still be created, but will have a 1382 /// NULL type pointer to signify an error. 1383 /// 1384 /// \param SS The scope specifier appearing before the template-id, if any. 1385 /// 1386 /// \param IsClassName Is this template-id appearing in a context where we 1387 /// know it names a class, such as in an elaborated-type-specifier or 1388 /// base-specifier? ('typename' and 'template' are unneeded and disallowed 1389 /// in those contexts.) 1390 void Parser::AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, 1391 bool IsClassName) { 1392 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens"); 1393 1394 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1395 assert(TemplateId->mightBeType() && 1396 "Only works for type and dependent templates"); 1397 1398 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1399 TemplateId->NumArgs); 1400 1401 TypeResult Type = 1402 TemplateId->isInvalid() 1403 ? TypeError() 1404 : Actions.ActOnTemplateIdType( 1405 getCurScope(), SS, TemplateId->TemplateKWLoc, 1406 TemplateId->Template, TemplateId->Name, 1407 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, 1408 TemplateArgsPtr, TemplateId->RAngleLoc, 1409 /*IsCtorOrDtorName*/ false, IsClassName); 1410 // Create the new "type" annotation token. 1411 Tok.setKind(tok::annot_typename); 1412 setTypeAnnotation(Tok, Type); 1413 if (SS.isNotEmpty()) // it was a C++ qualified type name. 1414 Tok.setLocation(SS.getBeginLoc()); 1415 // End location stays the same 1416 1417 // Replace the template-id annotation token, and possible the scope-specifier 1418 // that precedes it, with the typename annotation token. 1419 PP.AnnotateCachedTokens(Tok); 1420 } 1421 1422 /// Determine whether the given token can end a template argument. 1423 static bool isEndOfTemplateArgument(Token Tok) { 1424 // FIXME: Handle '>>>'. 1425 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater, 1426 tok::greatergreatergreater); 1427 } 1428 1429 /// Parse a C++ template template argument. 1430 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { 1431 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) && 1432 !Tok.is(tok::annot_cxxscope)) 1433 return ParsedTemplateArgument(); 1434 1435 // C++0x [temp.arg.template]p1: 1436 // A template-argument for a template template-parameter shall be the name 1437 // of a class template or an alias template, expressed as id-expression. 1438 // 1439 // We parse an id-expression that refers to a class template or alias 1440 // template. The grammar we parse is: 1441 // 1442 // nested-name-specifier[opt] template[opt] identifier ...[opt] 1443 // 1444 // followed by a token that terminates a template argument, such as ',', 1445 // '>', or (in some cases) '>>'. 1446 CXXScopeSpec SS; // nested-name-specifier, if present 1447 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1448 /*ObjectHadErrors=*/false, 1449 /*EnteringContext=*/false); 1450 1451 ParsedTemplateArgument Result; 1452 SourceLocation EllipsisLoc; 1453 if (SS.isSet() && Tok.is(tok::kw_template)) { 1454 // Parse the optional 'template' keyword following the 1455 // nested-name-specifier. 1456 SourceLocation TemplateKWLoc = ConsumeToken(); 1457 1458 if (Tok.is(tok::identifier)) { 1459 // We appear to have a dependent template name. 1460 UnqualifiedId Name; 1461 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1462 ConsumeToken(); // the identifier 1463 1464 TryConsumeToken(tok::ellipsis, EllipsisLoc); 1465 1466 // If the next token signals the end of a template argument, then we have 1467 // a (possibly-dependent) template name that could be a template template 1468 // argument. 1469 TemplateTy Template; 1470 if (isEndOfTemplateArgument(Tok) && 1471 Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Name, 1472 /*ObjectType=*/nullptr, 1473 /*EnteringContext=*/false, Template)) 1474 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); 1475 } 1476 } else if (Tok.is(tok::identifier)) { 1477 // We may have a (non-dependent) template name. 1478 TemplateTy Template; 1479 UnqualifiedId Name; 1480 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1481 ConsumeToken(); // the identifier 1482 1483 TryConsumeToken(tok::ellipsis, EllipsisLoc); 1484 1485 if (isEndOfTemplateArgument(Tok)) { 1486 bool MemberOfUnknownSpecialization; 1487 TemplateNameKind TNK = Actions.isTemplateName( 1488 getCurScope(), SS, 1489 /*hasTemplateKeyword=*/false, Name, 1490 /*ObjectType=*/nullptr, 1491 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization); 1492 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) { 1493 // We have an id-expression that refers to a class template or 1494 // (C++0x) alias template. 1495 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); 1496 } 1497 } 1498 } 1499 1500 // If this is a pack expansion, build it as such. 1501 if (EllipsisLoc.isValid() && !Result.isInvalid()) 1502 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc); 1503 1504 return Result; 1505 } 1506 1507 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]). 1508 /// 1509 /// template-argument: [C++ 14.2] 1510 /// constant-expression 1511 /// type-id 1512 /// id-expression 1513 ParsedTemplateArgument Parser::ParseTemplateArgument() { 1514 // C++ [temp.arg]p2: 1515 // In a template-argument, an ambiguity between a type-id and an 1516 // expression is resolved to a type-id, regardless of the form of 1517 // the corresponding template-parameter. 1518 // 1519 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look 1520 // up and annotate an identifier as an id-expression during disambiguation, 1521 // so enter the appropriate context for a constant expression template 1522 // argument before trying to disambiguate. 1523 1524 EnterExpressionEvaluationContext EnterConstantEvaluated( 1525 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated, 1526 /*LambdaContextDecl=*/nullptr, 1527 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument); 1528 if (isCXXTypeId(TypeIdAsTemplateArgument)) { 1529 TypeResult TypeArg = ParseTypeName( 1530 /*Range=*/nullptr, DeclaratorContext::TemplateArgContext); 1531 return Actions.ActOnTemplateTypeArgument(TypeArg); 1532 } 1533 1534 // Try to parse a template template argument. 1535 { 1536 TentativeParsingAction TPA(*this); 1537 1538 ParsedTemplateArgument TemplateTemplateArgument 1539 = ParseTemplateTemplateArgument(); 1540 if (!TemplateTemplateArgument.isInvalid()) { 1541 TPA.Commit(); 1542 return TemplateTemplateArgument; 1543 } 1544 1545 // Revert this tentative parse to parse a non-type template argument. 1546 TPA.Revert(); 1547 } 1548 1549 // Parse a non-type template argument. 1550 SourceLocation Loc = Tok.getLocation(); 1551 ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast); 1552 if (ExprArg.isInvalid() || !ExprArg.get()) { 1553 return ParsedTemplateArgument(); 1554 } 1555 1556 return ParsedTemplateArgument(ParsedTemplateArgument::NonType, 1557 ExprArg.get(), Loc); 1558 } 1559 1560 /// ParseTemplateArgumentList - Parse a C++ template-argument-list 1561 /// (C++ [temp.names]). Returns true if there was an error. 1562 /// 1563 /// template-argument-list: [C++ 14.2] 1564 /// template-argument 1565 /// template-argument-list ',' template-argument 1566 bool 1567 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { 1568 1569 ColonProtectionRAIIObject ColonProtection(*this, false); 1570 1571 do { 1572 ParsedTemplateArgument Arg = ParseTemplateArgument(); 1573 SourceLocation EllipsisLoc; 1574 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 1575 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc); 1576 1577 if (Arg.isInvalid()) 1578 return true; 1579 1580 // Save this template argument. 1581 TemplateArgs.push_back(Arg); 1582 1583 // If the next token is a comma, consume it and keep reading 1584 // arguments. 1585 } while (TryConsumeToken(tok::comma)); 1586 1587 return false; 1588 } 1589 1590 /// Parse a C++ explicit template instantiation 1591 /// (C++ [temp.explicit]). 1592 /// 1593 /// explicit-instantiation: 1594 /// 'extern' [opt] 'template' declaration 1595 /// 1596 /// Note that the 'extern' is a GNU extension and C++11 feature. 1597 Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context, 1598 SourceLocation ExternLoc, 1599 SourceLocation TemplateLoc, 1600 SourceLocation &DeclEnd, 1601 ParsedAttributes &AccessAttrs, 1602 AccessSpecifier AS) { 1603 // This isn't really required here. 1604 ParsingDeclRAIIObject 1605 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); 1606 1607 return ParseSingleDeclarationAfterTemplate( 1608 Context, ParsedTemplateInfo(ExternLoc, TemplateLoc), 1609 ParsingTemplateParams, DeclEnd, AccessAttrs, AS); 1610 } 1611 1612 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const { 1613 if (TemplateParams) 1614 return getTemplateParamsRange(TemplateParams->data(), 1615 TemplateParams->size()); 1616 1617 SourceRange R(TemplateLoc); 1618 if (ExternLoc.isValid()) 1619 R.setBegin(ExternLoc); 1620 return R; 1621 } 1622 1623 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) { 1624 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT); 1625 } 1626 1627 /// Late parse a C++ function template in Microsoft mode. 1628 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) { 1629 if (!LPT.D) 1630 return; 1631 1632 // Destroy TemplateIdAnnotations when we're done, if possible. 1633 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this); 1634 1635 // Get the FunctionDecl. 1636 FunctionDecl *FunD = LPT.D->getAsFunction(); 1637 // Track template parameter depth. 1638 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 1639 1640 // To restore the context after late parsing. 1641 Sema::ContextRAII GlobalSavedContext( 1642 Actions, Actions.Context.getTranslationUnitDecl()); 1643 1644 MultiParseScope Scopes(*this); 1645 1646 // Get the list of DeclContexts to reenter. 1647 SmallVector<DeclContext*, 4> DeclContextsToReenter; 1648 for (DeclContext *DC = FunD; DC && !DC->isTranslationUnit(); 1649 DC = DC->getLexicalParent()) 1650 DeclContextsToReenter.push_back(DC); 1651 1652 // Reenter scopes from outermost to innermost. 1653 for (DeclContext *DC : reverse(DeclContextsToReenter)) { 1654 CurTemplateDepthTracker.addDepth( 1655 ReenterTemplateScopes(Scopes, cast<Decl>(DC))); 1656 Scopes.Enter(Scope::DeclScope); 1657 // We'll reenter the function context itself below. 1658 if (DC != FunD) 1659 Actions.PushDeclContext(Actions.getCurScope(), DC); 1660 } 1661 1662 assert(!LPT.Toks.empty() && "Empty body!"); 1663 1664 // Append the current token at the end of the new token stream so that it 1665 // doesn't get lost. 1666 LPT.Toks.push_back(Tok); 1667 PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true); 1668 1669 // Consume the previously pushed token. 1670 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1671 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) && 1672 "Inline method not starting with '{', ':' or 'try'"); 1673 1674 // Parse the method body. Function body parsing code is similar enough 1675 // to be re-used for method bodies as well. 1676 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope | 1677 Scope::CompoundStmtScope); 1678 1679 // Recreate the containing function DeclContext. 1680 Sema::ContextRAII FunctionSavedContext(Actions, FunD->getLexicalParent()); 1681 1682 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD); 1683 1684 if (Tok.is(tok::kw_try)) { 1685 ParseFunctionTryBlock(LPT.D, FnScope); 1686 } else { 1687 if (Tok.is(tok::colon)) 1688 ParseConstructorInitializer(LPT.D); 1689 else 1690 Actions.ActOnDefaultCtorInitializers(LPT.D); 1691 1692 if (Tok.is(tok::l_brace)) { 1693 assert((!isa<FunctionTemplateDecl>(LPT.D) || 1694 cast<FunctionTemplateDecl>(LPT.D) 1695 ->getTemplateParameters() 1696 ->getDepth() == TemplateParameterDepth - 1) && 1697 "TemplateParameterDepth should be greater than the depth of " 1698 "current template being instantiated!"); 1699 ParseFunctionStatementBody(LPT.D, FnScope); 1700 Actions.UnmarkAsLateParsedTemplate(FunD); 1701 } else 1702 Actions.ActOnFinishFunctionBody(LPT.D, nullptr); 1703 } 1704 } 1705 1706 /// Lex a delayed template function for late parsing. 1707 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) { 1708 tok::TokenKind kind = Tok.getKind(); 1709 if (!ConsumeAndStoreFunctionPrologue(Toks)) { 1710 // Consume everything up to (and including) the matching right brace. 1711 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 1712 } 1713 1714 // If we're in a function-try-block, we need to store all the catch blocks. 1715 if (kind == tok::kw_try) { 1716 while (Tok.is(tok::kw_catch)) { 1717 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); 1718 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 1719 } 1720 } 1721 } 1722 1723 /// We've parsed something that could plausibly be intended to be a template 1724 /// name (\p LHS) followed by a '<' token, and the following code can't possibly 1725 /// be an expression. Determine if this is likely to be a template-id and if so, 1726 /// diagnose it. 1727 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) { 1728 TentativeParsingAction TPA(*this); 1729 // FIXME: We could look at the token sequence in a lot more detail here. 1730 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater, 1731 StopAtSemi | StopBeforeMatch)) { 1732 TPA.Commit(); 1733 1734 SourceLocation Greater; 1735 ParseGreaterThanInTemplateList(Less, Greater, true, false); 1736 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS, 1737 Less, Greater); 1738 return true; 1739 } 1740 1741 // There's no matching '>' token, this probably isn't supposed to be 1742 // interpreted as a template-id. Parse it as an (ill-formed) comparison. 1743 TPA.Revert(); 1744 return false; 1745 } 1746 1747 void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) { 1748 assert(Tok.is(tok::less) && "not at a potential angle bracket"); 1749 1750 bool DependentTemplateName = false; 1751 if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName, 1752 DependentTemplateName)) 1753 return; 1754 1755 // OK, this might be a name that the user intended to be parsed as a 1756 // template-name, followed by a '<' token. Check for some easy cases. 1757 1758 // If we have potential_template<>, then it's supposed to be a template-name. 1759 if (NextToken().is(tok::greater) || 1760 (getLangOpts().CPlusPlus11 && 1761 NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) { 1762 SourceLocation Less = ConsumeToken(); 1763 SourceLocation Greater; 1764 ParseGreaterThanInTemplateList(Less, Greater, true, false); 1765 Actions.diagnoseExprIntendedAsTemplateName( 1766 getCurScope(), PotentialTemplateName, Less, Greater); 1767 // FIXME: Perform error recovery. 1768 PotentialTemplateName = ExprError(); 1769 return; 1770 } 1771 1772 // If we have 'potential_template<type-id', assume it's supposed to be a 1773 // template-name if there's a matching '>' later on. 1774 { 1775 // FIXME: Avoid the tentative parse when NextToken() can't begin a type. 1776 TentativeParsingAction TPA(*this); 1777 SourceLocation Less = ConsumeToken(); 1778 if (isTypeIdUnambiguously() && 1779 diagnoseUnknownTemplateId(PotentialTemplateName, Less)) { 1780 TPA.Commit(); 1781 // FIXME: Perform error recovery. 1782 PotentialTemplateName = ExprError(); 1783 return; 1784 } 1785 TPA.Revert(); 1786 } 1787 1788 // Otherwise, remember that we saw this in case we see a potentially-matching 1789 // '>' token later on. 1790 AngleBracketTracker::Priority Priority = 1791 (DependentTemplateName ? AngleBracketTracker::DependentName 1792 : AngleBracketTracker::PotentialTypo) | 1793 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess 1794 : AngleBracketTracker::NoSpaceBeforeLess); 1795 AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(), 1796 Priority); 1797 } 1798 1799 bool Parser::checkPotentialAngleBracketDelimiter( 1800 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) { 1801 // If a comma in an expression context is followed by a type that can be a 1802 // template argument and cannot be an expression, then this is ill-formed, 1803 // but might be intended to be part of a template-id. 1804 if (OpToken.is(tok::comma) && isTypeIdUnambiguously() && 1805 diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) { 1806 AngleBrackets.clear(*this); 1807 return true; 1808 } 1809 1810 // If a context that looks like a template-id is followed by '()', then 1811 // this is ill-formed, but might be intended to be a template-id 1812 // followed by '()'. 1813 if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) && 1814 NextToken().is(tok::r_paren)) { 1815 Actions.diagnoseExprIntendedAsTemplateName( 1816 getCurScope(), LAngle.TemplateName, LAngle.LessLoc, 1817 OpToken.getLocation()); 1818 AngleBrackets.clear(*this); 1819 return true; 1820 } 1821 1822 // After a '>' (etc), we're no longer potentially in a construct that's 1823 // intended to be treated as a template-id. 1824 if (OpToken.is(tok::greater) || 1825 (getLangOpts().CPlusPlus11 && 1826 OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater))) 1827 AngleBrackets.clear(*this); 1828 return false; 1829 } 1830