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