clang API Documentation
00001 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements parsing of C++ templates. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Parse/Parser.h" 00015 #include "clang/Parse/ParseDiagnostic.h" 00016 #include "clang/Sema/DeclSpec.h" 00017 #include "clang/Sema/ParsedTemplate.h" 00018 #include "clang/Sema/Scope.h" 00019 #include "RAIIObjectsForParser.h" 00020 #include "clang/AST/DeclTemplate.h" 00021 #include "clang/AST/ASTConsumer.h" 00022 using namespace clang; 00023 00024 /// \brief Parse a template declaration, explicit instantiation, or 00025 /// explicit specialization. 00026 Decl * 00027 Parser::ParseDeclarationStartingWithTemplate(unsigned Context, 00028 SourceLocation &DeclEnd, 00029 AccessSpecifier AS, 00030 AttributeList *AccessAttrs) { 00031 ObjCDeclContextSwitch ObjCDC(*this); 00032 00033 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) { 00034 return ParseExplicitInstantiation(Context, 00035 SourceLocation(), ConsumeToken(), 00036 DeclEnd, AS); 00037 } 00038 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS, 00039 AccessAttrs); 00040 } 00041 00042 /// \brief RAII class that manages the template parameter depth. 00043 namespace { 00044 class TemplateParameterDepthCounter { 00045 unsigned &Depth; 00046 unsigned AddedLevels; 00047 00048 public: 00049 explicit TemplateParameterDepthCounter(unsigned &Depth) 00050 : Depth(Depth), AddedLevels(0) { } 00051 00052 ~TemplateParameterDepthCounter() { 00053 Depth -= AddedLevels; 00054 } 00055 00056 void operator++() { 00057 ++Depth; 00058 ++AddedLevels; 00059 } 00060 00061 operator unsigned() const { return Depth; } 00062 }; 00063 } 00064 00065 /// \brief Parse a template declaration or an explicit specialization. 00066 /// 00067 /// Template declarations include one or more template parameter lists 00068 /// and either the function or class template declaration. Explicit 00069 /// specializations contain one or more 'template < >' prefixes 00070 /// followed by a (possibly templated) declaration. Since the 00071 /// syntactic form of both features is nearly identical, we parse all 00072 /// of the template headers together and let semantic analysis sort 00073 /// the declarations from the explicit specializations. 00074 /// 00075 /// template-declaration: [C++ temp] 00076 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration 00077 /// 00078 /// explicit-specialization: [ C++ temp.expl.spec] 00079 /// 'template' '<' '>' declaration 00080 Decl * 00081 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context, 00082 SourceLocation &DeclEnd, 00083 AccessSpecifier AS, 00084 AttributeList *AccessAttrs) { 00085 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) && 00086 "Token does not start a template declaration."); 00087 00088 // Enter template-parameter scope. 00089 ParseScope TemplateParmScope(this, Scope::TemplateParamScope); 00090 00091 // Tell the action that names should be checked in the context of 00092 // the declaration to come. 00093 ParsingDeclRAIIObject 00094 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); 00095 00096 // Parse multiple levels of template headers within this template 00097 // parameter scope, e.g., 00098 // 00099 // template<typename T> 00100 // template<typename U> 00101 // class A<T>::B { ... }; 00102 // 00103 // We parse multiple levels non-recursively so that we can build a 00104 // single data structure containing all of the template parameter 00105 // lists to easily differentiate between the case above and: 00106 // 00107 // template<typename T> 00108 // class A { 00109 // template<typename U> class B; 00110 // }; 00111 // 00112 // In the first case, the action for declaring A<T>::B receives 00113 // both template parameter lists. In the second case, the action for 00114 // defining A<T>::B receives just the inner template parameter list 00115 // (and retrieves the outer template parameter list from its 00116 // context). 00117 bool isSpecialization = true; 00118 bool LastParamListWasEmpty = false; 00119 TemplateParameterLists ParamLists; 00120 TemplateParameterDepthCounter Depth(TemplateParameterDepth); 00121 do { 00122 // Consume the 'export', if any. 00123 SourceLocation ExportLoc; 00124 if (Tok.is(tok::kw_export)) { 00125 ExportLoc = ConsumeToken(); 00126 } 00127 00128 // Consume the 'template', which should be here. 00129 SourceLocation TemplateLoc; 00130 if (Tok.is(tok::kw_template)) { 00131 TemplateLoc = ConsumeToken(); 00132 } else { 00133 Diag(Tok.getLocation(), diag::err_expected_template); 00134 return 0; 00135 } 00136 00137 // Parse the '<' template-parameter-list '>' 00138 SourceLocation LAngleLoc, RAngleLoc; 00139 SmallVector<Decl*, 4> TemplateParams; 00140 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc, 00141 RAngleLoc)) { 00142 // Skip until the semi-colon or a }. 00143 SkipUntil(tok::r_brace, true, true); 00144 if (Tok.is(tok::semi)) 00145 ConsumeToken(); 00146 return 0; 00147 } 00148 00149 ParamLists.push_back( 00150 Actions.ActOnTemplateParameterList(Depth, ExportLoc, 00151 TemplateLoc, LAngleLoc, 00152 TemplateParams.data(), 00153 TemplateParams.size(), RAngleLoc)); 00154 00155 if (!TemplateParams.empty()) { 00156 isSpecialization = false; 00157 ++Depth; 00158 } else { 00159 LastParamListWasEmpty = true; 00160 } 00161 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template)); 00162 00163 // Parse the actual template declaration. 00164 return ParseSingleDeclarationAfterTemplate(Context, 00165 ParsedTemplateInfo(&ParamLists, 00166 isSpecialization, 00167 LastParamListWasEmpty), 00168 ParsingTemplateParams, 00169 DeclEnd, AS, AccessAttrs); 00170 } 00171 00172 /// \brief Parse a single declaration that declares a template, 00173 /// template specialization, or explicit instantiation of a template. 00174 /// 00175 /// \param TemplateParams if non-NULL, the template parameter lists 00176 /// that preceded this declaration. In this case, the declaration is a 00177 /// template declaration, out-of-line definition of a template, or an 00178 /// explicit template specialization. When NULL, the declaration is an 00179 /// explicit template instantiation. 00180 /// 00181 /// \param TemplateLoc when TemplateParams is NULL, the location of 00182 /// the 'template' keyword that indicates that we have an explicit 00183 /// template instantiation. 00184 /// 00185 /// \param DeclEnd will receive the source location of the last token 00186 /// within this declaration. 00187 /// 00188 /// \param AS the access specifier associated with this 00189 /// declaration. Will be AS_none for namespace-scope declarations. 00190 /// 00191 /// \returns the new declaration. 00192 Decl * 00193 Parser::ParseSingleDeclarationAfterTemplate( 00194 unsigned Context, 00195 const ParsedTemplateInfo &TemplateInfo, 00196 ParsingDeclRAIIObject &DiagsFromTParams, 00197 SourceLocation &DeclEnd, 00198 AccessSpecifier AS, 00199 AttributeList *AccessAttrs) { 00200 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 00201 "Template information required"); 00202 00203 if (Context == Declarator::MemberContext) { 00204 // We are parsing a member template. 00205 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo, 00206 &DiagsFromTParams); 00207 return 0; 00208 } 00209 00210 ParsedAttributesWithRange prefixAttrs(AttrFactory); 00211 MaybeParseCXX0XAttributes(prefixAttrs); 00212 00213 if (Tok.is(tok::kw_using)) 00214 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd, 00215 prefixAttrs); 00216 00217 // Parse the declaration specifiers, stealing any diagnostics from 00218 // the template parameters. 00219 ParsingDeclSpec DS(*this, &DiagsFromTParams); 00220 00221 // Move the attributes from the prefix into the DS. 00222 DS.takeAttributesFrom(prefixAttrs); 00223 00224 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, 00225 getDeclSpecContextFromDeclaratorContext(Context)); 00226 00227 if (Tok.is(tok::semi)) { 00228 DeclEnd = ConsumeToken(); 00229 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); 00230 DS.complete(Decl); 00231 return Decl; 00232 } 00233 00234 // Parse the declarator. 00235 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context); 00236 ParseDeclarator(DeclaratorInfo); 00237 // Error parsing the declarator? 00238 if (!DeclaratorInfo.hasName()) { 00239 // If so, skip until the semi-colon or a }. 00240 SkipUntil(tok::r_brace, true, true); 00241 if (Tok.is(tok::semi)) 00242 ConsumeToken(); 00243 return 0; 00244 } 00245 00246 LateParsedAttrList LateParsedAttrs; 00247 if (DeclaratorInfo.isFunctionDeclarator()) 00248 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 00249 00250 // If we have a declaration or declarator list, handle it. 00251 if (isDeclarationAfterDeclarator()) { 00252 // Parse this declaration. 00253 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo, 00254 TemplateInfo); 00255 00256 if (Tok.is(tok::comma)) { 00257 Diag(Tok, diag::err_multiple_template_declarators) 00258 << (int)TemplateInfo.Kind; 00259 SkipUntil(tok::semi, true, false); 00260 return ThisDecl; 00261 } 00262 00263 // Eat the semi colon after the declaration. 00264 ExpectAndConsumeSemi(diag::err_expected_semi_declaration); 00265 if (LateParsedAttrs.size() > 0) 00266 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false); 00267 DeclaratorInfo.complete(ThisDecl); 00268 return ThisDecl; 00269 } 00270 00271 if (DeclaratorInfo.isFunctionDeclarator() && 00272 isStartOfFunctionDefinition(DeclaratorInfo)) { 00273 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 00274 // Recover by ignoring the 'typedef'. This was probably supposed to be 00275 // the 'typename' keyword, which we should have already suggested adding 00276 // if it's appropriate. 00277 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef) 00278 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 00279 DS.ClearStorageClassSpecs(); 00280 } 00281 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo, 00282 &LateParsedAttrs); 00283 } 00284 00285 if (DeclaratorInfo.isFunctionDeclarator()) 00286 Diag(Tok, diag::err_expected_fn_body); 00287 else 00288 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator); 00289 SkipUntil(tok::semi); 00290 return 0; 00291 } 00292 00293 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in 00294 /// angle brackets. Depth is the depth of this template-parameter-list, which 00295 /// is the number of template headers directly enclosing this template header. 00296 /// TemplateParams is the current list of template parameters we're building. 00297 /// The template parameter we parse will be added to this list. LAngleLoc and 00298 /// RAngleLoc will receive the positions of the '<' and '>', respectively, 00299 /// that enclose this template parameter list. 00300 /// 00301 /// \returns true if an error occurred, false otherwise. 00302 bool Parser::ParseTemplateParameters(unsigned Depth, 00303 SmallVectorImpl<Decl*> &TemplateParams, 00304 SourceLocation &LAngleLoc, 00305 SourceLocation &RAngleLoc) { 00306 // Get the template parameter list. 00307 if (!Tok.is(tok::less)) { 00308 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template"; 00309 return true; 00310 } 00311 LAngleLoc = ConsumeToken(); 00312 00313 // Try to parse the template parameter list. 00314 bool Failed = false; 00315 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater)) 00316 Failed = ParseTemplateParameterList(Depth, TemplateParams); 00317 00318 if (Tok.is(tok::greatergreater)) { 00319 Tok.setKind(tok::greater); 00320 RAngleLoc = Tok.getLocation(); 00321 Tok.setLocation(Tok.getLocation().getLocWithOffset(1)); 00322 } else if (Tok.is(tok::greater)) 00323 RAngleLoc = ConsumeToken(); 00324 else if (Failed) { 00325 Diag(Tok.getLocation(), diag::err_expected_greater); 00326 return true; 00327 } 00328 return false; 00329 } 00330 00331 /// ParseTemplateParameterList - Parse a template parameter list. If 00332 /// the parsing fails badly (i.e., closing bracket was left out), this 00333 /// will try to put the token stream in a reasonable position (closing 00334 /// a statement, etc.) and return false. 00335 /// 00336 /// template-parameter-list: [C++ temp] 00337 /// template-parameter 00338 /// template-parameter-list ',' template-parameter 00339 bool 00340 Parser::ParseTemplateParameterList(unsigned Depth, 00341 SmallVectorImpl<Decl*> &TemplateParams) { 00342 while (1) { 00343 if (Decl *TmpParam 00344 = ParseTemplateParameter(Depth, TemplateParams.size())) { 00345 TemplateParams.push_back(TmpParam); 00346 } else { 00347 // If we failed to parse a template parameter, skip until we find 00348 // a comma or closing brace. 00349 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true); 00350 } 00351 00352 // Did we find a comma or the end of the template parmeter list? 00353 if (Tok.is(tok::comma)) { 00354 ConsumeToken(); 00355 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) { 00356 // Don't consume this... that's done by template parser. 00357 break; 00358 } else { 00359 // Somebody probably forgot to close the template. Skip ahead and 00360 // try to get out of the expression. This error is currently 00361 // subsumed by whatever goes on in ParseTemplateParameter. 00362 Diag(Tok.getLocation(), diag::err_expected_comma_greater); 00363 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true); 00364 return false; 00365 } 00366 } 00367 return true; 00368 } 00369 00370 /// \brief Determine whether the parser is at the start of a template 00371 /// type parameter. 00372 bool Parser::isStartOfTemplateTypeParameter() { 00373 if (Tok.is(tok::kw_class)) { 00374 // "class" may be the start of an elaborated-type-specifier or a 00375 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter. 00376 switch (NextToken().getKind()) { 00377 case tok::equal: 00378 case tok::comma: 00379 case tok::greater: 00380 case tok::greatergreater: 00381 case tok::ellipsis: 00382 return true; 00383 00384 case tok::identifier: 00385 // This may be either a type-parameter or an elaborated-type-specifier. 00386 // We have to look further. 00387 break; 00388 00389 default: 00390 return false; 00391 } 00392 00393 switch (GetLookAheadToken(2).getKind()) { 00394 case tok::equal: 00395 case tok::comma: 00396 case tok::greater: 00397 case tok::greatergreater: 00398 return true; 00399 00400 default: 00401 return false; 00402 } 00403 } 00404 00405 if (Tok.isNot(tok::kw_typename)) 00406 return false; 00407 00408 // C++ [temp.param]p2: 00409 // There is no semantic difference between class and typename in a 00410 // template-parameter. typename followed by an unqualified-id 00411 // names a template type parameter. typename followed by a 00412 // qualified-id denotes the type in a non-type 00413 // parameter-declaration. 00414 Token Next = NextToken(); 00415 00416 // If we have an identifier, skip over it. 00417 if (Next.getKind() == tok::identifier) 00418 Next = GetLookAheadToken(2); 00419 00420 switch (Next.getKind()) { 00421 case tok::equal: 00422 case tok::comma: 00423 case tok::greater: 00424 case tok::greatergreater: 00425 case tok::ellipsis: 00426 return true; 00427 00428 default: 00429 return false; 00430 } 00431 } 00432 00433 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]). 00434 /// 00435 /// template-parameter: [C++ temp.param] 00436 /// type-parameter 00437 /// parameter-declaration 00438 /// 00439 /// type-parameter: (see below) 00440 /// 'class' ...[opt] identifier[opt] 00441 /// 'class' identifier[opt] '=' type-id 00442 /// 'typename' ...[opt] identifier[opt] 00443 /// 'typename' identifier[opt] '=' type-id 00444 /// 'template' '<' template-parameter-list '>' 00445 /// 'class' ...[opt] identifier[opt] 00446 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] 00447 /// = id-expression 00448 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) { 00449 if (isStartOfTemplateTypeParameter()) 00450 return ParseTypeParameter(Depth, Position); 00451 00452 if (Tok.is(tok::kw_template)) 00453 return ParseTemplateTemplateParameter(Depth, Position); 00454 00455 // If it's none of the above, then it must be a parameter declaration. 00456 // NOTE: This will pick up errors in the closure of the template parameter 00457 // list (e.g., template < ; Check here to implement >> style closures. 00458 return ParseNonTypeTemplateParameter(Depth, Position); 00459 } 00460 00461 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]). 00462 /// Other kinds of template parameters are parsed in 00463 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter. 00464 /// 00465 /// type-parameter: [C++ temp.param] 00466 /// 'class' ...[opt][C++0x] identifier[opt] 00467 /// 'class' identifier[opt] '=' type-id 00468 /// 'typename' ...[opt][C++0x] identifier[opt] 00469 /// 'typename' identifier[opt] '=' type-id 00470 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) { 00471 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) && 00472 "A type-parameter starts with 'class' or 'typename'"); 00473 00474 // Consume the 'class' or 'typename' keyword. 00475 bool TypenameKeyword = Tok.is(tok::kw_typename); 00476 SourceLocation KeyLoc = ConsumeToken(); 00477 00478 // Grab the ellipsis (if given). 00479 bool Ellipsis = false; 00480 SourceLocation EllipsisLoc; 00481 if (Tok.is(tok::ellipsis)) { 00482 Ellipsis = true; 00483 EllipsisLoc = ConsumeToken(); 00484 00485 Diag(EllipsisLoc, 00486 getLangOpts().CPlusPlus0x 00487 ? diag::warn_cxx98_compat_variadic_templates 00488 : diag::ext_variadic_templates); 00489 } 00490 00491 // Grab the template parameter name (if given) 00492 SourceLocation NameLoc; 00493 IdentifierInfo* ParamName = 0; 00494 if (Tok.is(tok::identifier)) { 00495 ParamName = Tok.getIdentifierInfo(); 00496 NameLoc = ConsumeToken(); 00497 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || 00498 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) { 00499 // Unnamed template parameter. Don't have to do anything here, just 00500 // don't consume this token. 00501 } else { 00502 Diag(Tok.getLocation(), diag::err_expected_ident); 00503 return 0; 00504 } 00505 00506 // Grab a default argument (if available). 00507 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before 00508 // we introduce the type parameter into the local scope. 00509 SourceLocation EqualLoc; 00510 ParsedType DefaultArg; 00511 if (Tok.is(tok::equal)) { 00512 EqualLoc = ConsumeToken(); 00513 DefaultArg = ParseTypeName(/*Range=*/0, 00514 Declarator::TemplateTypeArgContext).get(); 00515 } 00516 00517 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis, 00518 EllipsisLoc, KeyLoc, ParamName, NameLoc, 00519 Depth, Position, EqualLoc, DefaultArg); 00520 } 00521 00522 /// ParseTemplateTemplateParameter - Handle the parsing of template 00523 /// template parameters. 00524 /// 00525 /// type-parameter: [C++ temp.param] 00526 /// 'template' '<' template-parameter-list '>' 'class' 00527 /// ...[opt] identifier[opt] 00528 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] 00529 /// = id-expression 00530 Decl * 00531 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { 00532 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword"); 00533 00534 // Handle the template <...> part. 00535 SourceLocation TemplateLoc = ConsumeToken(); 00536 SmallVector<Decl*,8> TemplateParams; 00537 SourceLocation LAngleLoc, RAngleLoc; 00538 { 00539 ParseScope TemplateParmScope(this, Scope::TemplateParamScope); 00540 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc, 00541 RAngleLoc)) { 00542 return 0; 00543 } 00544 } 00545 00546 // Generate a meaningful error if the user forgot to put class before the 00547 // identifier, comma, or greater. Provide a fixit if the identifier, comma, 00548 // or greater appear immediately or after 'typename' or 'struct'. In the 00549 // latter case, replace the keyword with 'class'. 00550 if (!Tok.is(tok::kw_class)) { 00551 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct); 00552 const Token& Next = Replace ? NextToken() : Tok; 00553 if (Next.is(tok::identifier) || Next.is(tok::comma) || 00554 Next.is(tok::greater) || Next.is(tok::greatergreater) || 00555 Next.is(tok::ellipsis)) 00556 Diag(Tok.getLocation(), diag::err_class_on_template_template_param) 00557 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class") 00558 : FixItHint::CreateInsertion(Tok.getLocation(), "class ")); 00559 else 00560 Diag(Tok.getLocation(), diag::err_class_on_template_template_param); 00561 00562 if (Replace) 00563 ConsumeToken(); 00564 } else 00565 ConsumeToken(); 00566 00567 // Parse the ellipsis, if given. 00568 SourceLocation EllipsisLoc; 00569 if (Tok.is(tok::ellipsis)) { 00570 EllipsisLoc = ConsumeToken(); 00571 00572 Diag(EllipsisLoc, 00573 getLangOpts().CPlusPlus0x 00574 ? diag::warn_cxx98_compat_variadic_templates 00575 : diag::ext_variadic_templates); 00576 } 00577 00578 // Get the identifier, if given. 00579 SourceLocation NameLoc; 00580 IdentifierInfo* ParamName = 0; 00581 if (Tok.is(tok::identifier)) { 00582 ParamName = Tok.getIdentifierInfo(); 00583 NameLoc = ConsumeToken(); 00584 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || 00585 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) { 00586 // Unnamed template parameter. Don't have to do anything here, just 00587 // don't consume this token. 00588 } else { 00589 Diag(Tok.getLocation(), diag::err_expected_ident); 00590 return 0; 00591 } 00592 00593 TemplateParameterList *ParamList = 00594 Actions.ActOnTemplateParameterList(Depth, SourceLocation(), 00595 TemplateLoc, LAngleLoc, 00596 TemplateParams.data(), 00597 TemplateParams.size(), 00598 RAngleLoc); 00599 00600 // Grab a default argument (if available). 00601 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before 00602 // we introduce the template parameter into the local scope. 00603 SourceLocation EqualLoc; 00604 ParsedTemplateArgument DefaultArg; 00605 if (Tok.is(tok::equal)) { 00606 EqualLoc = ConsumeToken(); 00607 DefaultArg = ParseTemplateTemplateArgument(); 00608 if (DefaultArg.isInvalid()) { 00609 Diag(Tok.getLocation(), 00610 diag::err_default_template_template_parameter_not_template); 00611 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true); 00612 } 00613 } 00614 00615 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc, 00616 ParamList, EllipsisLoc, 00617 ParamName, NameLoc, Depth, 00618 Position, EqualLoc, DefaultArg); 00619 } 00620 00621 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type 00622 /// template parameters (e.g., in "template<int Size> class array;"). 00623 /// 00624 /// template-parameter: 00625 /// ... 00626 /// parameter-declaration 00627 Decl * 00628 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { 00629 // Parse the declaration-specifiers (i.e., the type). 00630 // FIXME: The type should probably be restricted in some way... Not all 00631 // declarators (parts of declarators?) are accepted for parameters. 00632 DeclSpec DS(AttrFactory); 00633 ParseDeclarationSpecifiers(DS); 00634 00635 // Parse this as a typename. 00636 Declarator ParamDecl(DS, Declarator::TemplateParamContext); 00637 ParseDeclarator(ParamDecl); 00638 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 00639 Diag(Tok.getLocation(), diag::err_expected_template_parameter); 00640 return 0; 00641 } 00642 00643 // If there is a default value, parse it. 00644 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before 00645 // we introduce the template parameter into the local scope. 00646 SourceLocation EqualLoc; 00647 ExprResult DefaultArg; 00648 if (Tok.is(tok::equal)) { 00649 EqualLoc = ConsumeToken(); 00650 00651 // C++ [temp.param]p15: 00652 // When parsing a default template-argument for a non-type 00653 // template-parameter, the first non-nested > is taken as the 00654 // end of the template-parameter-list rather than a greater-than 00655 // operator. 00656 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); 00657 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 00658 00659 DefaultArg = ParseAssignmentExpression(); 00660 if (DefaultArg.isInvalid()) 00661 SkipUntil(tok::comma, tok::greater, true, true); 00662 } 00663 00664 // Create the parameter. 00665 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, 00666 Depth, Position, EqualLoc, 00667 DefaultArg.take()); 00668 } 00669 00670 /// \brief Parses a template-id that after the template name has 00671 /// already been parsed. 00672 /// 00673 /// This routine takes care of parsing the enclosed template argument 00674 /// list ('<' template-parameter-list [opt] '>') and placing the 00675 /// results into a form that can be transferred to semantic analysis. 00676 /// 00677 /// \param Template the template declaration produced by isTemplateName 00678 /// 00679 /// \param TemplateNameLoc the source location of the template name 00680 /// 00681 /// \param SS if non-NULL, the nested-name-specifier preceding the 00682 /// template name. 00683 /// 00684 /// \param ConsumeLastToken if true, then we will consume the last 00685 /// token that forms the template-id. Otherwise, we will leave the 00686 /// last token in the stream (e.g., so that it can be replaced with an 00687 /// annotation token). 00688 bool 00689 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, 00690 SourceLocation TemplateNameLoc, 00691 const CXXScopeSpec &SS, 00692 bool ConsumeLastToken, 00693 SourceLocation &LAngleLoc, 00694 TemplateArgList &TemplateArgs, 00695 SourceLocation &RAngleLoc) { 00696 assert(Tok.is(tok::less) && "Must have already parsed the template-name"); 00697 00698 // Consume the '<'. 00699 LAngleLoc = ConsumeToken(); 00700 00701 // Parse the optional template-argument-list. 00702 bool Invalid = false; 00703 { 00704 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); 00705 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) 00706 Invalid = ParseTemplateArgumentList(TemplateArgs); 00707 00708 if (Invalid) { 00709 // Try to find the closing '>'. 00710 SkipUntil(tok::greater, true, !ConsumeLastToken); 00711 00712 return true; 00713 } 00714 } 00715 00716 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) { 00717 Diag(Tok.getLocation(), diag::err_expected_greater); 00718 return true; 00719 } 00720 00721 // Determine the location of the '>' or '>>'. Only consume this 00722 // token if the caller asked us to. 00723 RAngleLoc = Tok.getLocation(); 00724 00725 if (Tok.is(tok::greatergreater)) { 00726 const char *ReplaceStr = "> >"; 00727 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater)) 00728 ReplaceStr = "> > "; 00729 00730 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ? 00731 diag::warn_cxx98_compat_two_right_angle_brackets : 00732 diag::err_two_right_angle_brackets_need_space) 00733 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), 00734 ReplaceStr); 00735 00736 Tok.setKind(tok::greater); 00737 if (!ConsumeLastToken) { 00738 // Since we're not supposed to consume the '>>' token, we need 00739 // to insert a second '>' token after the first. 00740 PP.EnterToken(Tok); 00741 } 00742 } else if (ConsumeLastToken) 00743 ConsumeToken(); 00744 00745 return false; 00746 } 00747 00748 /// \brief Replace the tokens that form a simple-template-id with an 00749 /// annotation token containing the complete template-id. 00750 /// 00751 /// The first token in the stream must be the name of a template that 00752 /// is followed by a '<'. This routine will parse the complete 00753 /// simple-template-id and replace the tokens with a single annotation 00754 /// token with one of two different kinds: if the template-id names a 00755 /// type (and \p AllowTypeAnnotation is true), the annotation token is 00756 /// a type annotation that includes the optional nested-name-specifier 00757 /// (\p SS). Otherwise, the annotation token is a template-id 00758 /// annotation that does not include the optional 00759 /// nested-name-specifier. 00760 /// 00761 /// \param Template the declaration of the template named by the first 00762 /// token (an identifier), as returned from \c Action::isTemplateName(). 00763 /// 00764 /// \param TemplateNameKind the kind of template that \p Template 00765 /// refers to, as returned from \c Action::isTemplateName(). 00766 /// 00767 /// \param SS if non-NULL, the nested-name-specifier that precedes 00768 /// this template name. 00769 /// 00770 /// \param TemplateKWLoc if valid, specifies that this template-id 00771 /// annotation was preceded by the 'template' keyword and gives the 00772 /// location of that keyword. If invalid (the default), then this 00773 /// template-id was not preceded by a 'template' keyword. 00774 /// 00775 /// \param AllowTypeAnnotation if true (the default), then a 00776 /// simple-template-id that refers to a class template, template 00777 /// template parameter, or other template that produces a type will be 00778 /// replaced with a type annotation token. Otherwise, the 00779 /// simple-template-id is always replaced with a template-id 00780 /// annotation token. 00781 /// 00782 /// If an unrecoverable parse error occurs and no annotation token can be 00783 /// formed, this function returns true. 00784 /// 00785 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, 00786 CXXScopeSpec &SS, 00787 SourceLocation TemplateKWLoc, 00788 UnqualifiedId &TemplateName, 00789 bool AllowTypeAnnotation) { 00790 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++"); 00791 assert(Template && Tok.is(tok::less) && 00792 "Parser isn't at the beginning of a template-id"); 00793 00794 // Consume the template-name. 00795 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin(); 00796 00797 // Parse the enclosed template argument list. 00798 SourceLocation LAngleLoc, RAngleLoc; 00799 TemplateArgList TemplateArgs; 00800 bool Invalid = ParseTemplateIdAfterTemplateName(Template, 00801 TemplateNameLoc, 00802 SS, false, LAngleLoc, 00803 TemplateArgs, 00804 RAngleLoc); 00805 00806 if (Invalid) { 00807 // If we failed to parse the template ID but skipped ahead to a >, we're not 00808 // going to be able to form a token annotation. Eat the '>' if present. 00809 if (Tok.is(tok::greater)) 00810 ConsumeToken(); 00811 return true; 00812 } 00813 00814 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(), 00815 TemplateArgs.size()); 00816 00817 // Build the annotation token. 00818 if (TNK == TNK_Type_template && AllowTypeAnnotation) { 00819 TypeResult Type 00820 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc, 00821 Template, TemplateNameLoc, 00822 LAngleLoc, TemplateArgsPtr, RAngleLoc); 00823 if (Type.isInvalid()) { 00824 // If we failed to parse the template ID but skipped ahead to a >, we're not 00825 // going to be able to form a token annotation. Eat the '>' if present. 00826 if (Tok.is(tok::greater)) 00827 ConsumeToken(); 00828 return true; 00829 } 00830 00831 Tok.setKind(tok::annot_typename); 00832 setTypeAnnotation(Tok, Type.get()); 00833 if (SS.isNotEmpty()) 00834 Tok.setLocation(SS.getBeginLoc()); 00835 else if (TemplateKWLoc.isValid()) 00836 Tok.setLocation(TemplateKWLoc); 00837 else 00838 Tok.setLocation(TemplateNameLoc); 00839 } else { 00840 // Build a template-id annotation token that can be processed 00841 // later. 00842 Tok.setKind(tok::annot_template_id); 00843 TemplateIdAnnotation *TemplateId 00844 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds); 00845 TemplateId->TemplateNameLoc = TemplateNameLoc; 00846 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) { 00847 TemplateId->Name = TemplateName.Identifier; 00848 TemplateId->Operator = OO_None; 00849 } else { 00850 TemplateId->Name = 0; 00851 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator; 00852 } 00853 TemplateId->SS = SS; 00854 TemplateId->TemplateKWLoc = TemplateKWLoc; 00855 TemplateId->Template = Template; 00856 TemplateId->Kind = TNK; 00857 TemplateId->LAngleLoc = LAngleLoc; 00858 TemplateId->RAngleLoc = RAngleLoc; 00859 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); 00860 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) 00861 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]); 00862 Tok.setAnnotationValue(TemplateId); 00863 if (TemplateKWLoc.isValid()) 00864 Tok.setLocation(TemplateKWLoc); 00865 else 00866 Tok.setLocation(TemplateNameLoc); 00867 00868 TemplateArgsPtr.release(); 00869 } 00870 00871 // Common fields for the annotation token 00872 Tok.setAnnotationEndLoc(RAngleLoc); 00873 00874 // In case the tokens were cached, have Preprocessor replace them with the 00875 // annotation token. 00876 PP.AnnotateCachedTokens(Tok); 00877 return false; 00878 } 00879 00880 /// \brief Replaces a template-id annotation token with a type 00881 /// annotation token. 00882 /// 00883 /// If there was a failure when forming the type from the template-id, 00884 /// a type annotation token will still be created, but will have a 00885 /// NULL type pointer to signify an error. 00886 void Parser::AnnotateTemplateIdTokenAsType() { 00887 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens"); 00888 00889 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 00890 assert((TemplateId->Kind == TNK_Type_template || 00891 TemplateId->Kind == TNK_Dependent_template_name) && 00892 "Only works for type and dependent templates"); 00893 00894 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 00895 TemplateId->getTemplateArgs(), 00896 TemplateId->NumArgs); 00897 00898 TypeResult Type 00899 = Actions.ActOnTemplateIdType(TemplateId->SS, 00900 TemplateId->TemplateKWLoc, 00901 TemplateId->Template, 00902 TemplateId->TemplateNameLoc, 00903 TemplateId->LAngleLoc, 00904 TemplateArgsPtr, 00905 TemplateId->RAngleLoc); 00906 // Create the new "type" annotation token. 00907 Tok.setKind(tok::annot_typename); 00908 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get()); 00909 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name. 00910 Tok.setLocation(TemplateId->SS.getBeginLoc()); 00911 // End location stays the same 00912 00913 // Replace the template-id annotation token, and possible the scope-specifier 00914 // that precedes it, with the typename annotation token. 00915 PP.AnnotateCachedTokens(Tok); 00916 } 00917 00918 /// \brief Determine whether the given token can end a template argument. 00919 static bool isEndOfTemplateArgument(Token Tok) { 00920 return Tok.is(tok::comma) || Tok.is(tok::greater) || 00921 Tok.is(tok::greatergreater); 00922 } 00923 00924 /// \brief Parse a C++ template template argument. 00925 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { 00926 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) && 00927 !Tok.is(tok::annot_cxxscope)) 00928 return ParsedTemplateArgument(); 00929 00930 // C++0x [temp.arg.template]p1: 00931 // A template-argument for a template template-parameter shall be the name 00932 // of a class template or an alias template, expressed as id-expression. 00933 // 00934 // We parse an id-expression that refers to a class template or alias 00935 // template. The grammar we parse is: 00936 // 00937 // nested-name-specifier[opt] template[opt] identifier ...[opt] 00938 // 00939 // followed by a token that terminates a template argument, such as ',', 00940 // '>', or (in some cases) '>>'. 00941 CXXScopeSpec SS; // nested-name-specifier, if present 00942 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 00943 /*EnteringContext=*/false); 00944 00945 ParsedTemplateArgument Result; 00946 SourceLocation EllipsisLoc; 00947 if (SS.isSet() && Tok.is(tok::kw_template)) { 00948 // Parse the optional 'template' keyword following the 00949 // nested-name-specifier. 00950 SourceLocation TemplateKWLoc = ConsumeToken(); 00951 00952 if (Tok.is(tok::identifier)) { 00953 // We appear to have a dependent template name. 00954 UnqualifiedId Name; 00955 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 00956 ConsumeToken(); // the identifier 00957 00958 // Parse the ellipsis. 00959 if (Tok.is(tok::ellipsis)) 00960 EllipsisLoc = ConsumeToken(); 00961 00962 // If the next token signals the end of a template argument, 00963 // then we have a dependent template name that could be a template 00964 // template argument. 00965 TemplateTy Template; 00966 if (isEndOfTemplateArgument(Tok) && 00967 Actions.ActOnDependentTemplateName(getCurScope(), 00968 SS, TemplateKWLoc, Name, 00969 /*ObjectType=*/ ParsedType(), 00970 /*EnteringContext=*/false, 00971 Template)) 00972 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); 00973 } 00974 } else if (Tok.is(tok::identifier)) { 00975 // We may have a (non-dependent) template name. 00976 TemplateTy Template; 00977 UnqualifiedId Name; 00978 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 00979 ConsumeToken(); // the identifier 00980 00981 // Parse the ellipsis. 00982 if (Tok.is(tok::ellipsis)) 00983 EllipsisLoc = ConsumeToken(); 00984 00985 if (isEndOfTemplateArgument(Tok)) { 00986 bool MemberOfUnknownSpecialization; 00987 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, 00988 /*hasTemplateKeyword=*/false, 00989 Name, 00990 /*ObjectType=*/ ParsedType(), 00991 /*EnteringContext=*/false, 00992 Template, 00993 MemberOfUnknownSpecialization); 00994 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) { 00995 // We have an id-expression that refers to a class template or 00996 // (C++0x) alias template. 00997 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); 00998 } 00999 } 01000 } 01001 01002 // If this is a pack expansion, build it as such. 01003 if (EllipsisLoc.isValid() && !Result.isInvalid()) 01004 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc); 01005 01006 return Result; 01007 } 01008 01009 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]). 01010 /// 01011 /// template-argument: [C++ 14.2] 01012 /// constant-expression 01013 /// type-id 01014 /// id-expression 01015 ParsedTemplateArgument Parser::ParseTemplateArgument() { 01016 // C++ [temp.arg]p2: 01017 // In a template-argument, an ambiguity between a type-id and an 01018 // expression is resolved to a type-id, regardless of the form of 01019 // the corresponding template-parameter. 01020 // 01021 // Therefore, we initially try to parse a type-id. 01022 if (isCXXTypeId(TypeIdAsTemplateArgument)) { 01023 SourceLocation Loc = Tok.getLocation(); 01024 TypeResult TypeArg = ParseTypeName(/*Range=*/0, 01025 Declarator::TemplateTypeArgContext); 01026 if (TypeArg.isInvalid()) 01027 return ParsedTemplateArgument(); 01028 01029 return ParsedTemplateArgument(ParsedTemplateArgument::Type, 01030 TypeArg.get().getAsOpaquePtr(), 01031 Loc); 01032 } 01033 01034 // Try to parse a template template argument. 01035 { 01036 TentativeParsingAction TPA(*this); 01037 01038 ParsedTemplateArgument TemplateTemplateArgument 01039 = ParseTemplateTemplateArgument(); 01040 if (!TemplateTemplateArgument.isInvalid()) { 01041 TPA.Commit(); 01042 return TemplateTemplateArgument; 01043 } 01044 01045 // Revert this tentative parse to parse a non-type template argument. 01046 TPA.Revert(); 01047 } 01048 01049 // Parse a non-type template argument. 01050 SourceLocation Loc = Tok.getLocation(); 01051 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast); 01052 if (ExprArg.isInvalid() || !ExprArg.get()) 01053 return ParsedTemplateArgument(); 01054 01055 return ParsedTemplateArgument(ParsedTemplateArgument::NonType, 01056 ExprArg.release(), Loc); 01057 } 01058 01059 /// \brief Determine whether the current tokens can only be parsed as a 01060 /// template argument list (starting with the '<') and never as a '<' 01061 /// expression. 01062 bool Parser::IsTemplateArgumentList(unsigned Skip) { 01063 struct AlwaysRevertAction : TentativeParsingAction { 01064 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { } 01065 ~AlwaysRevertAction() { Revert(); } 01066 } Tentative(*this); 01067 01068 while (Skip) { 01069 ConsumeToken(); 01070 --Skip; 01071 } 01072 01073 // '<' 01074 if (!Tok.is(tok::less)) 01075 return false; 01076 ConsumeToken(); 01077 01078 // An empty template argument list. 01079 if (Tok.is(tok::greater)) 01080 return true; 01081 01082 // See whether we have declaration specifiers, which indicate a type. 01083 while (isCXXDeclarationSpecifier() == TPResult::True()) 01084 ConsumeToken(); 01085 01086 // If we have a '>' or a ',' then this is a template argument list. 01087 return Tok.is(tok::greater) || Tok.is(tok::comma); 01088 } 01089 01090 /// ParseTemplateArgumentList - Parse a C++ template-argument-list 01091 /// (C++ [temp.names]). Returns true if there was an error. 01092 /// 01093 /// template-argument-list: [C++ 14.2] 01094 /// template-argument 01095 /// template-argument-list ',' template-argument 01096 bool 01097 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { 01098 while (true) { 01099 ParsedTemplateArgument Arg = ParseTemplateArgument(); 01100 if (Tok.is(tok::ellipsis)) { 01101 SourceLocation EllipsisLoc = ConsumeToken(); 01102 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc); 01103 } 01104 01105 if (Arg.isInvalid()) { 01106 SkipUntil(tok::comma, tok::greater, true, true); 01107 return true; 01108 } 01109 01110 // Save this template argument. 01111 TemplateArgs.push_back(Arg); 01112 01113 // If the next token is a comma, consume it and keep reading 01114 // arguments. 01115 if (Tok.isNot(tok::comma)) break; 01116 01117 // Consume the comma. 01118 ConsumeToken(); 01119 } 01120 01121 return false; 01122 } 01123 01124 /// \brief Parse a C++ explicit template instantiation 01125 /// (C++ [temp.explicit]). 01126 /// 01127 /// explicit-instantiation: 01128 /// 'extern' [opt] 'template' declaration 01129 /// 01130 /// Note that the 'extern' is a GNU extension and C++0x feature. 01131 Decl *Parser::ParseExplicitInstantiation(unsigned Context, 01132 SourceLocation ExternLoc, 01133 SourceLocation TemplateLoc, 01134 SourceLocation &DeclEnd, 01135 AccessSpecifier AS) { 01136 // This isn't really required here. 01137 ParsingDeclRAIIObject 01138 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); 01139 01140 return ParseSingleDeclarationAfterTemplate(Context, 01141 ParsedTemplateInfo(ExternLoc, 01142 TemplateLoc), 01143 ParsingTemplateParams, 01144 DeclEnd, AS); 01145 } 01146 01147 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const { 01148 if (TemplateParams) 01149 return getTemplateParamsRange(TemplateParams->data(), 01150 TemplateParams->size()); 01151 01152 SourceRange R(TemplateLoc); 01153 if (ExternLoc.isValid()) 01154 R.setBegin(ExternLoc); 01155 return R; 01156 } 01157 01158 void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) { 01159 ((Parser*)P)->LateTemplateParser(FD); 01160 } 01161 01162 01163 void Parser::LateTemplateParser(const FunctionDecl *FD) { 01164 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD]; 01165 if (LPT) { 01166 ParseLateTemplatedFuncDef(*LPT); 01167 return; 01168 } 01169 01170 llvm_unreachable("Late templated function without associated lexed tokens"); 01171 } 01172 01173 /// \brief Late parse a C++ function template in Microsoft mode. 01174 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) { 01175 if(!LMT.D) 01176 return; 01177 01178 // Get the FunctionDecl. 01179 FunctionDecl *FD = 0; 01180 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D)) 01181 FD = FunTmpl->getTemplatedDecl(); 01182 else 01183 FD = cast<FunctionDecl>(LMT.D); 01184 01185 // To restore the context after late parsing. 01186 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext); 01187 01188 SmallVector<ParseScope*, 4> TemplateParamScopeStack; 01189 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD); 01190 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) { 01191 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope)); 01192 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator); 01193 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D); 01194 } else { 01195 // Get the list of DeclContext to reenter. 01196 SmallVector<DeclContext*, 4> DeclContextToReenter; 01197 DeclContext *DD = FD->getLexicalParent(); 01198 while (DD && !DD->isTranslationUnit()) { 01199 DeclContextToReenter.push_back(DD); 01200 DD = DD->getLexicalParent(); 01201 } 01202 01203 // Reenter template scopes from outmost to innermost. 01204 SmallVector<DeclContext*, 4>::reverse_iterator II = 01205 DeclContextToReenter.rbegin(); 01206 for (; II != DeclContextToReenter.rend(); ++II) { 01207 if (ClassTemplatePartialSpecializationDecl* MD = 01208 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) { 01209 TemplateParamScopeStack.push_back(new ParseScope(this, 01210 Scope::TemplateParamScope)); 01211 Actions.ActOnReenterTemplateScope(getCurScope(), MD); 01212 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) { 01213 TemplateParamScopeStack.push_back(new ParseScope(this, 01214 Scope::TemplateParamScope, 01215 MD->getDescribedClassTemplate() != 0 )); 01216 Actions.ActOnReenterTemplateScope(getCurScope(), 01217 MD->getDescribedClassTemplate()); 01218 } 01219 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope)); 01220 Actions.PushDeclContext(Actions.getCurScope(), *II); 01221 } 01222 TemplateParamScopeStack.push_back(new ParseScope(this, 01223 Scope::TemplateParamScope)); 01224 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D); 01225 } 01226 01227 assert(!LMT.Toks.empty() && "Empty body!"); 01228 01229 // Append the current token at the end of the new token stream so that it 01230 // doesn't get lost. 01231 LMT.Toks.push_back(Tok); 01232 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false); 01233 01234 // Consume the previously pushed token. 01235 ConsumeAnyToken(); 01236 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) 01237 && "Inline method not starting with '{', ':' or 'try'"); 01238 01239 // Parse the method body. Function body parsing code is similar enough 01240 // to be re-used for method bodies as well. 01241 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope); 01242 01243 // Recreate the containing function DeclContext. 01244 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD)); 01245 01246 if (FunctionTemplateDecl *FunctionTemplate 01247 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D)) 01248 Actions.ActOnStartOfFunctionDef(getCurScope(), 01249 FunctionTemplate->getTemplatedDecl()); 01250 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D)) 01251 Actions.ActOnStartOfFunctionDef(getCurScope(), Function); 01252 01253 01254 if (Tok.is(tok::kw_try)) { 01255 ParseFunctionTryBlock(LMT.D, FnScope); 01256 } else { 01257 if (Tok.is(tok::colon)) 01258 ParseConstructorInitializer(LMT.D); 01259 else 01260 Actions.ActOnDefaultCtorInitializers(LMT.D); 01261 01262 if (Tok.is(tok::l_brace)) { 01263 ParseFunctionStatementBody(LMT.D, FnScope); 01264 Actions.MarkAsLateParsedTemplate(FD, false); 01265 } else 01266 Actions.ActOnFinishFunctionBody(LMT.D, 0); 01267 } 01268 01269 // Exit scopes. 01270 FnScope.Exit(); 01271 SmallVector<ParseScope*, 4>::reverse_iterator I = 01272 TemplateParamScopeStack.rbegin(); 01273 for (; I != TemplateParamScopeStack.rend(); ++I) 01274 delete *I; 01275 01276 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D); 01277 if (grp) 01278 Actions.getASTConsumer().HandleTopLevelDecl(grp.get()); 01279 } 01280 01281 /// \brief Lex a delayed template function for late parsing. 01282 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) { 01283 tok::TokenKind kind = Tok.getKind(); 01284 if (!ConsumeAndStoreFunctionPrologue(Toks)) { 01285 // Consume everything up to (and including) the matching right brace. 01286 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 01287 } 01288 01289 // If we're in a function-try-block, we need to store all the catch blocks. 01290 if (kind == tok::kw_try) { 01291 while (Tok.is(tok::kw_catch)) { 01292 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); 01293 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 01294 } 01295 } 01296 }