Faisal Vali | 65efd10 | 2013-06-08 19:39:00 +0000 | [diff] [blame] | 1 | //===--- ParseTemplate.cpp - Template Parsing -----------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements parsing of C++ templates. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "clang/Parse/Parser.h" |
| 15 | #include "RAIIObjectsForParser.h" |
| 16 | #include "clang/AST/ASTConsumer.h" |
| 17 | #include "clang/AST/DeclTemplate.h" |
| 18 | #include "clang/Parse/ParseDiagnostic.h" |
| 19 | #include "clang/Sema/DeclSpec.h" |
| 20 | #include "clang/Sema/ParsedTemplate.h" |
| 21 | #include "clang/Sema/Scope.h" |
| 22 | using namespace clang; |
| 23 | |
| 24 | /// \brief Parse a template declaration, explicit instantiation, or |
| 25 | /// explicit specialization. |
| 26 | Decl * |
| 27 | Parser::ParseDeclarationStartingWithTemplate(unsigned Context, |
| 28 | SourceLocation &DeclEnd, |
| 29 | AccessSpecifier AS, |
| 30 | AttributeList *AccessAttrs) { |
| 31 | ObjCDeclContextSwitch ObjCDC(*this); |
| 32 | |
| 33 | if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) { |
| 34 | return ParseExplicitInstantiation(Context, |
| 35 | SourceLocation(), ConsumeToken(), |
| 36 | DeclEnd, AS); |
| 37 | } |
| 38 | return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS, |
| 39 | AccessAttrs); |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | /// \brief Parse a template declaration or an explicit specialization. |
| 45 | /// |
| 46 | /// Template declarations include one or more template parameter lists |
| 47 | /// and either the function or class template declaration. Explicit |
| 48 | /// specializations contain one or more 'template < >' prefixes |
| 49 | /// followed by a (possibly templated) declaration. Since the |
| 50 | /// syntactic form of both features is nearly identical, we parse all |
| 51 | /// of the template headers together and let semantic analysis sort |
| 52 | /// the declarations from the explicit specializations. |
| 53 | /// |
| 54 | /// template-declaration: [C++ temp] |
| 55 | /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration |
| 56 | /// |
| 57 | /// explicit-specialization: [ C++ temp.expl.spec] |
| 58 | /// 'template' '<' '>' declaration |
| 59 | Decl * |
| 60 | Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context, |
| 61 | SourceLocation &DeclEnd, |
| 62 | AccessSpecifier AS, |
| 63 | AttributeList *AccessAttrs) { |
| 64 | assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) && |
| 65 | "Token does not start a template declaration."); |
| 66 | |
| 67 | // Enter template-parameter scope. |
| 68 | ParseScope TemplateParmScope(this, Scope::TemplateParamScope); |
| 69 | |
| 70 | // Tell the action that names should be checked in the context of |
| 71 | // the declaration to come. |
| 72 | ParsingDeclRAIIObject |
| 73 | ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); |
| 74 | |
| 75 | // Parse multiple levels of template headers within this template |
| 76 | // parameter scope, e.g., |
| 77 | // |
| 78 | // template<typename T> |
| 79 | // template<typename U> |
| 80 | // class A<T>::B { ... }; |
| 81 | // |
| 82 | // We parse multiple levels non-recursively so that we can build a |
| 83 | // single data structure containing all of the template parameter |
| 84 | // lists to easily differentiate between the case above and: |
| 85 | // |
| 86 | // template<typename T> |
| 87 | // class A { |
| 88 | // template<typename U> class B; |
| 89 | // }; |
| 90 | // |
| 91 | // In the first case, the action for declaring A<T>::B receives |
| 92 | // both template parameter lists. In the second case, the action for |
| 93 | // defining A<T>::B receives just the inner template parameter list |
| 94 | // (and retrieves the outer template parameter list from its |
| 95 | // context). |
| 96 | bool isSpecialization = true; |
| 97 | bool LastParamListWasEmpty = false; |
| 98 | TemplateParameterLists ParamLists; |
| 99 | TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); |
| 100 | |
| 101 | do { |
| 102 | // Consume the 'export', if any. |
| 103 | SourceLocation ExportLoc; |
| 104 | if (Tok.is(tok::kw_export)) { |
| 105 | ExportLoc = ConsumeToken(); |
| 106 | } |
| 107 | |
| 108 | // Consume the 'template', which should be here. |
| 109 | SourceLocation TemplateLoc; |
| 110 | if (Tok.is(tok::kw_template)) { |
| 111 | TemplateLoc = ConsumeToken(); |
| 112 | } else { |
| 113 | Diag(Tok.getLocation(), diag::err_expected_template); |
| 114 | return 0; |
| 115 | } |
| 116 | |
| 117 | // Parse the '<' template-parameter-list '>' |
| 118 | SourceLocation LAngleLoc, RAngleLoc; |
| 119 | SmallVector<Decl*, 4> TemplateParams; |
| 120 | if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(), |
| 121 | TemplateParams, LAngleLoc, RAngleLoc)) { |
| 122 | // Skip until the semi-colon or a }. |
| 123 | SkipUntil(tok::r_brace, true, true); |
| 124 | if (Tok.is(tok::semi)) |
| 125 | ConsumeToken(); |
| 126 | return 0; |
| 127 | } |
| 128 | |
| 129 | ParamLists.push_back( |
| 130 | Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(), |
| 131 | ExportLoc, |
| 132 | TemplateLoc, LAngleLoc, |
| 133 | TemplateParams.data(), |
| 134 | TemplateParams.size(), RAngleLoc)); |
| 135 | |
| 136 | if (!TemplateParams.empty()) { |
| 137 | isSpecialization = false; |
| 138 | ++CurTemplateDepthTracker; |
| 139 | } else { |
| 140 | LastParamListWasEmpty = true; |
| 141 | } |
| 142 | } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template)); |
| 143 | |
| 144 | // Parse the actual template declaration. |
| 145 | return ParseSingleDeclarationAfterTemplate(Context, |
| 146 | ParsedTemplateInfo(&ParamLists, |
| 147 | isSpecialization, |
| 148 | LastParamListWasEmpty), |
| 149 | ParsingTemplateParams, |
| 150 | DeclEnd, AS, AccessAttrs); |
| 151 | } |
| 152 | |
| 153 | /// \brief Parse a single declaration that declares a template, |
| 154 | /// template specialization, or explicit instantiation of a template. |
| 155 | /// |
| 156 | /// \param DeclEnd will receive the source location of the last token |
| 157 | /// within this declaration. |
| 158 | /// |
| 159 | /// \param AS the access specifier associated with this |
| 160 | /// declaration. Will be AS_none for namespace-scope declarations. |
| 161 | /// |
| 162 | /// \returns the new declaration. |
| 163 | Decl * |
| 164 | Parser::ParseSingleDeclarationAfterTemplate( |
| 165 | unsigned Context, |
| 166 | const ParsedTemplateInfo &TemplateInfo, |
| 167 | ParsingDeclRAIIObject &DiagsFromTParams, |
| 168 | SourceLocation &DeclEnd, |
| 169 | AccessSpecifier AS, |
| 170 | AttributeList *AccessAttrs) { |
| 171 | assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && |
| 172 | "Template information required"); |
| 173 | |
| 174 | if (Context == Declarator::MemberContext) { |
| 175 | // We are parsing a member template. |
| 176 | ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo, |
| 177 | &DiagsFromTParams); |
| 178 | return 0; |
| 179 | } |
| 180 | |
| 181 | ParsedAttributesWithRange prefixAttrs(AttrFactory); |
| 182 | MaybeParseCXX11Attributes(prefixAttrs); |
| 183 | |
| 184 | if (Tok.is(tok::kw_using)) |
| 185 | return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd, |
| 186 | prefixAttrs); |
| 187 | |
| 188 | // Parse the declaration specifiers, stealing any diagnostics from |
| 189 | // the template parameters. |
| 190 | ParsingDeclSpec DS(*this, &DiagsFromTParams); |
| 191 | |
| 192 | ParseDeclarationSpecifiers(DS, TemplateInfo, AS, |
| 193 | getDeclSpecContextFromDeclaratorContext(Context)); |
| 194 | |
| 195 | if (Tok.is(tok::semi)) { |
| 196 | ProhibitAttributes(prefixAttrs); |
| 197 | DeclEnd = ConsumeToken(); |
| 198 | Decl *Decl = Actions.ParsedFreeStandingDeclSpec( |
| 199 | getCurScope(), AS, DS, |
| 200 | TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams |
| 201 | : MultiTemplateParamsArg(), |
| 202 | TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation); |
| 203 | DS.complete(Decl); |
| 204 | return Decl; |
| 205 | } |
| 206 | |
| 207 | // Move the attributes from the prefix into the DS. |
| 208 | if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) |
| 209 | ProhibitAttributes(prefixAttrs); |
| 210 | else |
| 211 | DS.takeAttributesFrom(prefixAttrs); |
| 212 | |
| 213 | // Parse the declarator. |
| 214 | ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context); |
| 215 | ParseDeclarator(DeclaratorInfo); |
| 216 | // Error parsing the declarator? |
| 217 | if (!DeclaratorInfo.hasName()) { |
| 218 | // If so, skip until the semi-colon or a }. |
| 219 | SkipUntil(tok::r_brace, true, true); |
| 220 | if (Tok.is(tok::semi)) |
| 221 | ConsumeToken(); |
| 222 | return 0; |
| 223 | } |
| 224 | |
| 225 | LateParsedAttrList LateParsedAttrs(true); |
| 226 | if (DeclaratorInfo.isFunctionDeclarator()) |
| 227 | MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); |
| 228 | |
| 229 | if (DeclaratorInfo.isFunctionDeclarator() && |
| 230 | isStartOfFunctionDefinition(DeclaratorInfo)) { |
| 231 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { |
| 232 | // Recover by ignoring the 'typedef'. This was probably supposed to be |
| 233 | // the 'typename' keyword, which we should have already suggested adding |
| 234 | // if it's appropriate. |
| 235 | Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef) |
| 236 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); |
| 237 | DS.ClearStorageClassSpecs(); |
| 238 | } |
Larisse Voufo | 7c64ef0 | 2013-06-21 00:08:46 +0000 | [diff] [blame^] | 239 | |
| 240 | if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { |
| 241 | if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) { |
| 242 | // If the declarator-id is not a template-id, issue a diagnostic and |
| 243 | // recover by ignoring the 'template' keyword. |
| 244 | Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0; |
| 245 | } else { |
| 246 | SourceLocation LAngleLoc |
| 247 | = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); |
| 248 | Diag(DeclaratorInfo.getIdentifierLoc(), |
| 249 | diag::err_explicit_instantiation_with_definition) |
| 250 | << SourceRange(TemplateInfo.TemplateLoc) |
| 251 | << FixItHint::CreateInsertion(LAngleLoc, "<>"); |
| 252 | |
| 253 | // Recover as if it were an explicit specialization. |
| 254 | TemplateParameterLists ParamLists; |
| 255 | SmallVector<Decl*, 4> TemplateParams; |
| 256 | ParamLists.push_back( |
| 257 | TemplateParameterList::Create(Actions.getASTContext(), |
| 258 | TemplateInfo.TemplateLoc, |
| 259 | LAngleLoc, |
| 260 | (NamedDecl**)TemplateParams.data(), |
| 261 | TemplateParams.size(), LAngleLoc)); |
| 262 | |
| 263 | return ParseFunctionDefinition(DeclaratorInfo, |
| 264 | ParsedTemplateInfo(&ParamLists, |
| 265 | /*isSpecialization=*/true, |
| 266 | /*LastParamListWasEmpty=*/true), |
| 267 | &LateParsedAttrs); |
| 268 | } |
| 269 | } |
Faisal Vali | 65efd10 | 2013-06-08 19:39:00 +0000 | [diff] [blame] | 270 | return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo, |
Larisse Voufo | 7c64ef0 | 2013-06-21 00:08:46 +0000 | [diff] [blame^] | 271 | &LateParsedAttrs); |
Faisal Vali | 65efd10 | 2013-06-08 19:39:00 +0000 | [diff] [blame] | 272 | } |
| 273 | |
| 274 | // Parse this declaration. |
| 275 | Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo, |
| 276 | TemplateInfo); |
| 277 | |
| 278 | if (Tok.is(tok::comma)) { |
| 279 | Diag(Tok, diag::err_multiple_template_declarators) |
| 280 | << (int)TemplateInfo.Kind; |
| 281 | SkipUntil(tok::semi, true, false); |
| 282 | return ThisDecl; |
| 283 | } |
| 284 | |
| 285 | // Eat the semi colon after the declaration. |
| 286 | ExpectAndConsumeSemi(diag::err_expected_semi_declaration); |
| 287 | if (LateParsedAttrs.size() > 0) |
| 288 | ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false); |
| 289 | DeclaratorInfo.complete(ThisDecl); |
| 290 | return ThisDecl; |
| 291 | } |
| 292 | |
| 293 | /// ParseTemplateParameters - Parses a template-parameter-list enclosed in |
| 294 | /// angle brackets. Depth is the depth of this template-parameter-list, which |
| 295 | /// is the number of template headers directly enclosing this template header. |
| 296 | /// TemplateParams is the current list of template parameters we're building. |
| 297 | /// The template parameter we parse will be added to this list. LAngleLoc and |
| 298 | /// RAngleLoc will receive the positions of the '<' and '>', respectively, |
| 299 | /// that enclose this template parameter list. |
| 300 | /// |
| 301 | /// \returns true if an error occurred, false otherwise. |
| 302 | bool Parser::ParseTemplateParameters(unsigned Depth, |
| 303 | SmallVectorImpl<Decl*> &TemplateParams, |
| 304 | SourceLocation &LAngleLoc, |
| 305 | SourceLocation &RAngleLoc) { |
| 306 | // Get the template parameter list. |
| 307 | if (!Tok.is(tok::less)) { |
| 308 | Diag(Tok.getLocation(), diag::err_expected_less_after) << "template"; |
| 309 | return true; |
| 310 | } |
| 311 | LAngleLoc = ConsumeToken(); |
| 312 | |
| 313 | // Try to parse the template parameter list. |
| 314 | bool Failed = false; |
| 315 | if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater)) |
| 316 | Failed = ParseTemplateParameterList(Depth, TemplateParams); |
| 317 | |
| 318 | if (Tok.is(tok::greatergreater)) { |
| 319 | // No diagnostic required here: a template-parameter-list can only be |
| 320 | // followed by a declaration or, for a template template parameter, the |
| 321 | // 'class' keyword. Therefore, the second '>' will be diagnosed later. |
| 322 | // This matters for elegant diagnosis of: |
| 323 | // template<template<typename>> struct S; |
| 324 | Tok.setKind(tok::greater); |
| 325 | RAngleLoc = Tok.getLocation(); |
| 326 | Tok.setLocation(Tok.getLocation().getLocWithOffset(1)); |
| 327 | } else if (Tok.is(tok::greater)) |
| 328 | RAngleLoc = ConsumeToken(); |
| 329 | else if (Failed) { |
| 330 | Diag(Tok.getLocation(), diag::err_expected_greater); |
| 331 | return true; |
| 332 | } |
| 333 | return false; |
| 334 | } |
| 335 | |
| 336 | /// ParseTemplateParameterList - Parse a template parameter list. If |
| 337 | /// the parsing fails badly (i.e., closing bracket was left out), this |
| 338 | /// will try to put the token stream in a reasonable position (closing |
| 339 | /// a statement, etc.) and return false. |
| 340 | /// |
| 341 | /// template-parameter-list: [C++ temp] |
| 342 | /// template-parameter |
| 343 | /// template-parameter-list ',' template-parameter |
| 344 | bool |
| 345 | Parser::ParseTemplateParameterList(unsigned Depth, |
| 346 | SmallVectorImpl<Decl*> &TemplateParams) { |
| 347 | while (1) { |
| 348 | if (Decl *TmpParam |
| 349 | = ParseTemplateParameter(Depth, TemplateParams.size())) { |
| 350 | TemplateParams.push_back(TmpParam); |
| 351 | } else { |
| 352 | // If we failed to parse a template parameter, skip until we find |
| 353 | // a comma or closing brace. |
| 354 | SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true); |
| 355 | } |
| 356 | |
| 357 | // Did we find a comma or the end of the template parameter list? |
| 358 | if (Tok.is(tok::comma)) { |
| 359 | ConsumeToken(); |
| 360 | } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) { |
| 361 | // Don't consume this... that's done by template parser. |
| 362 | break; |
| 363 | } else { |
| 364 | // Somebody probably forgot to close the template. Skip ahead and |
| 365 | // try to get out of the expression. This error is currently |
| 366 | // subsumed by whatever goes on in ParseTemplateParameter. |
| 367 | Diag(Tok.getLocation(), diag::err_expected_comma_greater); |
| 368 | SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true); |
| 369 | return false; |
| 370 | } |
| 371 | } |
| 372 | return true; |
| 373 | } |
| 374 | |
| 375 | /// \brief Determine whether the parser is at the start of a template |
| 376 | /// type parameter. |
| 377 | bool Parser::isStartOfTemplateTypeParameter() { |
| 378 | if (Tok.is(tok::kw_class)) { |
| 379 | // "class" may be the start of an elaborated-type-specifier or a |
| 380 | // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter. |
| 381 | switch (NextToken().getKind()) { |
| 382 | case tok::equal: |
| 383 | case tok::comma: |
| 384 | case tok::greater: |
| 385 | case tok::greatergreater: |
| 386 | case tok::ellipsis: |
| 387 | return true; |
| 388 | |
| 389 | case tok::identifier: |
| 390 | // This may be either a type-parameter or an elaborated-type-specifier. |
| 391 | // We have to look further. |
| 392 | break; |
| 393 | |
| 394 | default: |
| 395 | return false; |
| 396 | } |
| 397 | |
| 398 | switch (GetLookAheadToken(2).getKind()) { |
| 399 | case tok::equal: |
| 400 | case tok::comma: |
| 401 | case tok::greater: |
| 402 | case tok::greatergreater: |
| 403 | return true; |
| 404 | |
| 405 | default: |
| 406 | return false; |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | if (Tok.isNot(tok::kw_typename)) |
| 411 | return false; |
| 412 | |
| 413 | // C++ [temp.param]p2: |
| 414 | // There is no semantic difference between class and typename in a |
| 415 | // template-parameter. typename followed by an unqualified-id |
| 416 | // names a template type parameter. typename followed by a |
| 417 | // qualified-id denotes the type in a non-type |
| 418 | // parameter-declaration. |
| 419 | Token Next = NextToken(); |
| 420 | |
| 421 | // If we have an identifier, skip over it. |
| 422 | if (Next.getKind() == tok::identifier) |
| 423 | Next = GetLookAheadToken(2); |
| 424 | |
| 425 | switch (Next.getKind()) { |
| 426 | case tok::equal: |
| 427 | case tok::comma: |
| 428 | case tok::greater: |
| 429 | case tok::greatergreater: |
| 430 | case tok::ellipsis: |
| 431 | return true; |
| 432 | |
| 433 | default: |
| 434 | return false; |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]). |
| 439 | /// |
| 440 | /// template-parameter: [C++ temp.param] |
| 441 | /// type-parameter |
| 442 | /// parameter-declaration |
| 443 | /// |
| 444 | /// type-parameter: (see below) |
| 445 | /// 'class' ...[opt] identifier[opt] |
| 446 | /// 'class' identifier[opt] '=' type-id |
| 447 | /// 'typename' ...[opt] identifier[opt] |
| 448 | /// 'typename' identifier[opt] '=' type-id |
| 449 | /// 'template' '<' template-parameter-list '>' |
| 450 | /// 'class' ...[opt] identifier[opt] |
| 451 | /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] |
| 452 | /// = id-expression |
| 453 | Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) { |
| 454 | if (isStartOfTemplateTypeParameter()) |
| 455 | return ParseTypeParameter(Depth, Position); |
| 456 | |
| 457 | if (Tok.is(tok::kw_template)) |
| 458 | return ParseTemplateTemplateParameter(Depth, Position); |
| 459 | |
| 460 | // If it's none of the above, then it must be a parameter declaration. |
| 461 | // NOTE: This will pick up errors in the closure of the template parameter |
| 462 | // list (e.g., template < ; Check here to implement >> style closures. |
| 463 | return ParseNonTypeTemplateParameter(Depth, Position); |
| 464 | } |
| 465 | |
| 466 | /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]). |
| 467 | /// Other kinds of template parameters are parsed in |
| 468 | /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter. |
| 469 | /// |
| 470 | /// type-parameter: [C++ temp.param] |
| 471 | /// 'class' ...[opt][C++0x] identifier[opt] |
| 472 | /// 'class' identifier[opt] '=' type-id |
| 473 | /// 'typename' ...[opt][C++0x] identifier[opt] |
| 474 | /// 'typename' identifier[opt] '=' type-id |
| 475 | Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) { |
| 476 | assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) && |
| 477 | "A type-parameter starts with 'class' or 'typename'"); |
| 478 | |
| 479 | // Consume the 'class' or 'typename' keyword. |
| 480 | bool TypenameKeyword = Tok.is(tok::kw_typename); |
| 481 | SourceLocation KeyLoc = ConsumeToken(); |
| 482 | |
| 483 | // Grab the ellipsis (if given). |
| 484 | bool Ellipsis = false; |
| 485 | SourceLocation EllipsisLoc; |
| 486 | if (Tok.is(tok::ellipsis)) { |
| 487 | Ellipsis = true; |
| 488 | EllipsisLoc = ConsumeToken(); |
| 489 | |
| 490 | Diag(EllipsisLoc, |
| 491 | getLangOpts().CPlusPlus11 |
| 492 | ? diag::warn_cxx98_compat_variadic_templates |
| 493 | : diag::ext_variadic_templates); |
| 494 | } |
| 495 | |
| 496 | // Grab the template parameter name (if given) |
| 497 | SourceLocation NameLoc; |
| 498 | IdentifierInfo* ParamName = 0; |
| 499 | if (Tok.is(tok::identifier)) { |
| 500 | ParamName = Tok.getIdentifierInfo(); |
| 501 | NameLoc = ConsumeToken(); |
| 502 | } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || |
| 503 | Tok.is(tok::greater) || Tok.is(tok::greatergreater)) { |
| 504 | // Unnamed template parameter. Don't have to do anything here, just |
| 505 | // don't consume this token. |
| 506 | } else { |
| 507 | Diag(Tok.getLocation(), diag::err_expected_ident); |
| 508 | return 0; |
| 509 | } |
| 510 | |
| 511 | // Grab a default argument (if available). |
| 512 | // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before |
| 513 | // we introduce the type parameter into the local scope. |
| 514 | SourceLocation EqualLoc; |
| 515 | ParsedType DefaultArg; |
| 516 | if (Tok.is(tok::equal)) { |
| 517 | EqualLoc = ConsumeToken(); |
| 518 | DefaultArg = ParseTypeName(/*Range=*/0, |
| 519 | Declarator::TemplateTypeArgContext).get(); |
| 520 | } |
| 521 | |
| 522 | return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis, |
| 523 | EllipsisLoc, KeyLoc, ParamName, NameLoc, |
| 524 | Depth, Position, EqualLoc, DefaultArg); |
| 525 | } |
| 526 | |
| 527 | /// ParseTemplateTemplateParameter - Handle the parsing of template |
| 528 | /// template parameters. |
| 529 | /// |
| 530 | /// type-parameter: [C++ temp.param] |
| 531 | /// 'template' '<' template-parameter-list '>' 'class' |
| 532 | /// ...[opt] identifier[opt] |
| 533 | /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] |
| 534 | /// = id-expression |
| 535 | Decl * |
| 536 | Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { |
| 537 | assert(Tok.is(tok::kw_template) && "Expected 'template' keyword"); |
| 538 | |
| 539 | // Handle the template <...> part. |
| 540 | SourceLocation TemplateLoc = ConsumeToken(); |
| 541 | SmallVector<Decl*,8> TemplateParams; |
| 542 | SourceLocation LAngleLoc, RAngleLoc; |
| 543 | { |
| 544 | ParseScope TemplateParmScope(this, Scope::TemplateParamScope); |
| 545 | if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc, |
| 546 | RAngleLoc)) { |
| 547 | return 0; |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | // Generate a meaningful error if the user forgot to put class before the |
| 552 | // identifier, comma, or greater. Provide a fixit if the identifier, comma, |
| 553 | // or greater appear immediately or after 'typename' or 'struct'. In the |
| 554 | // latter case, replace the keyword with 'class'. |
| 555 | if (!Tok.is(tok::kw_class)) { |
| 556 | bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct); |
| 557 | const Token& Next = Replace ? NextToken() : Tok; |
| 558 | if (Next.is(tok::identifier) || Next.is(tok::comma) || |
| 559 | Next.is(tok::greater) || Next.is(tok::greatergreater) || |
| 560 | Next.is(tok::ellipsis)) |
| 561 | Diag(Tok.getLocation(), diag::err_class_on_template_template_param) |
| 562 | << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class") |
| 563 | : FixItHint::CreateInsertion(Tok.getLocation(), "class ")); |
| 564 | else |
| 565 | Diag(Tok.getLocation(), diag::err_class_on_template_template_param); |
| 566 | |
| 567 | if (Replace) |
| 568 | ConsumeToken(); |
| 569 | } else |
| 570 | ConsumeToken(); |
| 571 | |
| 572 | // Parse the ellipsis, if given. |
| 573 | SourceLocation EllipsisLoc; |
| 574 | if (Tok.is(tok::ellipsis)) { |
| 575 | EllipsisLoc = ConsumeToken(); |
| 576 | |
| 577 | Diag(EllipsisLoc, |
| 578 | getLangOpts().CPlusPlus11 |
| 579 | ? diag::warn_cxx98_compat_variadic_templates |
| 580 | : diag::ext_variadic_templates); |
| 581 | } |
| 582 | |
| 583 | // Get the identifier, if given. |
| 584 | SourceLocation NameLoc; |
| 585 | IdentifierInfo* ParamName = 0; |
| 586 | if (Tok.is(tok::identifier)) { |
| 587 | ParamName = Tok.getIdentifierInfo(); |
| 588 | NameLoc = ConsumeToken(); |
| 589 | } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || |
| 590 | Tok.is(tok::greater) || Tok.is(tok::greatergreater)) { |
| 591 | // Unnamed template parameter. Don't have to do anything here, just |
| 592 | // don't consume this token. |
| 593 | } else { |
| 594 | Diag(Tok.getLocation(), diag::err_expected_ident); |
| 595 | return 0; |
| 596 | } |
| 597 | |
| 598 | TemplateParameterList *ParamList = |
| 599 | Actions.ActOnTemplateParameterList(Depth, SourceLocation(), |
| 600 | TemplateLoc, LAngleLoc, |
| 601 | TemplateParams.data(), |
| 602 | TemplateParams.size(), |
| 603 | RAngleLoc); |
| 604 | |
| 605 | // Grab a default argument (if available). |
| 606 | // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before |
| 607 | // we introduce the template parameter into the local scope. |
| 608 | SourceLocation EqualLoc; |
| 609 | ParsedTemplateArgument DefaultArg; |
| 610 | if (Tok.is(tok::equal)) { |
| 611 | EqualLoc = ConsumeToken(); |
| 612 | DefaultArg = ParseTemplateTemplateArgument(); |
| 613 | if (DefaultArg.isInvalid()) { |
| 614 | Diag(Tok.getLocation(), |
| 615 | diag::err_default_template_template_parameter_not_template); |
| 616 | SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true); |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc, |
| 621 | ParamList, EllipsisLoc, |
| 622 | ParamName, NameLoc, Depth, |
| 623 | Position, EqualLoc, DefaultArg); |
| 624 | } |
| 625 | |
| 626 | /// ParseNonTypeTemplateParameter - Handle the parsing of non-type |
| 627 | /// template parameters (e.g., in "template<int Size> class array;"). |
| 628 | /// |
| 629 | /// template-parameter: |
| 630 | /// ... |
| 631 | /// parameter-declaration |
| 632 | Decl * |
| 633 | Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { |
| 634 | // Parse the declaration-specifiers (i.e., the type). |
| 635 | // FIXME: The type should probably be restricted in some way... Not all |
| 636 | // declarators (parts of declarators?) are accepted for parameters. |
| 637 | DeclSpec DS(AttrFactory); |
| 638 | ParseDeclarationSpecifiers(DS); |
| 639 | |
| 640 | // Parse this as a typename. |
| 641 | Declarator ParamDecl(DS, Declarator::TemplateParamContext); |
| 642 | ParseDeclarator(ParamDecl); |
| 643 | if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { |
| 644 | Diag(Tok.getLocation(), diag::err_expected_template_parameter); |
| 645 | return 0; |
| 646 | } |
| 647 | |
| 648 | // If there is a default value, parse it. |
| 649 | // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before |
| 650 | // we introduce the template parameter into the local scope. |
| 651 | SourceLocation EqualLoc; |
| 652 | ExprResult DefaultArg; |
| 653 | if (Tok.is(tok::equal)) { |
| 654 | EqualLoc = ConsumeToken(); |
| 655 | |
| 656 | // C++ [temp.param]p15: |
| 657 | // When parsing a default template-argument for a non-type |
| 658 | // template-parameter, the first non-nested > is taken as the |
| 659 | // end of the template-parameter-list rather than a greater-than |
| 660 | // operator. |
| 661 | GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); |
| 662 | EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); |
| 663 | |
| 664 | DefaultArg = ParseAssignmentExpression(); |
| 665 | if (DefaultArg.isInvalid()) |
| 666 | SkipUntil(tok::comma, tok::greater, true, true); |
| 667 | } |
| 668 | |
| 669 | // Create the parameter. |
| 670 | return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, |
| 671 | Depth, Position, EqualLoc, |
| 672 | DefaultArg.take()); |
| 673 | } |
| 674 | |
| 675 | /// \brief Parses a '>' at the end of a template list. |
| 676 | /// |
| 677 | /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries |
| 678 | /// to determine if these tokens were supposed to be a '>' followed by |
| 679 | /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary. |
| 680 | /// |
| 681 | /// \param RAngleLoc the location of the consumed '>'. |
| 682 | /// |
| 683 | /// \param ConsumeLastToken if true, the '>' is not consumed. |
| 684 | bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, |
| 685 | bool ConsumeLastToken) { |
| 686 | // What will be left once we've consumed the '>'. |
| 687 | tok::TokenKind RemainingToken; |
| 688 | const char *ReplacementStr = "> >"; |
| 689 | |
| 690 | switch (Tok.getKind()) { |
| 691 | default: |
| 692 | Diag(Tok.getLocation(), diag::err_expected_greater); |
| 693 | return true; |
| 694 | |
| 695 | case tok::greater: |
| 696 | // Determine the location of the '>' token. Only consume this token |
| 697 | // if the caller asked us to. |
| 698 | RAngleLoc = Tok.getLocation(); |
| 699 | if (ConsumeLastToken) |
| 700 | ConsumeToken(); |
| 701 | return false; |
| 702 | |
| 703 | case tok::greatergreater: |
| 704 | RemainingToken = tok::greater; |
| 705 | break; |
| 706 | |
| 707 | case tok::greatergreatergreater: |
| 708 | RemainingToken = tok::greatergreater; |
| 709 | break; |
| 710 | |
| 711 | case tok::greaterequal: |
| 712 | RemainingToken = tok::equal; |
| 713 | ReplacementStr = "> ="; |
| 714 | break; |
| 715 | |
| 716 | case tok::greatergreaterequal: |
| 717 | RemainingToken = tok::greaterequal; |
| 718 | break; |
| 719 | } |
| 720 | |
| 721 | // This template-id is terminated by a token which starts with a '>'. Outside |
| 722 | // C++11, this is now error recovery, and in C++11, this is error recovery if |
| 723 | // the token isn't '>>'. |
| 724 | |
| 725 | RAngleLoc = Tok.getLocation(); |
| 726 | |
| 727 | // The source range of the '>>' or '>=' at the start of the token. |
| 728 | CharSourceRange ReplacementRange = |
| 729 | CharSourceRange::getCharRange(RAngleLoc, |
| 730 | Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(), |
| 731 | getLangOpts())); |
| 732 | |
| 733 | // A hint to put a space between the '>>'s. In order to make the hint as |
| 734 | // clear as possible, we include the characters either side of the space in |
| 735 | // the replacement, rather than just inserting a space at SecondCharLoc. |
| 736 | FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange, |
| 737 | ReplacementStr); |
| 738 | |
| 739 | // A hint to put another space after the token, if it would otherwise be |
| 740 | // lexed differently. |
| 741 | FixItHint Hint2; |
| 742 | Token Next = NextToken(); |
| 743 | if ((RemainingToken == tok::greater || |
| 744 | RemainingToken == tok::greatergreater) && |
| 745 | (Next.is(tok::greater) || Next.is(tok::greatergreater) || |
| 746 | Next.is(tok::greatergreatergreater) || Next.is(tok::equal) || |
| 747 | Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) || |
| 748 | Next.is(tok::equalequal)) && |
| 749 | areTokensAdjacent(Tok, Next)) |
| 750 | Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " "); |
| 751 | |
| 752 | unsigned DiagId = diag::err_two_right_angle_brackets_need_space; |
| 753 | if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)) |
| 754 | DiagId = diag::warn_cxx98_compat_two_right_angle_brackets; |
| 755 | else if (Tok.is(tok::greaterequal)) |
| 756 | DiagId = diag::err_right_angle_bracket_equal_needs_space; |
| 757 | Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2; |
| 758 | |
| 759 | // Strip the initial '>' from the token. |
| 760 | if (RemainingToken == tok::equal && Next.is(tok::equal) && |
| 761 | areTokensAdjacent(Tok, Next)) { |
| 762 | // Join two adjacent '=' tokens into one, for cases like: |
| 763 | // void (*p)() = f<int>; |
| 764 | // return f<int>==p; |
| 765 | ConsumeToken(); |
| 766 | Tok.setKind(tok::equalequal); |
| 767 | Tok.setLength(Tok.getLength() + 1); |
| 768 | } else { |
| 769 | Tok.setKind(RemainingToken); |
| 770 | Tok.setLength(Tok.getLength() - 1); |
| 771 | } |
| 772 | Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1, |
| 773 | PP.getSourceManager(), |
| 774 | getLangOpts())); |
| 775 | |
| 776 | if (!ConsumeLastToken) { |
| 777 | // Since we're not supposed to consume the '>' token, we need to push |
| 778 | // this token and revert the current token back to the '>'. |
| 779 | PP.EnterToken(Tok); |
| 780 | Tok.setKind(tok::greater); |
| 781 | Tok.setLength(1); |
| 782 | Tok.setLocation(RAngleLoc); |
| 783 | } |
| 784 | return false; |
| 785 | } |
| 786 | |
| 787 | |
| 788 | /// \brief Parses a template-id that after the template name has |
| 789 | /// already been parsed. |
| 790 | /// |
| 791 | /// This routine takes care of parsing the enclosed template argument |
| 792 | /// list ('<' template-parameter-list [opt] '>') and placing the |
| 793 | /// results into a form that can be transferred to semantic analysis. |
| 794 | /// |
| 795 | /// \param Template the template declaration produced by isTemplateName |
| 796 | /// |
| 797 | /// \param TemplateNameLoc the source location of the template name |
| 798 | /// |
| 799 | /// \param SS if non-NULL, the nested-name-specifier preceding the |
| 800 | /// template name. |
| 801 | /// |
| 802 | /// \param ConsumeLastToken if true, then we will consume the last |
| 803 | /// token that forms the template-id. Otherwise, we will leave the |
| 804 | /// last token in the stream (e.g., so that it can be replaced with an |
| 805 | /// annotation token). |
| 806 | bool |
| 807 | Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, |
| 808 | SourceLocation TemplateNameLoc, |
| 809 | const CXXScopeSpec &SS, |
| 810 | bool ConsumeLastToken, |
| 811 | SourceLocation &LAngleLoc, |
| 812 | TemplateArgList &TemplateArgs, |
| 813 | SourceLocation &RAngleLoc) { |
| 814 | assert(Tok.is(tok::less) && "Must have already parsed the template-name"); |
| 815 | |
| 816 | // Consume the '<'. |
| 817 | LAngleLoc = ConsumeToken(); |
| 818 | |
| 819 | // Parse the optional template-argument-list. |
| 820 | bool Invalid = false; |
| 821 | { |
| 822 | GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); |
| 823 | if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) |
| 824 | Invalid = ParseTemplateArgumentList(TemplateArgs); |
| 825 | |
| 826 | if (Invalid) { |
| 827 | // Try to find the closing '>'. |
| 828 | SkipUntil(tok::greater, true, !ConsumeLastToken); |
| 829 | |
| 830 | return true; |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken); |
| 835 | } |
| 836 | |
| 837 | /// \brief Replace the tokens that form a simple-template-id with an |
| 838 | /// annotation token containing the complete template-id. |
| 839 | /// |
| 840 | /// The first token in the stream must be the name of a template that |
| 841 | /// is followed by a '<'. This routine will parse the complete |
| 842 | /// simple-template-id and replace the tokens with a single annotation |
| 843 | /// token with one of two different kinds: if the template-id names a |
| 844 | /// type (and \p AllowTypeAnnotation is true), the annotation token is |
| 845 | /// a type annotation that includes the optional nested-name-specifier |
| 846 | /// (\p SS). Otherwise, the annotation token is a template-id |
| 847 | /// annotation that does not include the optional |
| 848 | /// nested-name-specifier. |
| 849 | /// |
| 850 | /// \param Template the declaration of the template named by the first |
| 851 | /// token (an identifier), as returned from \c Action::isTemplateName(). |
| 852 | /// |
| 853 | /// \param TNK the kind of template that \p Template |
| 854 | /// refers to, as returned from \c Action::isTemplateName(). |
| 855 | /// |
| 856 | /// \param SS if non-NULL, the nested-name-specifier that precedes |
| 857 | /// this template name. |
| 858 | /// |
| 859 | /// \param TemplateKWLoc if valid, specifies that this template-id |
| 860 | /// annotation was preceded by the 'template' keyword and gives the |
| 861 | /// location of that keyword. If invalid (the default), then this |
| 862 | /// template-id was not preceded by a 'template' keyword. |
| 863 | /// |
| 864 | /// \param AllowTypeAnnotation if true (the default), then a |
| 865 | /// simple-template-id that refers to a class template, template |
| 866 | /// template parameter, or other template that produces a type will be |
| 867 | /// replaced with a type annotation token. Otherwise, the |
| 868 | /// simple-template-id is always replaced with a template-id |
| 869 | /// annotation token. |
| 870 | /// |
| 871 | /// If an unrecoverable parse error occurs and no annotation token can be |
| 872 | /// formed, this function returns true. |
| 873 | /// |
| 874 | bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, |
| 875 | CXXScopeSpec &SS, |
| 876 | SourceLocation TemplateKWLoc, |
| 877 | UnqualifiedId &TemplateName, |
| 878 | bool AllowTypeAnnotation) { |
| 879 | assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++"); |
| 880 | assert(Template && Tok.is(tok::less) && |
| 881 | "Parser isn't at the beginning of a template-id"); |
| 882 | |
| 883 | // Consume the template-name. |
| 884 | SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin(); |
| 885 | |
| 886 | // Parse the enclosed template argument list. |
| 887 | SourceLocation LAngleLoc, RAngleLoc; |
| 888 | TemplateArgList TemplateArgs; |
| 889 | bool Invalid = ParseTemplateIdAfterTemplateName(Template, |
| 890 | TemplateNameLoc, |
| 891 | SS, false, LAngleLoc, |
| 892 | TemplateArgs, |
| 893 | RAngleLoc); |
| 894 | |
| 895 | if (Invalid) { |
| 896 | // If we failed to parse the template ID but skipped ahead to a >, we're not |
| 897 | // going to be able to form a token annotation. Eat the '>' if present. |
| 898 | if (Tok.is(tok::greater)) |
| 899 | ConsumeToken(); |
| 900 | return true; |
| 901 | } |
| 902 | |
| 903 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs); |
| 904 | |
| 905 | // Build the annotation token. |
| 906 | if (TNK == TNK_Type_template && AllowTypeAnnotation) { |
| 907 | TypeResult Type |
| 908 | = Actions.ActOnTemplateIdType(SS, TemplateKWLoc, |
| 909 | Template, TemplateNameLoc, |
| 910 | LAngleLoc, TemplateArgsPtr, RAngleLoc); |
| 911 | if (Type.isInvalid()) { |
| 912 | // If we failed to parse the template ID but skipped ahead to a >, we're not |
| 913 | // going to be able to form a token annotation. Eat the '>' if present. |
| 914 | if (Tok.is(tok::greater)) |
| 915 | ConsumeToken(); |
| 916 | return true; |
| 917 | } |
| 918 | |
| 919 | Tok.setKind(tok::annot_typename); |
| 920 | setTypeAnnotation(Tok, Type.get()); |
| 921 | if (SS.isNotEmpty()) |
| 922 | Tok.setLocation(SS.getBeginLoc()); |
| 923 | else if (TemplateKWLoc.isValid()) |
| 924 | Tok.setLocation(TemplateKWLoc); |
| 925 | else |
| 926 | Tok.setLocation(TemplateNameLoc); |
| 927 | } else { |
| 928 | // Build a template-id annotation token that can be processed |
| 929 | // later. |
| 930 | Tok.setKind(tok::annot_template_id); |
| 931 | TemplateIdAnnotation *TemplateId |
| 932 | = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds); |
| 933 | TemplateId->TemplateNameLoc = TemplateNameLoc; |
| 934 | if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) { |
| 935 | TemplateId->Name = TemplateName.Identifier; |
| 936 | TemplateId->Operator = OO_None; |
| 937 | } else { |
| 938 | TemplateId->Name = 0; |
| 939 | TemplateId->Operator = TemplateName.OperatorFunctionId.Operator; |
| 940 | } |
| 941 | TemplateId->SS = SS; |
| 942 | TemplateId->TemplateKWLoc = TemplateKWLoc; |
| 943 | TemplateId->Template = Template; |
| 944 | TemplateId->Kind = TNK; |
| 945 | TemplateId->LAngleLoc = LAngleLoc; |
| 946 | TemplateId->RAngleLoc = RAngleLoc; |
| 947 | ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); |
| 948 | for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) |
| 949 | Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]); |
| 950 | Tok.setAnnotationValue(TemplateId); |
| 951 | if (TemplateKWLoc.isValid()) |
| 952 | Tok.setLocation(TemplateKWLoc); |
| 953 | else |
| 954 | Tok.setLocation(TemplateNameLoc); |
| 955 | } |
| 956 | |
| 957 | // Common fields for the annotation token |
| 958 | Tok.setAnnotationEndLoc(RAngleLoc); |
| 959 | |
| 960 | // In case the tokens were cached, have Preprocessor replace them with the |
| 961 | // annotation token. |
| 962 | PP.AnnotateCachedTokens(Tok); |
| 963 | return false; |
| 964 | } |
| 965 | |
| 966 | /// \brief Replaces a template-id annotation token with a type |
| 967 | /// annotation token. |
| 968 | /// |
| 969 | /// If there was a failure when forming the type from the template-id, |
| 970 | /// a type annotation token will still be created, but will have a |
| 971 | /// NULL type pointer to signify an error. |
| 972 | void Parser::AnnotateTemplateIdTokenAsType() { |
| 973 | assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens"); |
| 974 | |
| 975 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); |
| 976 | assert((TemplateId->Kind == TNK_Type_template || |
| 977 | TemplateId->Kind == TNK_Dependent_template_name) && |
| 978 | "Only works for type and dependent templates"); |
| 979 | |
| 980 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
| 981 | TemplateId->NumArgs); |
| 982 | |
| 983 | TypeResult Type |
| 984 | = Actions.ActOnTemplateIdType(TemplateId->SS, |
| 985 | TemplateId->TemplateKWLoc, |
| 986 | TemplateId->Template, |
| 987 | TemplateId->TemplateNameLoc, |
| 988 | TemplateId->LAngleLoc, |
| 989 | TemplateArgsPtr, |
| 990 | TemplateId->RAngleLoc); |
| 991 | // Create the new "type" annotation token. |
| 992 | Tok.setKind(tok::annot_typename); |
| 993 | setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get()); |
| 994 | if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name. |
| 995 | Tok.setLocation(TemplateId->SS.getBeginLoc()); |
| 996 | // End location stays the same |
| 997 | |
| 998 | // Replace the template-id annotation token, and possible the scope-specifier |
| 999 | // that precedes it, with the typename annotation token. |
| 1000 | PP.AnnotateCachedTokens(Tok); |
| 1001 | } |
| 1002 | |
| 1003 | /// \brief Determine whether the given token can end a template argument. |
| 1004 | static bool isEndOfTemplateArgument(Token Tok) { |
| 1005 | return Tok.is(tok::comma) || Tok.is(tok::greater) || |
| 1006 | Tok.is(tok::greatergreater); |
| 1007 | } |
| 1008 | |
| 1009 | /// \brief Parse a C++ template template argument. |
| 1010 | ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { |
| 1011 | if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) && |
| 1012 | !Tok.is(tok::annot_cxxscope)) |
| 1013 | return ParsedTemplateArgument(); |
| 1014 | |
| 1015 | // C++0x [temp.arg.template]p1: |
| 1016 | // A template-argument for a template template-parameter shall be the name |
| 1017 | // of a class template or an alias template, expressed as id-expression. |
| 1018 | // |
| 1019 | // We parse an id-expression that refers to a class template or alias |
| 1020 | // template. The grammar we parse is: |
| 1021 | // |
| 1022 | // nested-name-specifier[opt] template[opt] identifier ...[opt] |
| 1023 | // |
| 1024 | // followed by a token that terminates a template argument, such as ',', |
| 1025 | // '>', or (in some cases) '>>'. |
| 1026 | CXXScopeSpec SS; // nested-name-specifier, if present |
| 1027 | ParseOptionalCXXScopeSpecifier(SS, ParsedType(), |
| 1028 | /*EnteringContext=*/false); |
| 1029 | |
| 1030 | ParsedTemplateArgument Result; |
| 1031 | SourceLocation EllipsisLoc; |
| 1032 | if (SS.isSet() && Tok.is(tok::kw_template)) { |
| 1033 | // Parse the optional 'template' keyword following the |
| 1034 | // nested-name-specifier. |
| 1035 | SourceLocation TemplateKWLoc = ConsumeToken(); |
| 1036 | |
| 1037 | if (Tok.is(tok::identifier)) { |
| 1038 | // We appear to have a dependent template name. |
| 1039 | UnqualifiedId Name; |
| 1040 | Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); |
| 1041 | ConsumeToken(); // the identifier |
| 1042 | |
| 1043 | // Parse the ellipsis. |
| 1044 | if (Tok.is(tok::ellipsis)) |
| 1045 | EllipsisLoc = ConsumeToken(); |
| 1046 | |
| 1047 | // If the next token signals the end of a template argument, |
| 1048 | // then we have a dependent template name that could be a template |
| 1049 | // template argument. |
| 1050 | TemplateTy Template; |
| 1051 | if (isEndOfTemplateArgument(Tok) && |
| 1052 | Actions.ActOnDependentTemplateName(getCurScope(), |
| 1053 | SS, TemplateKWLoc, Name, |
| 1054 | /*ObjectType=*/ ParsedType(), |
| 1055 | /*EnteringContext=*/false, |
| 1056 | Template)) |
| 1057 | Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); |
| 1058 | } |
| 1059 | } else if (Tok.is(tok::identifier)) { |
| 1060 | // We may have a (non-dependent) template name. |
| 1061 | TemplateTy Template; |
| 1062 | UnqualifiedId Name; |
| 1063 | Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); |
| 1064 | ConsumeToken(); // the identifier |
| 1065 | |
| 1066 | // Parse the ellipsis. |
| 1067 | if (Tok.is(tok::ellipsis)) |
| 1068 | EllipsisLoc = ConsumeToken(); |
| 1069 | |
| 1070 | if (isEndOfTemplateArgument(Tok)) { |
| 1071 | bool MemberOfUnknownSpecialization; |
| 1072 | TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, |
| 1073 | /*hasTemplateKeyword=*/false, |
| 1074 | Name, |
| 1075 | /*ObjectType=*/ ParsedType(), |
| 1076 | /*EnteringContext=*/false, |
| 1077 | Template, |
| 1078 | MemberOfUnknownSpecialization); |
| 1079 | if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) { |
| 1080 | // We have an id-expression that refers to a class template or |
| 1081 | // (C++0x) alias template. |
| 1082 | Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); |
| 1083 | } |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | // If this is a pack expansion, build it as such. |
| 1088 | if (EllipsisLoc.isValid() && !Result.isInvalid()) |
| 1089 | Result = Actions.ActOnPackExpansion(Result, EllipsisLoc); |
| 1090 | |
| 1091 | return Result; |
| 1092 | } |
| 1093 | |
| 1094 | /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]). |
| 1095 | /// |
| 1096 | /// template-argument: [C++ 14.2] |
| 1097 | /// constant-expression |
| 1098 | /// type-id |
| 1099 | /// id-expression |
| 1100 | ParsedTemplateArgument Parser::ParseTemplateArgument() { |
| 1101 | // C++ [temp.arg]p2: |
| 1102 | // In a template-argument, an ambiguity between a type-id and an |
| 1103 | // expression is resolved to a type-id, regardless of the form of |
| 1104 | // the corresponding template-parameter. |
| 1105 | // |
| 1106 | // Therefore, we initially try to parse a type-id. |
| 1107 | if (isCXXTypeId(TypeIdAsTemplateArgument)) { |
| 1108 | SourceLocation Loc = Tok.getLocation(); |
| 1109 | TypeResult TypeArg = ParseTypeName(/*Range=*/0, |
| 1110 | Declarator::TemplateTypeArgContext); |
| 1111 | if (TypeArg.isInvalid()) |
| 1112 | return ParsedTemplateArgument(); |
| 1113 | |
| 1114 | return ParsedTemplateArgument(ParsedTemplateArgument::Type, |
| 1115 | TypeArg.get().getAsOpaquePtr(), |
| 1116 | Loc); |
| 1117 | } |
| 1118 | |
| 1119 | // Try to parse a template template argument. |
| 1120 | { |
| 1121 | TentativeParsingAction TPA(*this); |
| 1122 | |
| 1123 | ParsedTemplateArgument TemplateTemplateArgument |
| 1124 | = ParseTemplateTemplateArgument(); |
| 1125 | if (!TemplateTemplateArgument.isInvalid()) { |
| 1126 | TPA.Commit(); |
| 1127 | return TemplateTemplateArgument; |
| 1128 | } |
| 1129 | |
| 1130 | // Revert this tentative parse to parse a non-type template argument. |
| 1131 | TPA.Revert(); |
| 1132 | } |
| 1133 | |
| 1134 | // Parse a non-type template argument. |
| 1135 | SourceLocation Loc = Tok.getLocation(); |
| 1136 | ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast); |
| 1137 | if (ExprArg.isInvalid() || !ExprArg.get()) |
| 1138 | return ParsedTemplateArgument(); |
| 1139 | |
| 1140 | return ParsedTemplateArgument(ParsedTemplateArgument::NonType, |
| 1141 | ExprArg.release(), Loc); |
| 1142 | } |
| 1143 | |
| 1144 | /// \brief Determine whether the current tokens can only be parsed as a |
| 1145 | /// template argument list (starting with the '<') and never as a '<' |
| 1146 | /// expression. |
| 1147 | bool Parser::IsTemplateArgumentList(unsigned Skip) { |
| 1148 | struct AlwaysRevertAction : TentativeParsingAction { |
| 1149 | AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { } |
| 1150 | ~AlwaysRevertAction() { Revert(); } |
| 1151 | } Tentative(*this); |
| 1152 | |
| 1153 | while (Skip) { |
| 1154 | ConsumeToken(); |
| 1155 | --Skip; |
| 1156 | } |
| 1157 | |
| 1158 | // '<' |
| 1159 | if (!Tok.is(tok::less)) |
| 1160 | return false; |
| 1161 | ConsumeToken(); |
| 1162 | |
| 1163 | // An empty template argument list. |
| 1164 | if (Tok.is(tok::greater)) |
| 1165 | return true; |
| 1166 | |
| 1167 | // See whether we have declaration specifiers, which indicate a type. |
| 1168 | while (isCXXDeclarationSpecifier() == TPResult::True()) |
| 1169 | ConsumeToken(); |
| 1170 | |
| 1171 | // If we have a '>' or a ',' then this is a template argument list. |
| 1172 | return Tok.is(tok::greater) || Tok.is(tok::comma); |
| 1173 | } |
| 1174 | |
| 1175 | /// ParseTemplateArgumentList - Parse a C++ template-argument-list |
| 1176 | /// (C++ [temp.names]). Returns true if there was an error. |
| 1177 | /// |
| 1178 | /// template-argument-list: [C++ 14.2] |
| 1179 | /// template-argument |
| 1180 | /// template-argument-list ',' template-argument |
| 1181 | bool |
| 1182 | Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { |
| 1183 | // Template argument lists are constant-evaluation contexts. |
| 1184 | EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated); |
| 1185 | |
| 1186 | while (true) { |
| 1187 | ParsedTemplateArgument Arg = ParseTemplateArgument(); |
| 1188 | if (Tok.is(tok::ellipsis)) { |
| 1189 | SourceLocation EllipsisLoc = ConsumeToken(); |
| 1190 | Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc); |
| 1191 | } |
| 1192 | |
| 1193 | if (Arg.isInvalid()) { |
| 1194 | SkipUntil(tok::comma, tok::greater, true, true); |
| 1195 | return true; |
| 1196 | } |
| 1197 | |
| 1198 | // Save this template argument. |
| 1199 | TemplateArgs.push_back(Arg); |
| 1200 | |
| 1201 | // If the next token is a comma, consume it and keep reading |
| 1202 | // arguments. |
| 1203 | if (Tok.isNot(tok::comma)) break; |
| 1204 | |
| 1205 | // Consume the comma. |
| 1206 | ConsumeToken(); |
| 1207 | } |
| 1208 | |
| 1209 | return false; |
| 1210 | } |
| 1211 | |
| 1212 | /// \brief Parse a C++ explicit template instantiation |
| 1213 | /// (C++ [temp.explicit]). |
| 1214 | /// |
| 1215 | /// explicit-instantiation: |
| 1216 | /// 'extern' [opt] 'template' declaration |
| 1217 | /// |
| 1218 | /// Note that the 'extern' is a GNU extension and C++11 feature. |
| 1219 | Decl *Parser::ParseExplicitInstantiation(unsigned Context, |
| 1220 | SourceLocation ExternLoc, |
| 1221 | SourceLocation TemplateLoc, |
| 1222 | SourceLocation &DeclEnd, |
| 1223 | AccessSpecifier AS) { |
| 1224 | // This isn't really required here. |
| 1225 | ParsingDeclRAIIObject |
| 1226 | ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); |
| 1227 | |
| 1228 | return ParseSingleDeclarationAfterTemplate(Context, |
| 1229 | ParsedTemplateInfo(ExternLoc, |
| 1230 | TemplateLoc), |
| 1231 | ParsingTemplateParams, |
| 1232 | DeclEnd, AS); |
| 1233 | } |
| 1234 | |
| 1235 | SourceRange Parser::ParsedTemplateInfo::getSourceRange() const { |
| 1236 | if (TemplateParams) |
| 1237 | return getTemplateParamsRange(TemplateParams->data(), |
| 1238 | TemplateParams->size()); |
| 1239 | |
| 1240 | SourceRange R(TemplateLoc); |
| 1241 | if (ExternLoc.isValid()) |
| 1242 | R.setBegin(ExternLoc); |
| 1243 | return R; |
| 1244 | } |
| 1245 | |
| 1246 | void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) { |
| 1247 | ((Parser*)P)->LateTemplateParser(FD); |
| 1248 | } |
| 1249 | |
| 1250 | |
| 1251 | void Parser::LateTemplateParser(const FunctionDecl *FD) { |
| 1252 | LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD]; |
| 1253 | if (LPT) { |
| 1254 | ParseLateTemplatedFuncDef(*LPT); |
| 1255 | return; |
| 1256 | } |
| 1257 | |
| 1258 | llvm_unreachable("Late templated function without associated lexed tokens"); |
| 1259 | } |
| 1260 | |
| 1261 | /// \brief Late parse a C++ function template in Microsoft mode. |
| 1262 | void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) { |
| 1263 | if(!LMT.D) |
| 1264 | return; |
| 1265 | |
| 1266 | // Get the FunctionDecl. |
| 1267 | FunctionTemplateDecl *FunTmplD = dyn_cast<FunctionTemplateDecl>(LMT.D); |
| 1268 | FunctionDecl *FunD = |
| 1269 | FunTmplD ? FunTmplD->getTemplatedDecl() : cast<FunctionDecl>(LMT.D); |
| 1270 | // Track template parameter depth. |
| 1271 | TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); |
| 1272 | |
| 1273 | // To restore the context after late parsing. |
| 1274 | Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext); |
| 1275 | |
| 1276 | SmallVector<ParseScope*, 4> TemplateParamScopeStack; |
| 1277 | |
| 1278 | // Get the list of DeclContexts to reenter. |
| 1279 | SmallVector<DeclContext*, 4> DeclContextsToReenter; |
| 1280 | DeclContext *DD = FunD->getLexicalParent(); |
| 1281 | while (DD && !DD->isTranslationUnit()) { |
| 1282 | DeclContextsToReenter.push_back(DD); |
| 1283 | DD = DD->getLexicalParent(); |
| 1284 | } |
| 1285 | |
| 1286 | // Reenter template scopes from outermost to innermost. |
| 1287 | SmallVector<DeclContext*, 4>::reverse_iterator II = |
| 1288 | DeclContextsToReenter.rbegin(); |
| 1289 | for (; II != DeclContextsToReenter.rend(); ++II) { |
| 1290 | if (ClassTemplatePartialSpecializationDecl *MD = |
| 1291 | dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) { |
| 1292 | TemplateParamScopeStack.push_back( |
| 1293 | new ParseScope(this, Scope::TemplateParamScope)); |
| 1294 | Actions.ActOnReenterTemplateScope(getCurScope(), MD); |
| 1295 | ++CurTemplateDepthTracker; |
| 1296 | } else if (CXXRecordDecl *MD = dyn_cast_or_null<CXXRecordDecl>(*II)) { |
Faisal Vali | 688f986 | 2013-06-08 19:47:52 +0000 | [diff] [blame] | 1297 | bool IsClassTemplate = MD->getDescribedClassTemplate() != 0; |
Faisal Vali | 65efd10 | 2013-06-08 19:39:00 +0000 | [diff] [blame] | 1298 | TemplateParamScopeStack.push_back( |
Faisal Vali | 688f986 | 2013-06-08 19:47:52 +0000 | [diff] [blame] | 1299 | new ParseScope(this, Scope::TemplateParamScope, |
| 1300 | /*ManageScope*/IsClassTemplate)); |
Faisal Vali | 65efd10 | 2013-06-08 19:39:00 +0000 | [diff] [blame] | 1301 | Actions.ActOnReenterTemplateScope(getCurScope(), |
| 1302 | MD->getDescribedClassTemplate()); |
Faisal Vali | 688f986 | 2013-06-08 19:47:52 +0000 | [diff] [blame] | 1303 | if (IsClassTemplate) |
| 1304 | ++CurTemplateDepthTracker; |
Faisal Vali | 65efd10 | 2013-06-08 19:39:00 +0000 | [diff] [blame] | 1305 | } |
| 1306 | TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope)); |
| 1307 | Actions.PushDeclContext(Actions.getCurScope(), *II); |
| 1308 | } |
| 1309 | TemplateParamScopeStack.push_back( |
| 1310 | new ParseScope(this, Scope::TemplateParamScope)); |
| 1311 | |
| 1312 | DeclaratorDecl *Declarator = dyn_cast<DeclaratorDecl>(FunD); |
| 1313 | if (Declarator && Declarator->getNumTemplateParameterLists() != 0) { |
| 1314 | Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator); |
| 1315 | ++CurTemplateDepthTracker; |
| 1316 | } |
| 1317 | Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D); |
| 1318 | ++CurTemplateDepthTracker; |
| 1319 | |
| 1320 | assert(!LMT.Toks.empty() && "Empty body!"); |
| 1321 | |
| 1322 | // Append the current token at the end of the new token stream so that it |
| 1323 | // doesn't get lost. |
| 1324 | LMT.Toks.push_back(Tok); |
| 1325 | PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false); |
| 1326 | |
| 1327 | // Consume the previously pushed token. |
| 1328 | ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); |
| 1329 | assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) |
| 1330 | && "Inline method not starting with '{', ':' or 'try'"); |
| 1331 | |
| 1332 | // Parse the method body. Function body parsing code is similar enough |
| 1333 | // to be re-used for method bodies as well. |
| 1334 | ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope); |
| 1335 | |
| 1336 | // Recreate the containing function DeclContext. |
| 1337 | Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD)); |
| 1338 | |
| 1339 | Actions.ActOnStartOfFunctionDef(getCurScope(), FunD); |
| 1340 | |
| 1341 | if (Tok.is(tok::kw_try)) { |
| 1342 | ParseFunctionTryBlock(LMT.D, FnScope); |
| 1343 | } else { |
| 1344 | if (Tok.is(tok::colon)) |
| 1345 | ParseConstructorInitializer(LMT.D); |
| 1346 | else |
| 1347 | Actions.ActOnDefaultCtorInitializers(LMT.D); |
| 1348 | |
| 1349 | if (Tok.is(tok::l_brace)) { |
| 1350 | assert((!FunTmplD || FunTmplD->getTemplateParameters()->getDepth() < |
| 1351 | TemplateParameterDepth) && |
| 1352 | "TemplateParameterDepth should be greater than the depth of " |
| 1353 | "current template being instantiated!"); |
| 1354 | ParseFunctionStatementBody(LMT.D, FnScope); |
| 1355 | Actions.MarkAsLateParsedTemplate(FunD, false); |
| 1356 | } else |
| 1357 | Actions.ActOnFinishFunctionBody(LMT.D, 0); |
| 1358 | } |
| 1359 | |
| 1360 | // Exit scopes. |
| 1361 | FnScope.Exit(); |
| 1362 | SmallVector<ParseScope*, 4>::reverse_iterator I = |
| 1363 | TemplateParamScopeStack.rbegin(); |
| 1364 | for (; I != TemplateParamScopeStack.rend(); ++I) |
| 1365 | delete *I; |
| 1366 | |
| 1367 | DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D); |
| 1368 | if (grp) |
| 1369 | Actions.getASTConsumer().HandleTopLevelDecl(grp.get()); |
| 1370 | } |
| 1371 | |
| 1372 | /// \brief Lex a delayed template function for late parsing. |
| 1373 | void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) { |
| 1374 | tok::TokenKind kind = Tok.getKind(); |
| 1375 | if (!ConsumeAndStoreFunctionPrologue(Toks)) { |
| 1376 | // Consume everything up to (and including) the matching right brace. |
| 1377 | ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); |
| 1378 | } |
| 1379 | |
| 1380 | // If we're in a function-try-block, we need to store all the catch blocks. |
| 1381 | if (kind == tok::kw_try) { |
| 1382 | while (Tok.is(tok::kw_catch)) { |
| 1383 | ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); |
| 1384 | ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); |
| 1385 | } |
| 1386 | } |
| 1387 | } |