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