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