clang API Documentation
00001 //===--- ParseDeclCXX.cpp - C++ Declaration 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 the C++ Declaration portions of the Parser interfaces. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Basic/OperatorKinds.h" 00015 #include "clang/Parse/Parser.h" 00016 #include "clang/Parse/ParseDiagnostic.h" 00017 #include "clang/Sema/DeclSpec.h" 00018 #include "clang/Sema/Scope.h" 00019 #include "clang/Sema/ParsedTemplate.h" 00020 #include "clang/Sema/PrettyDeclStackTrace.h" 00021 #include "llvm/ADT/SmallString.h" 00022 #include "RAIIObjectsForParser.h" 00023 using namespace clang; 00024 00025 /// ParseNamespace - We know that the current token is a namespace keyword. This 00026 /// may either be a top level namespace or a block-level namespace alias. If 00027 /// there was an inline keyword, it has already been parsed. 00028 /// 00029 /// namespace-definition: [C++ 7.3: basic.namespace] 00030 /// named-namespace-definition 00031 /// unnamed-namespace-definition 00032 /// 00033 /// unnamed-namespace-definition: 00034 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}' 00035 /// 00036 /// named-namespace-definition: 00037 /// original-namespace-definition 00038 /// extension-namespace-definition 00039 /// 00040 /// original-namespace-definition: 00041 /// 'inline'[opt] 'namespace' identifier attributes[opt] 00042 /// '{' namespace-body '}' 00043 /// 00044 /// extension-namespace-definition: 00045 /// 'inline'[opt] 'namespace' original-namespace-name 00046 /// '{' namespace-body '}' 00047 /// 00048 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias] 00049 /// 'namespace' identifier '=' qualified-namespace-specifier ';' 00050 /// 00051 Decl *Parser::ParseNamespace(unsigned Context, 00052 SourceLocation &DeclEnd, 00053 SourceLocation InlineLoc) { 00054 assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); 00055 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. 00056 ObjCDeclContextSwitch ObjCDC(*this); 00057 00058 if (Tok.is(tok::code_completion)) { 00059 Actions.CodeCompleteNamespaceDecl(getCurScope()); 00060 cutOffParsing(); 00061 return 0; 00062 } 00063 00064 SourceLocation IdentLoc; 00065 IdentifierInfo *Ident = 0; 00066 std::vector<SourceLocation> ExtraIdentLoc; 00067 std::vector<IdentifierInfo*> ExtraIdent; 00068 std::vector<SourceLocation> ExtraNamespaceLoc; 00069 00070 Token attrTok; 00071 00072 if (Tok.is(tok::identifier)) { 00073 Ident = Tok.getIdentifierInfo(); 00074 IdentLoc = ConsumeToken(); // eat the identifier. 00075 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) { 00076 ExtraNamespaceLoc.push_back(ConsumeToken()); 00077 ExtraIdent.push_back(Tok.getIdentifierInfo()); 00078 ExtraIdentLoc.push_back(ConsumeToken()); 00079 } 00080 } 00081 00082 // Read label attributes, if present. 00083 ParsedAttributes attrs(AttrFactory); 00084 if (Tok.is(tok::kw___attribute)) { 00085 attrTok = Tok; 00086 ParseGNUAttributes(attrs); 00087 } 00088 00089 if (Tok.is(tok::equal)) { 00090 if (!attrs.empty()) 00091 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias); 00092 if (InlineLoc.isValid()) 00093 Diag(InlineLoc, diag::err_inline_namespace_alias) 00094 << FixItHint::CreateRemoval(InlineLoc); 00095 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); 00096 } 00097 00098 00099 BalancedDelimiterTracker T(*this, tok::l_brace); 00100 if (T.consumeOpen()) { 00101 if (!ExtraIdent.empty()) { 00102 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 00103 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 00104 } 00105 Diag(Tok, Ident ? diag::err_expected_lbrace : 00106 diag::err_expected_ident_lbrace); 00107 return 0; 00108 } 00109 00110 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || 00111 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || 00112 getCurScope()->getFnParent()) { 00113 if (!ExtraIdent.empty()) { 00114 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 00115 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 00116 } 00117 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope); 00118 SkipUntil(tok::r_brace, false); 00119 return 0; 00120 } 00121 00122 if (!ExtraIdent.empty()) { 00123 TentativeParsingAction TPA(*this); 00124 SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true); 00125 Token rBraceToken = Tok; 00126 TPA.Revert(); 00127 00128 if (!rBraceToken.is(tok::r_brace)) { 00129 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 00130 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 00131 } else { 00132 std::string NamespaceFix; 00133 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(), 00134 E = ExtraIdent.end(); I != E; ++I) { 00135 NamespaceFix += " { namespace "; 00136 NamespaceFix += (*I)->getName(); 00137 } 00138 00139 std::string RBraces; 00140 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i) 00141 RBraces += "} "; 00142 00143 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 00144 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(), 00145 ExtraIdentLoc.back()), 00146 NamespaceFix) 00147 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces); 00148 } 00149 } 00150 00151 // If we're still good, complain about inline namespaces in non-C++0x now. 00152 if (InlineLoc.isValid()) 00153 Diag(InlineLoc, getLangOpts().CPlusPlus0x ? 00154 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace); 00155 00156 // Enter a scope for the namespace. 00157 ParseScope NamespaceScope(this, Scope::DeclScope); 00158 00159 Decl *NamespcDecl = 00160 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc, 00161 IdentLoc, Ident, T.getOpenLocation(), 00162 attrs.getList()); 00163 00164 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc, 00165 "parsing namespace"); 00166 00167 // Parse the contents of the namespace. This includes parsing recovery on 00168 // any improperly nested namespaces. 00169 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0, 00170 InlineLoc, attrs, T); 00171 00172 // Leave the namespace scope. 00173 NamespaceScope.Exit(); 00174 00175 DeclEnd = T.getCloseLocation(); 00176 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd); 00177 00178 return NamespcDecl; 00179 } 00180 00181 /// ParseInnerNamespace - Parse the contents of a namespace. 00182 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc, 00183 std::vector<IdentifierInfo*>& Ident, 00184 std::vector<SourceLocation>& NamespaceLoc, 00185 unsigned int index, SourceLocation& InlineLoc, 00186 ParsedAttributes& attrs, 00187 BalancedDelimiterTracker &Tracker) { 00188 if (index == Ident.size()) { 00189 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 00190 ParsedAttributesWithRange attrs(AttrFactory); 00191 MaybeParseCXX0XAttributes(attrs); 00192 MaybeParseMicrosoftAttributes(attrs); 00193 ParseExternalDeclaration(attrs); 00194 } 00195 00196 // The caller is what called check -- we are simply calling 00197 // the close for it. 00198 Tracker.consumeClose(); 00199 00200 return; 00201 } 00202 00203 // Parse improperly nested namespaces. 00204 ParseScope NamespaceScope(this, Scope::DeclScope); 00205 Decl *NamespcDecl = 00206 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(), 00207 NamespaceLoc[index], IdentLoc[index], 00208 Ident[index], Tracker.getOpenLocation(), 00209 attrs.getList()); 00210 00211 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc, 00212 attrs, Tracker); 00213 00214 NamespaceScope.Exit(); 00215 00216 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation()); 00217 } 00218 00219 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace 00220 /// alias definition. 00221 /// 00222 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, 00223 SourceLocation AliasLoc, 00224 IdentifierInfo *Alias, 00225 SourceLocation &DeclEnd) { 00226 assert(Tok.is(tok::equal) && "Not equal token"); 00227 00228 ConsumeToken(); // eat the '='. 00229 00230 if (Tok.is(tok::code_completion)) { 00231 Actions.CodeCompleteNamespaceAliasDecl(getCurScope()); 00232 cutOffParsing(); 00233 return 0; 00234 } 00235 00236 CXXScopeSpec SS; 00237 // Parse (optional) nested-name-specifier. 00238 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 00239 00240 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 00241 Diag(Tok, diag::err_expected_namespace_name); 00242 // Skip to end of the definition and eat the ';'. 00243 SkipUntil(tok::semi); 00244 return 0; 00245 } 00246 00247 // Parse identifier. 00248 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 00249 SourceLocation IdentLoc = ConsumeToken(); 00250 00251 // Eat the ';'. 00252 DeclEnd = Tok.getLocation(); 00253 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name, 00254 "", tok::semi); 00255 00256 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias, 00257 SS, IdentLoc, Ident); 00258 } 00259 00260 /// ParseLinkage - We know that the current token is a string_literal 00261 /// and just before that, that extern was seen. 00262 /// 00263 /// linkage-specification: [C++ 7.5p2: dcl.link] 00264 /// 'extern' string-literal '{' declaration-seq[opt] '}' 00265 /// 'extern' string-literal declaration 00266 /// 00267 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) { 00268 assert(Tok.is(tok::string_literal) && "Not a string literal!"); 00269 SmallString<8> LangBuffer; 00270 bool Invalid = false; 00271 StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid); 00272 if (Invalid) 00273 return 0; 00274 00275 // FIXME: This is incorrect: linkage-specifiers are parsed in translation 00276 // phase 7, so string-literal concatenation is supposed to occur. 00277 // extern "" "C" "" "+" "+" { } is legal. 00278 if (Tok.hasUDSuffix()) 00279 Diag(Tok, diag::err_invalid_string_udl); 00280 SourceLocation Loc = ConsumeStringToken(); 00281 00282 ParseScope LinkageScope(this, Scope::DeclScope); 00283 Decl *LinkageSpec 00284 = Actions.ActOnStartLinkageSpecification(getCurScope(), 00285 DS.getSourceRange().getBegin(), 00286 Loc, Lang, 00287 Tok.is(tok::l_brace) ? Tok.getLocation() 00288 : SourceLocation()); 00289 00290 ParsedAttributesWithRange attrs(AttrFactory); 00291 MaybeParseCXX0XAttributes(attrs); 00292 MaybeParseMicrosoftAttributes(attrs); 00293 00294 if (Tok.isNot(tok::l_brace)) { 00295 // Reset the source range in DS, as the leading "extern" 00296 // does not really belong to the inner declaration ... 00297 DS.SetRangeStart(SourceLocation()); 00298 DS.SetRangeEnd(SourceLocation()); 00299 // ... but anyway remember that such an "extern" was seen. 00300 DS.setExternInLinkageSpec(true); 00301 ParseExternalDeclaration(attrs, &DS); 00302 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 00303 SourceLocation()); 00304 } 00305 00306 DS.abort(); 00307 00308 ProhibitAttributes(attrs); 00309 00310 BalancedDelimiterTracker T(*this, tok::l_brace); 00311 T.consumeOpen(); 00312 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 00313 ParsedAttributesWithRange attrs(AttrFactory); 00314 MaybeParseCXX0XAttributes(attrs); 00315 MaybeParseMicrosoftAttributes(attrs); 00316 ParseExternalDeclaration(attrs); 00317 } 00318 00319 T.consumeClose(); 00320 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 00321 T.getCloseLocation()); 00322 } 00323 00324 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or 00325 /// using-directive. Assumes that current token is 'using'. 00326 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context, 00327 const ParsedTemplateInfo &TemplateInfo, 00328 SourceLocation &DeclEnd, 00329 ParsedAttributesWithRange &attrs, 00330 Decl **OwnedType) { 00331 assert(Tok.is(tok::kw_using) && "Not using token"); 00332 ObjCDeclContextSwitch ObjCDC(*this); 00333 00334 // Eat 'using'. 00335 SourceLocation UsingLoc = ConsumeToken(); 00336 00337 if (Tok.is(tok::code_completion)) { 00338 Actions.CodeCompleteUsing(getCurScope()); 00339 cutOffParsing(); 00340 return 0; 00341 } 00342 00343 // 'using namespace' means this is a using-directive. 00344 if (Tok.is(tok::kw_namespace)) { 00345 // Template parameters are always an error here. 00346 if (TemplateInfo.Kind) { 00347 SourceRange R = TemplateInfo.getSourceRange(); 00348 Diag(UsingLoc, diag::err_templated_using_directive) 00349 << R << FixItHint::CreateRemoval(R); 00350 } 00351 00352 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs); 00353 } 00354 00355 // Otherwise, it must be a using-declaration or an alias-declaration. 00356 00357 // Using declarations can't have attributes. 00358 ProhibitAttributes(attrs); 00359 00360 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd, 00361 AS_none, OwnedType); 00362 } 00363 00364 /// ParseUsingDirective - Parse C++ using-directive, assumes 00365 /// that current token is 'namespace' and 'using' was already parsed. 00366 /// 00367 /// using-directive: [C++ 7.3.p4: namespace.udir] 00368 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 00369 /// namespace-name ; 00370 /// [GNU] using-directive: 00371 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 00372 /// namespace-name attributes[opt] ; 00373 /// 00374 Decl *Parser::ParseUsingDirective(unsigned Context, 00375 SourceLocation UsingLoc, 00376 SourceLocation &DeclEnd, 00377 ParsedAttributes &attrs) { 00378 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token"); 00379 00380 // Eat 'namespace'. 00381 SourceLocation NamespcLoc = ConsumeToken(); 00382 00383 if (Tok.is(tok::code_completion)) { 00384 Actions.CodeCompleteUsingDirective(getCurScope()); 00385 cutOffParsing(); 00386 return 0; 00387 } 00388 00389 CXXScopeSpec SS; 00390 // Parse (optional) nested-name-specifier. 00391 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 00392 00393 IdentifierInfo *NamespcName = 0; 00394 SourceLocation IdentLoc = SourceLocation(); 00395 00396 // Parse namespace-name. 00397 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 00398 Diag(Tok, diag::err_expected_namespace_name); 00399 // If there was invalid namespace name, skip to end of decl, and eat ';'. 00400 SkipUntil(tok::semi); 00401 // FIXME: Are there cases, when we would like to call ActOnUsingDirective? 00402 return 0; 00403 } 00404 00405 // Parse identifier. 00406 NamespcName = Tok.getIdentifierInfo(); 00407 IdentLoc = ConsumeToken(); 00408 00409 // Parse (optional) attributes (most likely GNU strong-using extension). 00410 bool GNUAttr = false; 00411 if (Tok.is(tok::kw___attribute)) { 00412 GNUAttr = true; 00413 ParseGNUAttributes(attrs); 00414 } 00415 00416 // Eat ';'. 00417 DeclEnd = Tok.getLocation(); 00418 ExpectAndConsume(tok::semi, 00419 GNUAttr ? diag::err_expected_semi_after_attribute_list 00420 : diag::err_expected_semi_after_namespace_name, 00421 "", tok::semi); 00422 00423 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS, 00424 IdentLoc, NamespcName, attrs.getList()); 00425 } 00426 00427 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration. 00428 /// Assumes that 'using' was already seen. 00429 /// 00430 /// using-declaration: [C++ 7.3.p3: namespace.udecl] 00431 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier 00432 /// unqualified-id 00433 /// 'using' :: unqualified-id 00434 /// 00435 /// alias-declaration: C++0x [decl.typedef]p2 00436 /// 'using' identifier = type-id ; 00437 /// 00438 Decl *Parser::ParseUsingDeclaration(unsigned Context, 00439 const ParsedTemplateInfo &TemplateInfo, 00440 SourceLocation UsingLoc, 00441 SourceLocation &DeclEnd, 00442 AccessSpecifier AS, 00443 Decl **OwnedType) { 00444 CXXScopeSpec SS; 00445 SourceLocation TypenameLoc; 00446 bool IsTypeName; 00447 00448 // Ignore optional 'typename'. 00449 // FIXME: This is wrong; we should parse this as a typename-specifier. 00450 if (Tok.is(tok::kw_typename)) { 00451 TypenameLoc = Tok.getLocation(); 00452 ConsumeToken(); 00453 IsTypeName = true; 00454 } 00455 else 00456 IsTypeName = false; 00457 00458 // Parse nested-name-specifier. 00459 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 00460 00461 // Check nested-name specifier. 00462 if (SS.isInvalid()) { 00463 SkipUntil(tok::semi); 00464 return 0; 00465 } 00466 00467 // Parse the unqualified-id. We allow parsing of both constructor and 00468 // destructor names and allow the action module to diagnose any semantic 00469 // errors. 00470 SourceLocation TemplateKWLoc; 00471 UnqualifiedId Name; 00472 if (ParseUnqualifiedId(SS, 00473 /*EnteringContext=*/false, 00474 /*AllowDestructorName=*/true, 00475 /*AllowConstructorName=*/true, 00476 ParsedType(), 00477 TemplateKWLoc, 00478 Name)) { 00479 SkipUntil(tok::semi); 00480 return 0; 00481 } 00482 00483 ParsedAttributes attrs(AttrFactory); 00484 00485 // Maybe this is an alias-declaration. 00486 bool IsAliasDecl = Tok.is(tok::equal); 00487 TypeResult TypeAlias; 00488 if (IsAliasDecl) { 00489 // TODO: Attribute support. C++0x attributes may appear before the equals. 00490 // Where can GNU attributes appear? 00491 ConsumeToken(); 00492 00493 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ? 00494 diag::warn_cxx98_compat_alias_declaration : 00495 diag::ext_alias_declaration); 00496 00497 // Type alias templates cannot be specialized. 00498 int SpecKind = -1; 00499 if (TemplateInfo.Kind == ParsedTemplateInfo::Template && 00500 Name.getKind() == UnqualifiedId::IK_TemplateId) 00501 SpecKind = 0; 00502 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) 00503 SpecKind = 1; 00504 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 00505 SpecKind = 2; 00506 if (SpecKind != -1) { 00507 SourceRange Range; 00508 if (SpecKind == 0) 00509 Range = SourceRange(Name.TemplateId->LAngleLoc, 00510 Name.TemplateId->RAngleLoc); 00511 else 00512 Range = TemplateInfo.getSourceRange(); 00513 Diag(Range.getBegin(), diag::err_alias_declaration_specialization) 00514 << SpecKind << Range; 00515 SkipUntil(tok::semi); 00516 return 0; 00517 } 00518 00519 // Name must be an identifier. 00520 if (Name.getKind() != UnqualifiedId::IK_Identifier) { 00521 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier); 00522 // No removal fixit: can't recover from this. 00523 SkipUntil(tok::semi); 00524 return 0; 00525 } else if (IsTypeName) 00526 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier) 00527 << FixItHint::CreateRemoval(SourceRange(TypenameLoc, 00528 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc)); 00529 else if (SS.isNotEmpty()) 00530 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier) 00531 << FixItHint::CreateRemoval(SS.getRange()); 00532 00533 TypeAlias = ParseTypeName(0, TemplateInfo.Kind ? 00534 Declarator::AliasTemplateContext : 00535 Declarator::AliasDeclContext, AS, OwnedType); 00536 } else 00537 // Parse (optional) attributes (most likely GNU strong-using extension). 00538 MaybeParseGNUAttributes(attrs); 00539 00540 // Eat ';'. 00541 DeclEnd = Tok.getLocation(); 00542 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 00543 !attrs.empty() ? "attributes list" : 00544 IsAliasDecl ? "alias declaration" : "using declaration", 00545 tok::semi); 00546 00547 // Diagnose an attempt to declare a templated using-declaration. 00548 // In C++0x, alias-declarations can be templates: 00549 // template <...> using id = type; 00550 if (TemplateInfo.Kind && !IsAliasDecl) { 00551 SourceRange R = TemplateInfo.getSourceRange(); 00552 Diag(UsingLoc, diag::err_templated_using_declaration) 00553 << R << FixItHint::CreateRemoval(R); 00554 00555 // Unfortunately, we have to bail out instead of recovering by 00556 // ignoring the parameters, just in case the nested name specifier 00557 // depends on the parameters. 00558 return 0; 00559 } 00560 00561 // "typename" keyword is allowed for identifiers only, 00562 // because it may be a type definition. 00563 if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) { 00564 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only) 00565 << FixItHint::CreateRemoval(SourceRange(TypenameLoc)); 00566 // Proceed parsing, but reset the IsTypeName flag. 00567 IsTypeName = false; 00568 } 00569 00570 if (IsAliasDecl) { 00571 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 00572 MultiTemplateParamsArg TemplateParamsArg(Actions, 00573 TemplateParams ? TemplateParams->data() : 0, 00574 TemplateParams ? TemplateParams->size() : 0); 00575 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg, 00576 UsingLoc, Name, TypeAlias); 00577 } 00578 00579 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS, 00580 Name, attrs.getList(), 00581 IsTypeName, TypenameLoc); 00582 } 00583 00584 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration. 00585 /// 00586 /// [C++0x] static_assert-declaration: 00587 /// static_assert ( constant-expression , string-literal ) ; 00588 /// 00589 /// [C11] static_assert-declaration: 00590 /// _Static_assert ( constant-expression , string-literal ) ; 00591 /// 00592 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ 00593 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) && 00594 "Not a static_assert declaration"); 00595 00596 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11) 00597 Diag(Tok, diag::ext_c11_static_assert); 00598 if (Tok.is(tok::kw_static_assert)) 00599 Diag(Tok, diag::warn_cxx98_compat_static_assert); 00600 00601 SourceLocation StaticAssertLoc = ConsumeToken(); 00602 00603 BalancedDelimiterTracker T(*this, tok::l_paren); 00604 if (T.consumeOpen()) { 00605 Diag(Tok, diag::err_expected_lparen); 00606 return 0; 00607 } 00608 00609 ExprResult AssertExpr(ParseConstantExpression()); 00610 if (AssertExpr.isInvalid()) { 00611 SkipUntil(tok::semi); 00612 return 0; 00613 } 00614 00615 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi)) 00616 return 0; 00617 00618 if (!isTokenStringLiteral()) { 00619 Diag(Tok, diag::err_expected_string_literal); 00620 SkipUntil(tok::semi); 00621 return 0; 00622 } 00623 00624 ExprResult AssertMessage(ParseStringLiteralExpression()); 00625 if (AssertMessage.isInvalid()) { 00626 SkipUntil(tok::semi); 00627 return 0; 00628 } 00629 00630 T.consumeClose(); 00631 00632 DeclEnd = Tok.getLocation(); 00633 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert); 00634 00635 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, 00636 AssertExpr.take(), 00637 AssertMessage.take(), 00638 T.getCloseLocation()); 00639 } 00640 00641 /// ParseDecltypeSpecifier - Parse a C++0x decltype specifier. 00642 /// 00643 /// 'decltype' ( expression ) 00644 /// 00645 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { 00646 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) 00647 && "Not a decltype specifier"); 00648 00649 00650 ExprResult Result; 00651 SourceLocation StartLoc = Tok.getLocation(); 00652 SourceLocation EndLoc; 00653 00654 if (Tok.is(tok::annot_decltype)) { 00655 Result = getExprAnnotation(Tok); 00656 EndLoc = Tok.getAnnotationEndLoc(); 00657 ConsumeToken(); 00658 if (Result.isInvalid()) { 00659 DS.SetTypeSpecError(); 00660 return EndLoc; 00661 } 00662 } else { 00663 if (Tok.getIdentifierInfo()->isStr("decltype")) 00664 Diag(Tok, diag::warn_cxx98_compat_decltype); 00665 00666 ConsumeToken(); 00667 00668 BalancedDelimiterTracker T(*this, tok::l_paren); 00669 if (T.expectAndConsume(diag::err_expected_lparen_after, 00670 "decltype", tok::r_paren)) { 00671 DS.SetTypeSpecError(); 00672 return T.getOpenLocation() == Tok.getLocation() ? 00673 StartLoc : T.getOpenLocation(); 00674 } 00675 00676 // Parse the expression 00677 00678 // C++0x [dcl.type.simple]p4: 00679 // The operand of the decltype specifier is an unevaluated operand. 00680 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 00681 0, /*IsDecltype=*/true); 00682 Result = ParseExpression(); 00683 if (Result.isInvalid()) { 00684 SkipUntil(tok::r_paren); 00685 DS.SetTypeSpecError(); 00686 return StartLoc; 00687 } 00688 00689 // Match the ')' 00690 T.consumeClose(); 00691 if (T.getCloseLocation().isInvalid()) { 00692 DS.SetTypeSpecError(); 00693 // FIXME: this should return the location of the last token 00694 // that was consumed (by "consumeClose()") 00695 return T.getCloseLocation(); 00696 } 00697 00698 Result = Actions.ActOnDecltypeExpression(Result.take()); 00699 if (Result.isInvalid()) { 00700 DS.SetTypeSpecError(); 00701 return T.getCloseLocation(); 00702 } 00703 00704 EndLoc = T.getCloseLocation(); 00705 } 00706 00707 const char *PrevSpec = 0; 00708 unsigned DiagID; 00709 // Check for duplicate type specifiers (e.g. "int decltype(a)"). 00710 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, 00711 DiagID, Result.release())) { 00712 Diag(StartLoc, DiagID) << PrevSpec; 00713 DS.SetTypeSpecError(); 00714 } 00715 return EndLoc; 00716 } 00717 00718 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, 00719 SourceLocation StartLoc, 00720 SourceLocation EndLoc) { 00721 // make sure we have a token we can turn into an annotation token 00722 if (PP.isBacktrackEnabled()) 00723 PP.RevertCachedTokens(1); 00724 else 00725 PP.EnterToken(Tok); 00726 00727 Tok.setKind(tok::annot_decltype); 00728 setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ? 00729 DS.getRepAsExpr() : ExprResult()); 00730 Tok.setAnnotationEndLoc(EndLoc); 00731 Tok.setLocation(StartLoc); 00732 PP.AnnotateCachedTokens(Tok); 00733 } 00734 00735 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) { 00736 assert(Tok.is(tok::kw___underlying_type) && 00737 "Not an underlying type specifier"); 00738 00739 SourceLocation StartLoc = ConsumeToken(); 00740 BalancedDelimiterTracker T(*this, tok::l_paren); 00741 if (T.expectAndConsume(diag::err_expected_lparen_after, 00742 "__underlying_type", tok::r_paren)) { 00743 return; 00744 } 00745 00746 TypeResult Result = ParseTypeName(); 00747 if (Result.isInvalid()) { 00748 SkipUntil(tok::r_paren); 00749 return; 00750 } 00751 00752 // Match the ')' 00753 T.consumeClose(); 00754 if (T.getCloseLocation().isInvalid()) 00755 return; 00756 00757 const char *PrevSpec = 0; 00758 unsigned DiagID; 00759 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec, 00760 DiagID, Result.release())) 00761 Diag(StartLoc, DiagID) << PrevSpec; 00762 } 00763 00764 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a 00765 /// class name or decltype-specifier. Note that we only check that the result 00766 /// names a type; semantic analysis will need to verify that the type names a 00767 /// class. The result is either a type or null, depending on whether a type 00768 /// name was found. 00769 /// 00770 /// base-type-specifier: [C++ 10.1] 00771 /// class-or-decltype 00772 /// class-or-decltype: [C++ 10.1] 00773 /// nested-name-specifier[opt] class-name 00774 /// decltype-specifier 00775 /// class-name: [C++ 9.1] 00776 /// identifier 00777 /// simple-template-id 00778 /// 00779 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, 00780 SourceLocation &EndLocation) { 00781 // Ignore attempts to use typename 00782 if (Tok.is(tok::kw_typename)) { 00783 Diag(Tok, diag::err_expected_class_name_not_template) 00784 << FixItHint::CreateRemoval(Tok.getLocation()); 00785 ConsumeToken(); 00786 } 00787 00788 // Parse optional nested-name-specifier 00789 CXXScopeSpec SS; 00790 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 00791 00792 BaseLoc = Tok.getLocation(); 00793 00794 // Parse decltype-specifier 00795 // tok == kw_decltype is just error recovery, it can only happen when SS 00796 // isn't empty 00797 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) { 00798 if (SS.isNotEmpty()) 00799 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype) 00800 << FixItHint::CreateRemoval(SS.getRange()); 00801 // Fake up a Declarator to use with ActOnTypeName. 00802 DeclSpec DS(AttrFactory); 00803 00804 EndLocation = ParseDecltypeSpecifier(DS); 00805 00806 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 00807 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 00808 } 00809 00810 // Check whether we have a template-id that names a type. 00811 if (Tok.is(tok::annot_template_id)) { 00812 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 00813 if (TemplateId->Kind == TNK_Type_template || 00814 TemplateId->Kind == TNK_Dependent_template_name) { 00815 AnnotateTemplateIdTokenAsType(); 00816 00817 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 00818 ParsedType Type = getTypeAnnotation(Tok); 00819 EndLocation = Tok.getAnnotationEndLoc(); 00820 ConsumeToken(); 00821 00822 if (Type) 00823 return Type; 00824 return true; 00825 } 00826 00827 // Fall through to produce an error below. 00828 } 00829 00830 if (Tok.isNot(tok::identifier)) { 00831 Diag(Tok, diag::err_expected_class_name); 00832 return true; 00833 } 00834 00835 IdentifierInfo *Id = Tok.getIdentifierInfo(); 00836 SourceLocation IdLoc = ConsumeToken(); 00837 00838 if (Tok.is(tok::less)) { 00839 // It looks the user intended to write a template-id here, but the 00840 // template-name was wrong. Try to fix that. 00841 TemplateNameKind TNK = TNK_Type_template; 00842 TemplateTy Template; 00843 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), 00844 &SS, Template, TNK)) { 00845 Diag(IdLoc, diag::err_unknown_template_name) 00846 << Id; 00847 } 00848 00849 if (!Template) 00850 return true; 00851 00852 // Form the template name 00853 UnqualifiedId TemplateName; 00854 TemplateName.setIdentifier(Id, IdLoc); 00855 00856 // Parse the full template-id, then turn it into a type. 00857 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 00858 TemplateName, true)) 00859 return true; 00860 if (TNK == TNK_Dependent_template_name) 00861 AnnotateTemplateIdTokenAsType(); 00862 00863 // If we didn't end up with a typename token, there's nothing more we 00864 // can do. 00865 if (Tok.isNot(tok::annot_typename)) 00866 return true; 00867 00868 // Retrieve the type from the annotation token, consume that token, and 00869 // return. 00870 EndLocation = Tok.getAnnotationEndLoc(); 00871 ParsedType Type = getTypeAnnotation(Tok); 00872 ConsumeToken(); 00873 return Type; 00874 } 00875 00876 // We have an identifier; check whether it is actually a type. 00877 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, 00878 false, ParsedType(), 00879 /*IsCtorOrDtorName=*/false, 00880 /*NonTrivialTypeSourceInfo=*/true); 00881 if (!Type) { 00882 Diag(IdLoc, diag::err_expected_class_name); 00883 return true; 00884 } 00885 00886 // Consume the identifier. 00887 EndLocation = IdLoc; 00888 00889 // Fake up a Declarator to use with ActOnTypeName. 00890 DeclSpec DS(AttrFactory); 00891 DS.SetRangeStart(IdLoc); 00892 DS.SetRangeEnd(EndLocation); 00893 DS.getTypeSpecScope() = SS; 00894 00895 const char *PrevSpec = 0; 00896 unsigned DiagID; 00897 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type); 00898 00899 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 00900 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 00901 } 00902 00903 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 00904 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 00905 /// until we reach the start of a definition or see a token that 00906 /// cannot start a definition. 00907 /// 00908 /// class-specifier: [C++ class] 00909 /// class-head '{' member-specification[opt] '}' 00910 /// class-head '{' member-specification[opt] '}' attributes[opt] 00911 /// class-head: 00912 /// class-key identifier[opt] base-clause[opt] 00913 /// class-key nested-name-specifier identifier base-clause[opt] 00914 /// class-key nested-name-specifier[opt] simple-template-id 00915 /// base-clause[opt] 00916 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 00917 /// [GNU] class-key attributes[opt] nested-name-specifier 00918 /// identifier base-clause[opt] 00919 /// [GNU] class-key attributes[opt] nested-name-specifier[opt] 00920 /// simple-template-id base-clause[opt] 00921 /// class-key: 00922 /// 'class' 00923 /// 'struct' 00924 /// 'union' 00925 /// 00926 /// elaborated-type-specifier: [C++ dcl.type.elab] 00927 /// class-key ::[opt] nested-name-specifier[opt] identifier 00928 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 00929 /// simple-template-id 00930 /// 00931 /// Note that the C++ class-specifier and elaborated-type-specifier, 00932 /// together, subsume the C99 struct-or-union-specifier: 00933 /// 00934 /// struct-or-union-specifier: [C99 6.7.2.1] 00935 /// struct-or-union identifier[opt] '{' struct-contents '}' 00936 /// struct-or-union identifier 00937 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 00938 /// '}' attributes[opt] 00939 /// [GNU] struct-or-union attributes[opt] identifier 00940 /// struct-or-union: 00941 /// 'struct' 00942 /// 'union' 00943 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, 00944 SourceLocation StartLoc, DeclSpec &DS, 00945 const ParsedTemplateInfo &TemplateInfo, 00946 AccessSpecifier AS, 00947 bool EnteringContext, DeclSpecContext DSC) { 00948 DeclSpec::TST TagType; 00949 if (TagTokKind == tok::kw_struct) 00950 TagType = DeclSpec::TST_struct; 00951 else if (TagTokKind == tok::kw_class) 00952 TagType = DeclSpec::TST_class; 00953 else { 00954 assert(TagTokKind == tok::kw_union && "Not a class specifier"); 00955 TagType = DeclSpec::TST_union; 00956 } 00957 00958 if (Tok.is(tok::code_completion)) { 00959 // Code completion for a struct, class, or union name. 00960 Actions.CodeCompleteTag(getCurScope(), TagType); 00961 return cutOffParsing(); 00962 } 00963 00964 // C++03 [temp.explicit] 14.7.2/8: 00965 // The usual access checking rules do not apply to names used to specify 00966 // explicit instantiations. 00967 // 00968 // As an extension we do not perform access checking on the names used to 00969 // specify explicit specializations either. This is important to allow 00970 // specializing traits classes for private types. 00971 // 00972 // Note that we don't suppress if this turns out to be an elaborated 00973 // type specifier. 00974 bool shouldDelayDiagsInTag = 00975 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 00976 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 00977 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 00978 00979 ParsedAttributes attrs(AttrFactory); 00980 // If attributes exist after tag, parse them. 00981 if (Tok.is(tok::kw___attribute)) 00982 ParseGNUAttributes(attrs); 00983 00984 // If declspecs exist after tag, parse them. 00985 while (Tok.is(tok::kw___declspec)) 00986 ParseMicrosoftDeclSpec(attrs); 00987 00988 // If C++0x attributes exist here, parse them. 00989 // FIXME: Are we consistent with the ordering of parsing of different 00990 // styles of attributes? 00991 MaybeParseCXX0XAttributes(attrs); 00992 00993 if (TagType == DeclSpec::TST_struct && 00994 !Tok.is(tok::identifier) && 00995 Tok.getIdentifierInfo() && 00996 (Tok.is(tok::kw___is_arithmetic) || 00997 Tok.is(tok::kw___is_convertible) || 00998 Tok.is(tok::kw___is_empty) || 00999 Tok.is(tok::kw___is_floating_point) || 01000 Tok.is(tok::kw___is_function) || 01001 Tok.is(tok::kw___is_fundamental) || 01002 Tok.is(tok::kw___is_integral) || 01003 Tok.is(tok::kw___is_member_function_pointer) || 01004 Tok.is(tok::kw___is_member_pointer) || 01005 Tok.is(tok::kw___is_pod) || 01006 Tok.is(tok::kw___is_pointer) || 01007 Tok.is(tok::kw___is_same) || 01008 Tok.is(tok::kw___is_scalar) || 01009 Tok.is(tok::kw___is_signed) || 01010 Tok.is(tok::kw___is_unsigned) || 01011 Tok.is(tok::kw___is_void))) { 01012 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the 01013 // name of struct templates, but some are keywords in GCC >= 4.3 01014 // and Clang. Therefore, when we see the token sequence "struct 01015 // X", make X into a normal identifier rather than a keyword, to 01016 // allow libstdc++ 4.2 and libc++ to work properly. 01017 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 01018 Tok.setKind(tok::identifier); 01019 } 01020 01021 // Parse the (optional) nested-name-specifier. 01022 CXXScopeSpec &SS = DS.getTypeSpecScope(); 01023 if (getLangOpts().CPlusPlus) { 01024 // "FOO : BAR" is not a potential typo for "FOO::BAR". 01025 ColonProtectionRAIIObject X(*this); 01026 01027 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 01028 DS.SetTypeSpecError(); 01029 if (SS.isSet()) 01030 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 01031 Diag(Tok, diag::err_expected_ident); 01032 } 01033 01034 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 01035 01036 // Parse the (optional) class name or simple-template-id. 01037 IdentifierInfo *Name = 0; 01038 SourceLocation NameLoc; 01039 TemplateIdAnnotation *TemplateId = 0; 01040 if (Tok.is(tok::identifier)) { 01041 Name = Tok.getIdentifierInfo(); 01042 NameLoc = ConsumeToken(); 01043 01044 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) { 01045 // The name was supposed to refer to a template, but didn't. 01046 // Eat the template argument list and try to continue parsing this as 01047 // a class (or template thereof). 01048 TemplateArgList TemplateArgs; 01049 SourceLocation LAngleLoc, RAngleLoc; 01050 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS, 01051 true, LAngleLoc, 01052 TemplateArgs, RAngleLoc)) { 01053 // We couldn't parse the template argument list at all, so don't 01054 // try to give any location information for the list. 01055 LAngleLoc = RAngleLoc = SourceLocation(); 01056 } 01057 01058 Diag(NameLoc, diag::err_explicit_spec_non_template) 01059 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 01060 << (TagType == DeclSpec::TST_class? 0 01061 : TagType == DeclSpec::TST_struct? 1 01062 : 2) 01063 << Name 01064 << SourceRange(LAngleLoc, RAngleLoc); 01065 01066 // Strip off the last template parameter list if it was empty, since 01067 // we've removed its template argument list. 01068 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) { 01069 if (TemplateParams && TemplateParams->size() > 1) { 01070 TemplateParams->pop_back(); 01071 } else { 01072 TemplateParams = 0; 01073 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 01074 = ParsedTemplateInfo::NonTemplate; 01075 } 01076 } else if (TemplateInfo.Kind 01077 == ParsedTemplateInfo::ExplicitInstantiation) { 01078 // Pretend this is just a forward declaration. 01079 TemplateParams = 0; 01080 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 01081 = ParsedTemplateInfo::NonTemplate; 01082 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc 01083 = SourceLocation(); 01084 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc 01085 = SourceLocation(); 01086 } 01087 } 01088 } else if (Tok.is(tok::annot_template_id)) { 01089 TemplateId = takeTemplateIdAnnotation(Tok); 01090 NameLoc = ConsumeToken(); 01091 01092 if (TemplateId->Kind != TNK_Type_template && 01093 TemplateId->Kind != TNK_Dependent_template_name) { 01094 // The template-name in the simple-template-id refers to 01095 // something other than a class template. Give an appropriate 01096 // error message and skip to the ';'. 01097 SourceRange Range(NameLoc); 01098 if (SS.isNotEmpty()) 01099 Range.setBegin(SS.getBeginLoc()); 01100 01101 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 01102 << Name << static_cast<int>(TemplateId->Kind) << Range; 01103 01104 DS.SetTypeSpecError(); 01105 SkipUntil(tok::semi, false, true); 01106 return; 01107 } 01108 } 01109 01110 // There are four options here. 01111 // - If we are in a trailing return type, this is always just a reference, 01112 // and we must not try to parse a definition. For instance, 01113 // [] () -> struct S { }; 01114 // does not define a type. 01115 // - If we have 'struct foo {...', 'struct foo :...', 01116 // 'struct foo final :' or 'struct foo final {', then this is a definition. 01117 // - If we have 'struct foo;', then this is either a forward declaration 01118 // or a friend declaration, which have to be treated differently. 01119 // - Otherwise we have something like 'struct foo xyz', a reference. 01120 // However, in type-specifier-seq's, things look like declarations but are 01121 // just references, e.g. 01122 // new struct s; 01123 // or 01124 // &T::operator struct s; 01125 // For these, DSC is DSC_type_specifier. 01126 Sema::TagUseKind TUK; 01127 if (DSC == DSC_trailing) 01128 TUK = Sema::TUK_Reference; 01129 else if (Tok.is(tok::l_brace) || 01130 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || 01131 (isCXX0XFinalKeyword() && 01132 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) { 01133 if (DS.isFriendSpecified()) { 01134 // C++ [class.friend]p2: 01135 // A class shall not be defined in a friend declaration. 01136 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 01137 << SourceRange(DS.getFriendSpecLoc()); 01138 01139 // Skip everything up to the semicolon, so that this looks like a proper 01140 // friend class (or template thereof) declaration. 01141 SkipUntil(tok::semi, true, true); 01142 TUK = Sema::TUK_Friend; 01143 } else { 01144 // Okay, this is a class definition. 01145 TUK = Sema::TUK_Definition; 01146 } 01147 } else if (Tok.is(tok::semi) && DSC != DSC_type_specifier) 01148 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 01149 else 01150 TUK = Sema::TUK_Reference; 01151 01152 // If this is an elaborated type specifier, and we delayed 01153 // diagnostics before, just merge them into the current pool. 01154 if (shouldDelayDiagsInTag) { 01155 diagsFromTag.done(); 01156 if (TUK == Sema::TUK_Reference) 01157 diagsFromTag.redelay(); 01158 } 01159 01160 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error || 01161 TUK != Sema::TUK_Definition)) { 01162 if (DS.getTypeSpecType() != DeclSpec::TST_error) { 01163 // We have a declaration or reference to an anonymous class. 01164 Diag(StartLoc, diag::err_anon_type_definition) 01165 << DeclSpec::getSpecifierName(TagType); 01166 } 01167 01168 SkipUntil(tok::comma, true); 01169 return; 01170 } 01171 01172 // Create the tag portion of the class or class template. 01173 DeclResult TagOrTempResult = true; // invalid 01174 TypeResult TypeResult = true; // invalid 01175 01176 bool Owned = false; 01177 if (TemplateId) { 01178 // Explicit specialization, class template partial specialization, 01179 // or explicit instantiation. 01180 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 01181 TemplateId->getTemplateArgs(), 01182 TemplateId->NumArgs); 01183 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 01184 TUK == Sema::TUK_Declaration) { 01185 // This is an explicit instantiation of a class template. 01186 TagOrTempResult 01187 = Actions.ActOnExplicitInstantiation(getCurScope(), 01188 TemplateInfo.ExternLoc, 01189 TemplateInfo.TemplateLoc, 01190 TagType, 01191 StartLoc, 01192 SS, 01193 TemplateId->Template, 01194 TemplateId->TemplateNameLoc, 01195 TemplateId->LAngleLoc, 01196 TemplateArgsPtr, 01197 TemplateId->RAngleLoc, 01198 attrs.getList()); 01199 01200 // Friend template-ids are treated as references unless 01201 // they have template headers, in which case they're ill-formed 01202 // (FIXME: "template <class T> friend class A<T>::B<int>;"). 01203 // We diagnose this error in ActOnClassTemplateSpecialization. 01204 } else if (TUK == Sema::TUK_Reference || 01205 (TUK == Sema::TUK_Friend && 01206 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) { 01207 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc, 01208 TemplateId->SS, 01209 TemplateId->TemplateKWLoc, 01210 TemplateId->Template, 01211 TemplateId->TemplateNameLoc, 01212 TemplateId->LAngleLoc, 01213 TemplateArgsPtr, 01214 TemplateId->RAngleLoc); 01215 } else { 01216 // This is an explicit specialization or a class template 01217 // partial specialization. 01218 TemplateParameterLists FakedParamLists; 01219 01220 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 01221 // This looks like an explicit instantiation, because we have 01222 // something like 01223 // 01224 // template class Foo<X> 01225 // 01226 // but it actually has a definition. Most likely, this was 01227 // meant to be an explicit specialization, but the user forgot 01228 // the '<>' after 'template'. 01229 assert(TUK == Sema::TUK_Definition && "Expected a definition here"); 01230 01231 SourceLocation LAngleLoc 01232 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 01233 Diag(TemplateId->TemplateNameLoc, 01234 diag::err_explicit_instantiation_with_definition) 01235 << SourceRange(TemplateInfo.TemplateLoc) 01236 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 01237 01238 // Create a fake template parameter list that contains only 01239 // "template<>", so that we treat this construct as a class 01240 // template specialization. 01241 FakedParamLists.push_back( 01242 Actions.ActOnTemplateParameterList(0, SourceLocation(), 01243 TemplateInfo.TemplateLoc, 01244 LAngleLoc, 01245 0, 0, 01246 LAngleLoc)); 01247 TemplateParams = &FakedParamLists; 01248 } 01249 01250 // Build the class template specialization. 01251 TagOrTempResult 01252 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK, 01253 StartLoc, DS.getModulePrivateSpecLoc(), SS, 01254 TemplateId->Template, 01255 TemplateId->TemplateNameLoc, 01256 TemplateId->LAngleLoc, 01257 TemplateArgsPtr, 01258 TemplateId->RAngleLoc, 01259 attrs.getList(), 01260 MultiTemplateParamsArg(Actions, 01261 TemplateParams? &(*TemplateParams)[0] : 0, 01262 TemplateParams? TemplateParams->size() : 0)); 01263 } 01264 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 01265 TUK == Sema::TUK_Declaration) { 01266 // Explicit instantiation of a member of a class template 01267 // specialization, e.g., 01268 // 01269 // template struct Outer<int>::Inner; 01270 // 01271 TagOrTempResult 01272 = Actions.ActOnExplicitInstantiation(getCurScope(), 01273 TemplateInfo.ExternLoc, 01274 TemplateInfo.TemplateLoc, 01275 TagType, StartLoc, SS, Name, 01276 NameLoc, attrs.getList()); 01277 } else if (TUK == Sema::TUK_Friend && 01278 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) { 01279 TagOrTempResult = 01280 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(), 01281 TagType, StartLoc, SS, 01282 Name, NameLoc, attrs.getList(), 01283 MultiTemplateParamsArg(Actions, 01284 TemplateParams? &(*TemplateParams)[0] : 0, 01285 TemplateParams? TemplateParams->size() : 0)); 01286 } else { 01287 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 01288 TUK == Sema::TUK_Definition) { 01289 // FIXME: Diagnose this particular error. 01290 } 01291 01292 bool IsDependent = false; 01293 01294 // Don't pass down template parameter lists if this is just a tag 01295 // reference. For example, we don't need the template parameters here: 01296 // template <class T> class A *makeA(T t); 01297 MultiTemplateParamsArg TParams; 01298 if (TUK != Sema::TUK_Reference && TemplateParams) 01299 TParams = 01300 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size()); 01301 01302 // Declaration or definition of a class type 01303 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc, 01304 SS, Name, NameLoc, attrs.getList(), AS, 01305 DS.getModulePrivateSpecLoc(), 01306 TParams, Owned, IsDependent, 01307 SourceLocation(), false, 01308 clang::TypeResult()); 01309 01310 // If ActOnTag said the type was dependent, try again with the 01311 // less common call. 01312 if (IsDependent) { 01313 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend); 01314 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, 01315 SS, Name, StartLoc, NameLoc); 01316 } 01317 } 01318 01319 // If there is a body, parse it and inform the actions module. 01320 if (TUK == Sema::TUK_Definition) { 01321 assert(Tok.is(tok::l_brace) || 01322 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || 01323 isCXX0XFinalKeyword()); 01324 if (getLangOpts().CPlusPlus) 01325 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()); 01326 else 01327 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 01328 } 01329 01330 const char *PrevSpec = 0; 01331 unsigned DiagID; 01332 bool Result; 01333 if (!TypeResult.isInvalid()) { 01334 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 01335 NameLoc.isValid() ? NameLoc : StartLoc, 01336 PrevSpec, DiagID, TypeResult.get()); 01337 } else if (!TagOrTempResult.isInvalid()) { 01338 Result = DS.SetTypeSpecType(TagType, StartLoc, 01339 NameLoc.isValid() ? NameLoc : StartLoc, 01340 PrevSpec, DiagID, TagOrTempResult.get(), Owned); 01341 } else { 01342 DS.SetTypeSpecError(); 01343 return; 01344 } 01345 01346 if (Result) 01347 Diag(StartLoc, DiagID) << PrevSpec; 01348 01349 // At this point, we've successfully parsed a class-specifier in 'definition' 01350 // form (e.g. "struct foo { int x; }". While we could just return here, we're 01351 // going to look at what comes after it to improve error recovery. If an 01352 // impossible token occurs next, we assume that the programmer forgot a ; at 01353 // the end of the declaration and recover that way. 01354 // 01355 // This switch enumerates the valid "follow" set for definition. 01356 if (TUK == Sema::TUK_Definition) { 01357 bool ExpectedSemi = true; 01358 switch (Tok.getKind()) { 01359 default: break; 01360 case tok::semi: // struct foo {...} ; 01361 case tok::star: // struct foo {...} * P; 01362 case tok::amp: // struct foo {...} & R = ... 01363 case tok::identifier: // struct foo {...} V ; 01364 case tok::r_paren: //(struct foo {...} ) {4} 01365 case tok::annot_cxxscope: // struct foo {...} a:: b; 01366 case tok::annot_typename: // struct foo {...} a ::b; 01367 case tok::annot_template_id: // struct foo {...} a<int> ::b; 01368 case tok::l_paren: // struct foo {...} ( x); 01369 case tok::comma: // __builtin_offsetof(struct foo{...} , 01370 ExpectedSemi = false; 01371 break; 01372 // Type qualifiers 01373 case tok::kw_const: // struct foo {...} const x; 01374 case tok::kw_volatile: // struct foo {...} volatile x; 01375 case tok::kw_restrict: // struct foo {...} restrict x; 01376 case tok::kw_inline: // struct foo {...} inline foo() {}; 01377 // Storage-class specifiers 01378 case tok::kw_static: // struct foo {...} static x; 01379 case tok::kw_extern: // struct foo {...} extern x; 01380 case tok::kw_typedef: // struct foo {...} typedef x; 01381 case tok::kw_register: // struct foo {...} register x; 01382 case tok::kw_auto: // struct foo {...} auto x; 01383 case tok::kw_mutable: // struct foo {...} mutable x; 01384 case tok::kw_constexpr: // struct foo {...} constexpr x; 01385 // As shown above, type qualifiers and storage class specifiers absolutely 01386 // can occur after class specifiers according to the grammar. However, 01387 // almost no one actually writes code like this. If we see one of these, 01388 // it is much more likely that someone missed a semi colon and the 01389 // type/storage class specifier we're seeing is part of the *next* 01390 // intended declaration, as in: 01391 // 01392 // struct foo { ... } 01393 // typedef int X; 01394 // 01395 // We'd really like to emit a missing semicolon error instead of emitting 01396 // an error on the 'int' saying that you can't have two type specifiers in 01397 // the same declaration of X. Because of this, we look ahead past this 01398 // token to see if it's a type specifier. If so, we know the code is 01399 // otherwise invalid, so we can produce the expected semi error. 01400 if (!isKnownToBeTypeSpecifier(NextToken())) 01401 ExpectedSemi = false; 01402 break; 01403 01404 case tok::r_brace: // struct bar { struct foo {...} } 01405 // Missing ';' at end of struct is accepted as an extension in C mode. 01406 if (!getLangOpts().CPlusPlus) 01407 ExpectedSemi = false; 01408 break; 01409 } 01410 01411 // C++ [temp]p3 In a template-declaration which defines a class, no 01412 // declarator is permitted. 01413 if (TemplateInfo.Kind) 01414 ExpectedSemi = true; 01415 01416 if (ExpectedSemi) { 01417 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 01418 TagType == DeclSpec::TST_class ? "class" 01419 : TagType == DeclSpec::TST_struct? "struct" : "union"); 01420 // Push this token back into the preprocessor and change our current token 01421 // to ';' so that the rest of the code recovers as though there were an 01422 // ';' after the definition. 01423 PP.EnterToken(Tok); 01424 Tok.setKind(tok::semi); 01425 } 01426 } 01427 } 01428 01429 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 01430 /// 01431 /// base-clause : [C++ class.derived] 01432 /// ':' base-specifier-list 01433 /// base-specifier-list: 01434 /// base-specifier '...'[opt] 01435 /// base-specifier-list ',' base-specifier '...'[opt] 01436 void Parser::ParseBaseClause(Decl *ClassDecl) { 01437 assert(Tok.is(tok::colon) && "Not a base clause"); 01438 ConsumeToken(); 01439 01440 // Build up an array of parsed base specifiers. 01441 SmallVector<CXXBaseSpecifier *, 8> BaseInfo; 01442 01443 while (true) { 01444 // Parse a base-specifier. 01445 BaseResult Result = ParseBaseSpecifier(ClassDecl); 01446 if (Result.isInvalid()) { 01447 // Skip the rest of this base specifier, up until the comma or 01448 // opening brace. 01449 SkipUntil(tok::comma, tok::l_brace, true, true); 01450 } else { 01451 // Add this to our array of base specifiers. 01452 BaseInfo.push_back(Result.get()); 01453 } 01454 01455 // If the next token is a comma, consume it and keep reading 01456 // base-specifiers. 01457 if (Tok.isNot(tok::comma)) break; 01458 01459 // Consume the comma. 01460 ConsumeToken(); 01461 } 01462 01463 // Attach the base specifiers 01464 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 01465 } 01466 01467 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 01468 /// one entry in the base class list of a class specifier, for example: 01469 /// class foo : public bar, virtual private baz { 01470 /// 'public bar' and 'virtual private baz' are each base-specifiers. 01471 /// 01472 /// base-specifier: [C++ class.derived] 01473 /// ::[opt] nested-name-specifier[opt] class-name 01474 /// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 01475 /// base-type-specifier 01476 /// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 01477 /// base-type-specifier 01478 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { 01479 bool IsVirtual = false; 01480 SourceLocation StartLoc = Tok.getLocation(); 01481 01482 // Parse the 'virtual' keyword. 01483 if (Tok.is(tok::kw_virtual)) { 01484 ConsumeToken(); 01485 IsVirtual = true; 01486 } 01487 01488 // Parse an (optional) access specifier. 01489 AccessSpecifier Access = getAccessSpecifierIfPresent(); 01490 if (Access != AS_none) 01491 ConsumeToken(); 01492 01493 // Parse the 'virtual' keyword (again!), in case it came after the 01494 // access specifier. 01495 if (Tok.is(tok::kw_virtual)) { 01496 SourceLocation VirtualLoc = ConsumeToken(); 01497 if (IsVirtual) { 01498 // Complain about duplicate 'virtual' 01499 Diag(VirtualLoc, diag::err_dup_virtual) 01500 << FixItHint::CreateRemoval(VirtualLoc); 01501 } 01502 01503 IsVirtual = true; 01504 } 01505 01506 // Parse the class-name. 01507 SourceLocation EndLocation; 01508 SourceLocation BaseLoc; 01509 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation); 01510 if (BaseType.isInvalid()) 01511 return true; 01512 01513 // Parse the optional ellipsis (for a pack expansion). The ellipsis is 01514 // actually part of the base-specifier-list grammar productions, but we 01515 // parse it here for convenience. 01516 SourceLocation EllipsisLoc; 01517 if (Tok.is(tok::ellipsis)) 01518 EllipsisLoc = ConsumeToken(); 01519 01520 // Find the complete source range for the base-specifier. 01521 SourceRange Range(StartLoc, EndLocation); 01522 01523 // Notify semantic analysis that we have parsed a complete 01524 // base-specifier. 01525 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, 01526 BaseType.get(), BaseLoc, EllipsisLoc); 01527 } 01528 01529 /// getAccessSpecifierIfPresent - Determine whether the next token is 01530 /// a C++ access-specifier. 01531 /// 01532 /// access-specifier: [C++ class.derived] 01533 /// 'private' 01534 /// 'protected' 01535 /// 'public' 01536 AccessSpecifier Parser::getAccessSpecifierIfPresent() const { 01537 switch (Tok.getKind()) { 01538 default: return AS_none; 01539 case tok::kw_private: return AS_private; 01540 case tok::kw_protected: return AS_protected; 01541 case tok::kw_public: return AS_public; 01542 } 01543 } 01544 01545 /// \brief If the given declarator has any parts for which parsing has to be 01546 /// delayed, e.g., default arguments, create a late-parsed method declaration 01547 /// record to handle the parsing at the end of the class definition. 01548 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, 01549 Decl *ThisDecl) { 01550 // We just declared a member function. If this member function 01551 // has any default arguments, we'll need to parse them later. 01552 LateParsedMethodDeclaration *LateMethod = 0; 01553 DeclaratorChunk::FunctionTypeInfo &FTI 01554 = DeclaratorInfo.getFunctionTypeInfo(); 01555 01556 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 01557 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 01558 if (!LateMethod) { 01559 // Push this method onto the stack of late-parsed method 01560 // declarations. 01561 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl); 01562 getCurrentClass().LateParsedDeclarations.push_back(LateMethod); 01563 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope(); 01564 01565 // Add all of the parameters prior to this one (they don't 01566 // have default arguments). 01567 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 01568 for (unsigned I = 0; I < ParamIdx; ++I) 01569 LateMethod->DefaultArgs.push_back( 01570 LateParsedDefaultArgument(FTI.ArgInfo[I].Param)); 01571 } 01572 01573 // Add this parameter to the list of parameters (it may or may 01574 // not have a default argument). 01575 LateMethod->DefaultArgs.push_back( 01576 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 01577 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 01578 } 01579 } 01580 } 01581 01582 /// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x 01583 /// virt-specifier. 01584 /// 01585 /// virt-specifier: 01586 /// override 01587 /// final 01588 VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) const { 01589 if (!getLangOpts().CPlusPlus) 01590 return VirtSpecifiers::VS_None; 01591 01592 if (Tok.is(tok::identifier)) { 01593 IdentifierInfo *II = Tok.getIdentifierInfo(); 01594 01595 // Initialize the contextual keywords. 01596 if (!Ident_final) { 01597 Ident_final = &PP.getIdentifierTable().get("final"); 01598 Ident_override = &PP.getIdentifierTable().get("override"); 01599 } 01600 01601 if (II == Ident_override) 01602 return VirtSpecifiers::VS_Override; 01603 01604 if (II == Ident_final) 01605 return VirtSpecifiers::VS_Final; 01606 } 01607 01608 return VirtSpecifiers::VS_None; 01609 } 01610 01611 /// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq. 01612 /// 01613 /// virt-specifier-seq: 01614 /// virt-specifier 01615 /// virt-specifier-seq virt-specifier 01616 void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS) { 01617 while (true) { 01618 VirtSpecifiers::Specifier Specifier = isCXX0XVirtSpecifier(); 01619 if (Specifier == VirtSpecifiers::VS_None) 01620 return; 01621 01622 // C++ [class.mem]p8: 01623 // A virt-specifier-seq shall contain at most one of each virt-specifier. 01624 const char *PrevSpec = 0; 01625 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec)) 01626 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier) 01627 << PrevSpec 01628 << FixItHint::CreateRemoval(Tok.getLocation()); 01629 01630 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ? 01631 diag::warn_cxx98_compat_override_control_keyword : 01632 diag::ext_override_control_keyword) 01633 << VirtSpecifiers::getSpecifierName(Specifier); 01634 ConsumeToken(); 01635 } 01636 } 01637 01638 /// isCXX0XFinalKeyword - Determine whether the next token is a C++0x 01639 /// contextual 'final' keyword. 01640 bool Parser::isCXX0XFinalKeyword() const { 01641 if (!getLangOpts().CPlusPlus) 01642 return false; 01643 01644 if (!Tok.is(tok::identifier)) 01645 return false; 01646 01647 // Initialize the contextual keywords. 01648 if (!Ident_final) { 01649 Ident_final = &PP.getIdentifierTable().get("final"); 01650 Ident_override = &PP.getIdentifierTable().get("override"); 01651 } 01652 01653 return Tok.getIdentifierInfo() == Ident_final; 01654 } 01655 01656 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 01657 /// 01658 /// member-declaration: 01659 /// decl-specifier-seq[opt] member-declarator-list[opt] ';' 01660 /// function-definition ';'[opt] 01661 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 01662 /// using-declaration [TODO] 01663 /// [C++0x] static_assert-declaration 01664 /// template-declaration 01665 /// [GNU] '__extension__' member-declaration 01666 /// 01667 /// member-declarator-list: 01668 /// member-declarator 01669 /// member-declarator-list ',' member-declarator 01670 /// 01671 /// member-declarator: 01672 /// declarator virt-specifier-seq[opt] pure-specifier[opt] 01673 /// declarator constant-initializer[opt] 01674 /// [C++11] declarator brace-or-equal-initializer[opt] 01675 /// identifier[opt] ':' constant-expression 01676 /// 01677 /// virt-specifier-seq: 01678 /// virt-specifier 01679 /// virt-specifier-seq virt-specifier 01680 /// 01681 /// virt-specifier: 01682 /// override 01683 /// final 01684 /// 01685 /// pure-specifier: 01686 /// '= 0' 01687 /// 01688 /// constant-initializer: 01689 /// '=' constant-expression 01690 /// 01691 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, 01692 AttributeList *AccessAttrs, 01693 const ParsedTemplateInfo &TemplateInfo, 01694 ParsingDeclRAIIObject *TemplateDiags) { 01695 if (Tok.is(tok::at)) { 01696 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs)) 01697 Diag(Tok, diag::err_at_defs_cxx); 01698 else 01699 Diag(Tok, diag::err_at_in_class); 01700 01701 ConsumeToken(); 01702 SkipUntil(tok::r_brace); 01703 return; 01704 } 01705 01706 // Access declarations. 01707 bool MalformedTypeSpec = false; 01708 if (!TemplateInfo.Kind && 01709 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) { 01710 if (TryAnnotateCXXScopeToken()) 01711 MalformedTypeSpec = true; 01712 01713 bool isAccessDecl; 01714 if (Tok.isNot(tok::annot_cxxscope)) 01715 isAccessDecl = false; 01716 else if (NextToken().is(tok::identifier)) 01717 isAccessDecl = GetLookAheadToken(2).is(tok::semi); 01718 else 01719 isAccessDecl = NextToken().is(tok::kw_operator); 01720 01721 if (isAccessDecl) { 01722 // Collect the scope specifier token we annotated earlier. 01723 CXXScopeSpec SS; 01724 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 01725 /*EnteringContext=*/false); 01726 01727 // Try to parse an unqualified-id. 01728 SourceLocation TemplateKWLoc; 01729 UnqualifiedId Name; 01730 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), 01731 TemplateKWLoc, Name)) { 01732 SkipUntil(tok::semi); 01733 return; 01734 } 01735 01736 // TODO: recover from mistakenly-qualified operator declarations. 01737 if (ExpectAndConsume(tok::semi, 01738 diag::err_expected_semi_after, 01739 "access declaration", 01740 tok::semi)) 01741 return; 01742 01743 Actions.ActOnUsingDeclaration(getCurScope(), AS, 01744 false, SourceLocation(), 01745 SS, Name, 01746 /* AttrList */ 0, 01747 /* IsTypeName */ false, 01748 SourceLocation()); 01749 return; 01750 } 01751 } 01752 01753 // static_assert-declaration 01754 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) { 01755 // FIXME: Check for templates 01756 SourceLocation DeclEnd; 01757 ParseStaticAssertDeclaration(DeclEnd); 01758 return; 01759 } 01760 01761 if (Tok.is(tok::kw_template)) { 01762 assert(!TemplateInfo.TemplateParams && 01763 "Nested template improperly parsed?"); 01764 SourceLocation DeclEnd; 01765 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 01766 AS, AccessAttrs); 01767 return; 01768 } 01769 01770 // Handle: member-declaration ::= '__extension__' member-declaration 01771 if (Tok.is(tok::kw___extension__)) { 01772 // __extension__ silences extension warnings in the subexpression. 01773 ExtensionRAIIObject O(Diags); // Use RAII to do this. 01774 ConsumeToken(); 01775 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, 01776 TemplateInfo, TemplateDiags); 01777 } 01778 01779 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it 01780 // is a bitfield. 01781 ColonProtectionRAIIObject X(*this); 01782 01783 ParsedAttributesWithRange attrs(AttrFactory); 01784 // Optional C++0x attribute-specifier 01785 MaybeParseCXX0XAttributes(attrs); 01786 MaybeParseMicrosoftAttributes(attrs); 01787 01788 if (Tok.is(tok::kw_using)) { 01789 ProhibitAttributes(attrs); 01790 01791 // Eat 'using'. 01792 SourceLocation UsingLoc = ConsumeToken(); 01793 01794 if (Tok.is(tok::kw_namespace)) { 01795 Diag(UsingLoc, diag::err_using_namespace_in_class); 01796 SkipUntil(tok::semi, true, true); 01797 } else { 01798 SourceLocation DeclEnd; 01799 // Otherwise, it must be a using-declaration or an alias-declaration. 01800 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo, 01801 UsingLoc, DeclEnd, AS); 01802 } 01803 return; 01804 } 01805 01806 // Hold late-parsed attributes so we can attach a Decl to them later. 01807 LateParsedAttrList CommonLateParsedAttrs; 01808 01809 // decl-specifier-seq: 01810 // Parse the common declaration-specifiers piece. 01811 ParsingDeclSpec DS(*this, TemplateDiags); 01812 DS.takeAttributesFrom(attrs); 01813 if (MalformedTypeSpec) 01814 DS.SetTypeSpecError(); 01815 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class, 01816 &CommonLateParsedAttrs); 01817 01818 MultiTemplateParamsArg TemplateParams(Actions, 01819 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0, 01820 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0); 01821 01822 if (Tok.is(tok::semi)) { 01823 ConsumeToken(); 01824 Decl *TheDecl = 01825 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams); 01826 DS.complete(TheDecl); 01827 return; 01828 } 01829 01830 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext); 01831 VirtSpecifiers VS; 01832 01833 // Hold late-parsed attributes so we can attach a Decl to them later. 01834 LateParsedAttrList LateParsedAttrs; 01835 01836 SourceLocation EqualLoc; 01837 bool HasInitializer = false; 01838 ExprResult Init; 01839 if (Tok.isNot(tok::colon)) { 01840 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 01841 ColonProtectionRAIIObject X(*this); 01842 01843 // Parse the first declarator. 01844 ParseDeclarator(DeclaratorInfo); 01845 // Error parsing the declarator? 01846 if (!DeclaratorInfo.hasName()) { 01847 // If so, skip until the semi-colon or a }. 01848 SkipUntil(tok::r_brace, true, true); 01849 if (Tok.is(tok::semi)) 01850 ConsumeToken(); 01851 return; 01852 } 01853 01854 ParseOptionalCXX0XVirtSpecifierSeq(VS); 01855 01856 // If attributes exist after the declarator, but before an '{', parse them. 01857 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 01858 01859 // MSVC permits pure specifier on inline functions declared at class scope. 01860 // Hence check for =0 before checking for function definition. 01861 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) && 01862 DeclaratorInfo.isFunctionDeclarator() && 01863 NextToken().is(tok::numeric_constant)) { 01864 EqualLoc = ConsumeToken(); 01865 Init = ParseInitializer(); 01866 if (Init.isInvalid()) 01867 SkipUntil(tok::comma, true, true); 01868 else 01869 HasInitializer = true; 01870 } 01871 01872 FunctionDefinitionKind DefinitionKind = FDK_Declaration; 01873 // function-definition: 01874 // 01875 // In C++11, a non-function declarator followed by an open brace is a 01876 // braced-init-list for an in-class member initialization, not an 01877 // erroneous function definition. 01878 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) { 01879 DefinitionKind = FDK_Definition; 01880 } else if (DeclaratorInfo.isFunctionDeclarator()) { 01881 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) { 01882 DefinitionKind = FDK_Definition; 01883 } else if (Tok.is(tok::equal)) { 01884 const Token &KW = NextToken(); 01885 if (KW.is(tok::kw_default)) 01886 DefinitionKind = FDK_Defaulted; 01887 else if (KW.is(tok::kw_delete)) 01888 DefinitionKind = FDK_Deleted; 01889 } 01890 } 01891 01892 if (DefinitionKind) { 01893 if (!DeclaratorInfo.isFunctionDeclarator()) { 01894 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params); 01895 ConsumeBrace(); 01896 SkipUntil(tok::r_brace, /*StopAtSemi*/false); 01897 01898 // Consume the optional ';' 01899 if (Tok.is(tok::semi)) 01900 ConsumeToken(); 01901 return; 01902 } 01903 01904 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 01905 Diag(DeclaratorInfo.getIdentifierLoc(), 01906 diag::err_function_declared_typedef); 01907 // This recovery skips the entire function body. It would be nice 01908 // to simply call ParseCXXInlineMethodDef() below, however Sema 01909 // assumes the declarator represents a function, not a typedef. 01910 ConsumeBrace(); 01911 SkipUntil(tok::r_brace, /*StopAtSemi*/false); 01912 01913 // Consume the optional ';' 01914 if (Tok.is(tok::semi)) 01915 ConsumeToken(); 01916 return; 01917 } 01918 01919 Decl *FunDecl = 01920 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo, 01921 VS, DefinitionKind, Init); 01922 01923 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { 01924 CommonLateParsedAttrs[i]->addDecl(FunDecl); 01925 } 01926 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { 01927 LateParsedAttrs[i]->addDecl(FunDecl); 01928 } 01929 LateParsedAttrs.clear(); 01930 01931 // Consume the ';' - it's optional unless we have a delete or default 01932 if (Tok.is(tok::semi)) 01933 ConsumeExtraSemi(AfterDefinition); 01934 01935 return; 01936 } 01937 } 01938 01939 // member-declarator-list: 01940 // member-declarator 01941 // member-declarator-list ',' member-declarator 01942 01943 SmallVector<Decl *, 8> DeclsInGroup; 01944 ExprResult BitfieldSize; 01945 bool ExpectSemi = true; 01946 01947 while (1) { 01948 // member-declarator: 01949 // declarator pure-specifier[opt] 01950 // declarator brace-or-equal-initializer[opt] 01951 // identifier[opt] ':' constant-expression 01952 if (Tok.is(tok::colon)) { 01953 ConsumeToken(); 01954 BitfieldSize = ParseConstantExpression(); 01955 if (BitfieldSize.isInvalid()) 01956 SkipUntil(tok::comma, true, true); 01957 } 01958 01959 // If a simple-asm-expr is present, parse it. 01960 if (Tok.is(tok::kw_asm)) { 01961 SourceLocation Loc; 01962 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 01963 if (AsmLabel.isInvalid()) 01964 SkipUntil(tok::comma, true, true); 01965 01966 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 01967 DeclaratorInfo.SetRangeEnd(Loc); 01968 } 01969 01970 // If attributes exist after the declarator, parse them. 01971 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 01972 01973 // FIXME: When g++ adds support for this, we'll need to check whether it 01974 // goes before or after the GNU attributes and __asm__. 01975 ParseOptionalCXX0XVirtSpecifierSeq(VS); 01976 01977 bool HasDeferredInitializer = false; 01978 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) { 01979 if (BitfieldSize.get()) { 01980 Diag(Tok, diag::err_bitfield_member_init); 01981 SkipUntil(tok::comma, true, true); 01982 } else { 01983 HasInitializer = true; 01984 HasDeferredInitializer = !DeclaratorInfo.isDeclarationOfFunction() && 01985 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 01986 != DeclSpec::SCS_static && 01987 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 01988 != DeclSpec::SCS_typedef; 01989 } 01990 } 01991 01992 // NOTE: If Sema is the Action module and declarator is an instance field, 01993 // this call will *not* return the created decl; It will return null. 01994 // See Sema::ActOnCXXMemberDeclarator for details. 01995 01996 Decl *ThisDecl = 0; 01997 if (DS.isFriendSpecified()) { 01998 // TODO: handle initializers, bitfields, 'delete' 01999 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 02000 move(TemplateParams)); 02001 } else { 02002 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, 02003 DeclaratorInfo, 02004 move(TemplateParams), 02005 BitfieldSize.release(), 02006 VS, HasDeferredInitializer); 02007 if (AccessAttrs) 02008 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs, 02009 false, true); 02010 } 02011 02012 // Set the Decl for any late parsed attributes 02013 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { 02014 CommonLateParsedAttrs[i]->addDecl(ThisDecl); 02015 } 02016 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { 02017 LateParsedAttrs[i]->addDecl(ThisDecl); 02018 } 02019 LateParsedAttrs.clear(); 02020 02021 // Handle the initializer. 02022 if (HasDeferredInitializer) { 02023 // The initializer was deferred; parse it and cache the tokens. 02024 Diag(Tok, getLangOpts().CPlusPlus0x ? 02025 diag::warn_cxx98_compat_nonstatic_member_init : 02026 diag::ext_nonstatic_member_init); 02027 02028 if (DeclaratorInfo.isArrayOfUnknownBound()) { 02029 // C++0x [dcl.array]p3: An array bound may also be omitted when the 02030 // declarator is followed by an initializer. 02031 // 02032 // A brace-or-equal-initializer for a member-declarator is not an 02033 // initializer in the grammar, so this is ill-formed. 02034 Diag(Tok, diag::err_incomplete_array_member_init); 02035 SkipUntil(tok::comma, true, true); 02036 if (ThisDecl) 02037 // Avoid later warnings about a class member of incomplete type. 02038 ThisDecl->setInvalidDecl(); 02039 } else 02040 ParseCXXNonStaticMemberInitializer(ThisDecl); 02041 } else if (HasInitializer) { 02042 // Normal initializer. 02043 if (!Init.isUsable()) 02044 Init = ParseCXXMemberInitializer(ThisDecl, 02045 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc); 02046 02047 if (Init.isInvalid()) 02048 SkipUntil(tok::comma, true, true); 02049 else if (ThisDecl) 02050 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(), 02051 DS.getTypeSpecType() == DeclSpec::TST_auto); 02052 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) { 02053 // No initializer. 02054 Actions.ActOnUninitializedDecl(ThisDecl, 02055 DS.getTypeSpecType() == DeclSpec::TST_auto); 02056 } 02057 02058 if (ThisDecl) { 02059 Actions.FinalizeDeclaration(ThisDecl); 02060 DeclsInGroup.push_back(ThisDecl); 02061 } 02062 02063 if (ThisDecl && DeclaratorInfo.isFunctionDeclarator() && 02064 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 02065 != DeclSpec::SCS_typedef) { 02066 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl); 02067 } 02068 02069 DeclaratorInfo.complete(ThisDecl); 02070 02071 // If we don't have a comma, it is either the end of the list (a ';') 02072 // or an error, bail out. 02073 if (Tok.isNot(tok::comma)) 02074 break; 02075 02076 // Consume the comma. 02077 SourceLocation CommaLoc = ConsumeToken(); 02078 02079 if (Tok.isAtStartOfLine() && 02080 !MightBeDeclarator(Declarator::MemberContext)) { 02081 // This comma was followed by a line-break and something which can't be 02082 // the start of a declarator. The comma was probably a typo for a 02083 // semicolon. 02084 Diag(CommaLoc, diag::err_expected_semi_declaration) 02085 << FixItHint::CreateReplacement(CommaLoc, ";"); 02086 ExpectSemi = false; 02087 break; 02088 } 02089 02090 // Parse the next declarator. 02091 DeclaratorInfo.clear(); 02092 VS.clear(); 02093 BitfieldSize = true; 02094 Init = true; 02095 HasInitializer = false; 02096 DeclaratorInfo.setCommaLoc(CommaLoc); 02097 02098 // Attributes are only allowed on the second declarator. 02099 MaybeParseGNUAttributes(DeclaratorInfo); 02100 02101 if (Tok.isNot(tok::colon)) 02102 ParseDeclarator(DeclaratorInfo); 02103 } 02104 02105 if (ExpectSemi && 02106 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 02107 // Skip to end of block or statement. 02108 SkipUntil(tok::r_brace, true, true); 02109 // If we stopped at a ';', eat it. 02110 if (Tok.is(tok::semi)) ConsumeToken(); 02111 return; 02112 } 02113 02114 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(), 02115 DeclsInGroup.size()); 02116 } 02117 02118 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or 02119 /// pure-specifier. Also detect and reject any attempted defaulted/deleted 02120 /// function definition. The location of the '=', if any, will be placed in 02121 /// EqualLoc. 02122 /// 02123 /// pure-specifier: 02124 /// '= 0' 02125 /// 02126 /// brace-or-equal-initializer: 02127 /// '=' initializer-expression 02128 /// braced-init-list 02129 /// 02130 /// initializer-clause: 02131 /// assignment-expression 02132 /// braced-init-list 02133 /// 02134 /// defaulted/deleted function-definition: 02135 /// '=' 'default' 02136 /// '=' 'delete' 02137 /// 02138 /// Prior to C++0x, the assignment-expression in an initializer-clause must 02139 /// be a constant-expression. 02140 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction, 02141 SourceLocation &EqualLoc) { 02142 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace)) 02143 && "Data member initializer not starting with '=' or '{'"); 02144 02145 EnterExpressionEvaluationContext Context(Actions, 02146 Sema::PotentiallyEvaluated, 02147 D); 02148 if (Tok.is(tok::equal)) { 02149 EqualLoc = ConsumeToken(); 02150 if (Tok.is(tok::kw_delete)) { 02151 // In principle, an initializer of '= delete p;' is legal, but it will 02152 // never type-check. It's better to diagnose it as an ill-formed expression 02153 // than as an ill-formed deleted non-function member. 02154 // An initializer of '= delete p, foo' will never be parsed, because 02155 // a top-level comma always ends the initializer expression. 02156 const Token &Next = NextToken(); 02157 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) || 02158 Next.is(tok::eof)) { 02159 if (IsFunction) 02160 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 02161 << 1 /* delete */; 02162 else 02163 Diag(ConsumeToken(), diag::err_deleted_non_function); 02164 return ExprResult(); 02165 } 02166 } else if (Tok.is(tok::kw_default)) { 02167 if (IsFunction) 02168 Diag(Tok, diag::err_default_delete_in_multiple_declaration) 02169 << 0 /* default */; 02170 else 02171 Diag(ConsumeToken(), diag::err_default_special_members); 02172 return ExprResult(); 02173 } 02174 02175 } 02176 return ParseInitializer(); 02177 } 02178 02179 /// ParseCXXMemberSpecification - Parse the class definition. 02180 /// 02181 /// member-specification: 02182 /// member-declaration member-specification[opt] 02183 /// access-specifier ':' member-specification[opt] 02184 /// 02185 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 02186 unsigned TagType, Decl *TagDecl) { 02187 assert((TagType == DeclSpec::TST_struct || 02188 TagType == DeclSpec::TST_union || 02189 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 02190 02191 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 02192 "parsing struct/union/class body"); 02193 02194 // Determine whether this is a non-nested class. Note that local 02195 // classes are *not* considered to be nested classes. 02196 bool NonNestedClass = true; 02197 if (!ClassStack.empty()) { 02198 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 02199 if (S->isClassScope()) { 02200 // We're inside a class scope, so this is a nested class. 02201 NonNestedClass = false; 02202 break; 02203 } 02204 02205 if ((S->getFlags() & Scope::FnScope)) { 02206 // If we're in a function or function template declared in the 02207 // body of a class, then this is a local class rather than a 02208 // nested class. 02209 const Scope *Parent = S->getParent(); 02210 if (Parent->isTemplateParamScope()) 02211 Parent = Parent->getParent(); 02212 if (Parent->isClassScope()) 02213 break; 02214 } 02215 } 02216 } 02217 02218 // Enter a scope for the class. 02219 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 02220 02221 // Note that we are parsing a new (potentially-nested) class definition. 02222 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass); 02223 02224 if (TagDecl) 02225 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 02226 02227 SourceLocation FinalLoc; 02228 02229 // Parse the optional 'final' keyword. 02230 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { 02231 assert(isCXX0XFinalKeyword() && "not a class definition"); 02232 FinalLoc = ConsumeToken(); 02233 02234 Diag(FinalLoc, getLangOpts().CPlusPlus0x ? 02235 diag::warn_cxx98_compat_override_control_keyword : 02236 diag::ext_override_control_keyword) << "final"; 02237 } 02238 02239 if (Tok.is(tok::colon)) { 02240 ParseBaseClause(TagDecl); 02241 02242 if (!Tok.is(tok::l_brace)) { 02243 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers); 02244 02245 if (TagDecl) 02246 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 02247 return; 02248 } 02249 } 02250 02251 assert(Tok.is(tok::l_brace)); 02252 BalancedDelimiterTracker T(*this, tok::l_brace); 02253 T.consumeOpen(); 02254 02255 if (TagDecl) 02256 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc, 02257 T.getOpenLocation()); 02258 02259 // C++ 11p3: Members of a class defined with the keyword class are private 02260 // by default. Members of a class defined with the keywords struct or union 02261 // are public by default. 02262 AccessSpecifier CurAS; 02263 if (TagType == DeclSpec::TST_class) 02264 CurAS = AS_private; 02265 else 02266 CurAS = AS_public; 02267 ParsedAttributes AccessAttrs(AttrFactory); 02268 02269 if (TagDecl) { 02270 // While we still have something to read, read the member-declarations. 02271 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 02272 // Each iteration of this loop reads one member-declaration. 02273 02274 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) || 02275 Tok.is(tok::kw___if_not_exists))) { 02276 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); 02277 continue; 02278 } 02279 02280 // Check for extraneous top-level semicolon. 02281 if (Tok.is(tok::semi)) { 02282 ConsumeExtraSemi(InsideStruct, 02283 DeclSpec::getSpecifierName((DeclSpec::TST)TagType)); 02284 continue; 02285 } 02286 02287 if (Tok.is(tok::annot_pragma_vis)) { 02288 HandlePragmaVisibility(); 02289 continue; 02290 } 02291 02292 if (Tok.is(tok::annot_pragma_pack)) { 02293 HandlePragmaPack(); 02294 continue; 02295 } 02296 02297 AccessSpecifier AS = getAccessSpecifierIfPresent(); 02298 if (AS != AS_none) { 02299 // Current token is a C++ access specifier. 02300 CurAS = AS; 02301 SourceLocation ASLoc = Tok.getLocation(); 02302 unsigned TokLength = Tok.getLength(); 02303 ConsumeToken(); 02304 AccessAttrs.clear(); 02305 MaybeParseGNUAttributes(AccessAttrs); 02306 02307 SourceLocation EndLoc; 02308 if (Tok.is(tok::colon)) { 02309 EndLoc = Tok.getLocation(); 02310 ConsumeToken(); 02311 } else if (Tok.is(tok::semi)) { 02312 EndLoc = Tok.getLocation(); 02313 ConsumeToken(); 02314 Diag(EndLoc, diag::err_expected_colon) 02315 << FixItHint::CreateReplacement(EndLoc, ":"); 02316 } else { 02317 EndLoc = ASLoc.getLocWithOffset(TokLength); 02318 Diag(EndLoc, diag::err_expected_colon) 02319 << FixItHint::CreateInsertion(EndLoc, ":"); 02320 } 02321 02322 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc, 02323 AccessAttrs.getList())) { 02324 // found another attribute than only annotations 02325 AccessAttrs.clear(); 02326 } 02327 02328 continue; 02329 } 02330 02331 // FIXME: Make sure we don't have a template here. 02332 02333 // Parse all the comma separated declarators. 02334 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList()); 02335 } 02336 02337 T.consumeClose(); 02338 } else { 02339 SkipUntil(tok::r_brace, false, false); 02340 } 02341 02342 // If attributes exist after class contents, parse them. 02343 ParsedAttributes attrs(AttrFactory); 02344 MaybeParseGNUAttributes(attrs); 02345 02346 if (TagDecl) 02347 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 02348 T.getOpenLocation(), 02349 T.getCloseLocation(), 02350 attrs.getList()); 02351 02352 // C++11 [class.mem]p2: 02353 // Within the class member-specification, the class is regarded as complete 02354 // within function bodies, default arguments, and 02355 // brace-or-equal-initializers for non-static data members (including such 02356 // things in nested classes). 02357 if (TagDecl && NonNestedClass) { 02358 // We are not inside a nested class. This class and its nested classes 02359 // are complete and we can parse the delayed portions of method 02360 // declarations and the lexed inline method definitions, along with any 02361 // delayed attributes. 02362 SourceLocation SavedPrevTokLocation = PrevTokLocation; 02363 ParseLexedAttributes(getCurrentClass()); 02364 ParseLexedMethodDeclarations(getCurrentClass()); 02365 02366 // We've finished with all pending member declarations. 02367 Actions.ActOnFinishCXXMemberDecls(); 02368 02369 ParseLexedMemberInitializers(getCurrentClass()); 02370 ParseLexedMethodDefs(getCurrentClass()); 02371 PrevTokLocation = SavedPrevTokLocation; 02372 } 02373 02374 if (TagDecl) 02375 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 02376 T.getCloseLocation()); 02377 02378 // Leave the class scope. 02379 ParsingDef.Pop(); 02380 ClassScope.Exit(); 02381 } 02382 02383 /// ParseConstructorInitializer - Parse a C++ constructor initializer, 02384 /// which explicitly initializes the members or base classes of a 02385 /// class (C++ [class.base.init]). For example, the three initializers 02386 /// after the ':' in the Derived constructor below: 02387 /// 02388 /// @code 02389 /// class Base { }; 02390 /// class Derived : Base { 02391 /// int x; 02392 /// float f; 02393 /// public: 02394 /// Derived(float f) : Base(), x(17), f(f) { } 02395 /// }; 02396 /// @endcode 02397 /// 02398 /// [C++] ctor-initializer: 02399 /// ':' mem-initializer-list 02400 /// 02401 /// [C++] mem-initializer-list: 02402 /// mem-initializer ...[opt] 02403 /// mem-initializer ...[opt] , mem-initializer-list 02404 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { 02405 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 02406 02407 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers 02408 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 02409 SourceLocation ColonLoc = ConsumeToken(); 02410 02411 SmallVector<CXXCtorInitializer*, 4> MemInitializers; 02412 bool AnyErrors = false; 02413 02414 do { 02415 if (Tok.is(tok::code_completion)) { 02416 Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 02417 MemInitializers.data(), 02418 MemInitializers.size()); 02419 return cutOffParsing(); 02420 } else { 02421 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 02422 if (!MemInit.isInvalid()) 02423 MemInitializers.push_back(MemInit.get()); 02424 else 02425 AnyErrors = true; 02426 } 02427 02428 if (Tok.is(tok::comma)) 02429 ConsumeToken(); 02430 else if (Tok.is(tok::l_brace)) 02431 break; 02432 // If the next token looks like a base or member initializer, assume that 02433 // we're just missing a comma. 02434 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) { 02435 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 02436 Diag(Loc, diag::err_ctor_init_missing_comma) 02437 << FixItHint::CreateInsertion(Loc, ", "); 02438 } else { 02439 // Skip over garbage, until we get to '{'. Don't eat the '{'. 02440 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 02441 SkipUntil(tok::l_brace, true, true); 02442 break; 02443 } 02444 } while (true); 02445 02446 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 02447 MemInitializers.data(), MemInitializers.size(), 02448 AnyErrors); 02449 } 02450 02451 /// ParseMemInitializer - Parse a C++ member initializer, which is 02452 /// part of a constructor initializer that explicitly initializes one 02453 /// member or base class (C++ [class.base.init]). See 02454 /// ParseConstructorInitializer for an example. 02455 /// 02456 /// [C++] mem-initializer: 02457 /// mem-initializer-id '(' expression-list[opt] ')' 02458 /// [C++0x] mem-initializer-id braced-init-list 02459 /// 02460 /// [C++] mem-initializer-id: 02461 /// '::'[opt] nested-name-specifier[opt] class-name 02462 /// identifier 02463 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { 02464 // parse '::'[opt] nested-name-specifier[opt] 02465 CXXScopeSpec SS; 02466 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 02467 ParsedType TemplateTypeTy; 02468 if (Tok.is(tok::annot_template_id)) { 02469 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 02470 if (TemplateId->Kind == TNK_Type_template || 02471 TemplateId->Kind == TNK_Dependent_template_name) { 02472 AnnotateTemplateIdTokenAsType(); 02473 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 02474 TemplateTypeTy = getTypeAnnotation(Tok); 02475 } 02476 } 02477 // Uses of decltype will already have been converted to annot_decltype by 02478 // ParseOptionalCXXScopeSpecifier at this point. 02479 if (!TemplateTypeTy && Tok.isNot(tok::identifier) 02480 && Tok.isNot(tok::annot_decltype)) { 02481 Diag(Tok, diag::err_expected_member_or_base_name); 02482 return true; 02483 } 02484 02485 IdentifierInfo *II = 0; 02486 DeclSpec DS(AttrFactory); 02487 SourceLocation IdLoc = Tok.getLocation(); 02488 if (Tok.is(tok::annot_decltype)) { 02489 // Get the decltype expression, if there is one. 02490 ParseDecltypeSpecifier(DS); 02491 } else { 02492 if (Tok.is(tok::identifier)) 02493 // Get the identifier. This may be a member name or a class name, 02494 // but we'll let the semantic analysis determine which it is. 02495 II = Tok.getIdentifierInfo(); 02496 ConsumeToken(); 02497 } 02498 02499 02500 // Parse the '('. 02501 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 02502 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 02503 02504 ExprResult InitList = ParseBraceInitializer(); 02505 if (InitList.isInvalid()) 02506 return true; 02507 02508 SourceLocation EllipsisLoc; 02509 if (Tok.is(tok::ellipsis)) 02510 EllipsisLoc = ConsumeToken(); 02511 02512 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 02513 TemplateTypeTy, DS, IdLoc, 02514 InitList.take(), EllipsisLoc); 02515 } else if(Tok.is(tok::l_paren)) { 02516 BalancedDelimiterTracker T(*this, tok::l_paren); 02517 T.consumeOpen(); 02518 02519 // Parse the optional expression-list. 02520 ExprVector ArgExprs(Actions); 02521 CommaLocsTy CommaLocs; 02522 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 02523 SkipUntil(tok::r_paren); 02524 return true; 02525 } 02526 02527 T.consumeClose(); 02528 02529 SourceLocation EllipsisLoc; 02530 if (Tok.is(tok::ellipsis)) 02531 EllipsisLoc = ConsumeToken(); 02532 02533 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 02534 TemplateTypeTy, DS, IdLoc, 02535 T.getOpenLocation(), ArgExprs.take(), 02536 ArgExprs.size(), T.getCloseLocation(), 02537 EllipsisLoc); 02538 } 02539 02540 Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace 02541 : diag::err_expected_lparen); 02542 return true; 02543 } 02544 02545 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]). 02546 /// 02547 /// exception-specification: 02548 /// dynamic-exception-specification 02549 /// noexcept-specification 02550 /// 02551 /// noexcept-specification: 02552 /// 'noexcept' 02553 /// 'noexcept' '(' constant-expression ')' 02554 ExceptionSpecificationType 02555 Parser::tryParseExceptionSpecification( 02556 SourceRange &SpecificationRange, 02557 SmallVectorImpl<ParsedType> &DynamicExceptions, 02558 SmallVectorImpl<SourceRange> &DynamicExceptionRanges, 02559 ExprResult &NoexceptExpr) { 02560 ExceptionSpecificationType Result = EST_None; 02561 02562 // See if there's a dynamic specification. 02563 if (Tok.is(tok::kw_throw)) { 02564 Result = ParseDynamicExceptionSpecification(SpecificationRange, 02565 DynamicExceptions, 02566 DynamicExceptionRanges); 02567 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() && 02568 "Produced different number of exception types and ranges."); 02569 } 02570 02571 // If there's no noexcept specification, we're done. 02572 if (Tok.isNot(tok::kw_noexcept)) 02573 return Result; 02574 02575 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl); 02576 02577 // If we already had a dynamic specification, parse the noexcept for, 02578 // recovery, but emit a diagnostic and don't store the results. 02579 SourceRange NoexceptRange; 02580 ExceptionSpecificationType NoexceptType = EST_None; 02581 02582 SourceLocation KeywordLoc = ConsumeToken(); 02583 if (Tok.is(tok::l_paren)) { 02584 // There is an argument. 02585 BalancedDelimiterTracker T(*this, tok::l_paren); 02586 T.consumeOpen(); 02587 NoexceptType = EST_ComputedNoexcept; 02588 NoexceptExpr = ParseConstantExpression(); 02589 // The argument must be contextually convertible to bool. We use 02590 // ActOnBooleanCondition for this purpose. 02591 if (!NoexceptExpr.isInvalid()) 02592 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc, 02593 NoexceptExpr.get()); 02594 T.consumeClose(); 02595 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation()); 02596 } else { 02597 // There is no argument. 02598 NoexceptType = EST_BasicNoexcept; 02599 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc); 02600 } 02601 02602 if (Result == EST_None) { 02603 SpecificationRange = NoexceptRange; 02604 Result = NoexceptType; 02605 02606 // If there's a dynamic specification after a noexcept specification, 02607 // parse that and ignore the results. 02608 if (Tok.is(tok::kw_throw)) { 02609 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 02610 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions, 02611 DynamicExceptionRanges); 02612 } 02613 } else { 02614 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 02615 } 02616 02617 return Result; 02618 } 02619 02620 /// ParseDynamicExceptionSpecification - Parse a C++ 02621 /// dynamic-exception-specification (C++ [except.spec]). 02622 /// 02623 /// dynamic-exception-specification: 02624 /// 'throw' '(' type-id-list [opt] ')' 02625 /// [MS] 'throw' '(' '...' ')' 02626 /// 02627 /// type-id-list: 02628 /// type-id ... [opt] 02629 /// type-id-list ',' type-id ... [opt] 02630 /// 02631 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( 02632 SourceRange &SpecificationRange, 02633 SmallVectorImpl<ParsedType> &Exceptions, 02634 SmallVectorImpl<SourceRange> &Ranges) { 02635 assert(Tok.is(tok::kw_throw) && "expected throw"); 02636 02637 SpecificationRange.setBegin(ConsumeToken()); 02638 BalancedDelimiterTracker T(*this, tok::l_paren); 02639 if (T.consumeOpen()) { 02640 Diag(Tok, diag::err_expected_lparen_after) << "throw"; 02641 SpecificationRange.setEnd(SpecificationRange.getBegin()); 02642 return EST_DynamicNone; 02643 } 02644 02645 // Parse throw(...), a Microsoft extension that means "this function 02646 // can throw anything". 02647 if (Tok.is(tok::ellipsis)) { 02648 SourceLocation EllipsisLoc = ConsumeToken(); 02649 if (!getLangOpts().MicrosoftExt) 02650 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 02651 T.consumeClose(); 02652 SpecificationRange.setEnd(T.getCloseLocation()); 02653 return EST_MSAny; 02654 } 02655 02656 // Parse the sequence of type-ids. 02657 SourceRange Range; 02658 while (Tok.isNot(tok::r_paren)) { 02659 TypeResult Res(ParseTypeName(&Range)); 02660 02661 if (Tok.is(tok::ellipsis)) { 02662 // C++0x [temp.variadic]p5: 02663 // - In a dynamic-exception-specification (15.4); the pattern is a 02664 // type-id. 02665 SourceLocation Ellipsis = ConsumeToken(); 02666 Range.setEnd(Ellipsis); 02667 if (!Res.isInvalid()) 02668 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis); 02669 } 02670 02671 if (!Res.isInvalid()) { 02672 Exceptions.push_back(Res.get()); 02673 Ranges.push_back(Range); 02674 } 02675 02676 if (Tok.is(tok::comma)) 02677 ConsumeToken(); 02678 else 02679 break; 02680 } 02681 02682 T.consumeClose(); 02683 SpecificationRange.setEnd(T.getCloseLocation()); 02684 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic; 02685 } 02686 02687 /// ParseTrailingReturnType - Parse a trailing return type on a new-style 02688 /// function declaration. 02689 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) { 02690 assert(Tok.is(tok::arrow) && "expected arrow"); 02691 02692 ConsumeToken(); 02693 02694 return ParseTypeName(&Range, Declarator::TrailingReturnContext); 02695 } 02696 02697 /// \brief We have just started parsing the definition of a new class, 02698 /// so push that class onto our stack of classes that is currently 02699 /// being parsed. 02700 Sema::ParsingClassState 02701 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) { 02702 assert((NonNestedClass || !ClassStack.empty()) && 02703 "Nested class without outer class"); 02704 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass)); 02705 return Actions.PushParsingClass(); 02706 } 02707 02708 /// \brief Deallocate the given parsed class and all of its nested 02709 /// classes. 02710 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 02711 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I) 02712 delete Class->LateParsedDeclarations[I]; 02713 delete Class; 02714 } 02715 02716 /// \brief Pop the top class of the stack of classes that are 02717 /// currently being parsed. 02718 /// 02719 /// This routine should be called when we have finished parsing the 02720 /// definition of a class, but have not yet popped the Scope 02721 /// associated with the class's definition. 02722 /// 02723 /// \returns true if the class we've popped is a top-level class, 02724 /// false otherwise. 02725 void Parser::PopParsingClass(Sema::ParsingClassState state) { 02726 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 02727 02728 Actions.PopParsingClass(state); 02729 02730 ParsingClass *Victim = ClassStack.top(); 02731 ClassStack.pop(); 02732 if (Victim->TopLevelClass) { 02733 // Deallocate all of the nested classes of this class, 02734 // recursively: we don't need to keep any of this information. 02735 DeallocateParsedClasses(Victim); 02736 return; 02737 } 02738 assert(!ClassStack.empty() && "Missing top-level class?"); 02739 02740 if (Victim->LateParsedDeclarations.empty()) { 02741 // The victim is a nested class, but we will not need to perform 02742 // any processing after the definition of this class since it has 02743 // no members whose handling was delayed. Therefore, we can just 02744 // remove this nested class. 02745 DeallocateParsedClasses(Victim); 02746 return; 02747 } 02748 02749 // This nested class has some members that will need to be processed 02750 // after the top-level class is completely defined. Therefore, add 02751 // it to the list of nested classes within its parent. 02752 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); 02753 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim)); 02754 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); 02755 } 02756 02757 /// \brief Try to parse an 'identifier' which appears within an attribute-token. 02758 /// 02759 /// \return the parsed identifier on success, and 0 if the next token is not an 02760 /// attribute-token. 02761 /// 02762 /// C++11 [dcl.attr.grammar]p3: 02763 /// If a keyword or an alternative token that satisfies the syntactic 02764 /// requirements of an identifier is contained in an attribute-token, 02765 /// it is considered an identifier. 02766 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) { 02767 switch (Tok.getKind()) { 02768 default: 02769 // Identifiers and keywords have identifier info attached. 02770 if (IdentifierInfo *II = Tok.getIdentifierInfo()) { 02771 Loc = ConsumeToken(); 02772 return II; 02773 } 02774 return 0; 02775 02776 case tok::ampamp: // 'and' 02777 case tok::pipe: // 'bitor' 02778 case tok::pipepipe: // 'or' 02779 case tok::caret: // 'xor' 02780 case tok::tilde: // 'compl' 02781 case tok::amp: // 'bitand' 02782 case tok::ampequal: // 'and_eq' 02783 case tok::pipeequal: // 'or_eq' 02784 case tok::caretequal: // 'xor_eq' 02785 case tok::exclaim: // 'not' 02786 case tok::exclaimequal: // 'not_eq' 02787 // Alternative tokens do not have identifier info, but their spelling 02788 // starts with an alphabetical character. 02789 llvm::SmallString<8> SpellingBuf; 02790 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf); 02791 if (std::isalpha(Spelling[0])) { 02792 Loc = ConsumeToken(); 02793 return &PP.getIdentifierTable().get(Spelling); 02794 } 02795 return 0; 02796 } 02797 } 02798 02799 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently 02800 /// only parses standard attributes. 02801 /// 02802 /// [C++11] attribute-specifier: 02803 /// '[' '[' attribute-list ']' ']' 02804 /// alignment-specifier 02805 /// 02806 /// [C++11] attribute-list: 02807 /// attribute[opt] 02808 /// attribute-list ',' attribute[opt] 02809 /// attribute '...' 02810 /// attribute-list ',' attribute '...' 02811 /// 02812 /// [C++11] attribute: 02813 /// attribute-token attribute-argument-clause[opt] 02814 /// 02815 /// [C++11] attribute-token: 02816 /// identifier 02817 /// attribute-scoped-token 02818 /// 02819 /// [C++11] attribute-scoped-token: 02820 /// attribute-namespace '::' identifier 02821 /// 02822 /// [C++11] attribute-namespace: 02823 /// identifier 02824 /// 02825 /// [C++11] attribute-argument-clause: 02826 /// '(' balanced-token-seq ')' 02827 /// 02828 /// [C++11] balanced-token-seq: 02829 /// balanced-token 02830 /// balanced-token-seq balanced-token 02831 /// 02832 /// [C++11] balanced-token: 02833 /// '(' balanced-token-seq ')' 02834 /// '[' balanced-token-seq ']' 02835 /// '{' balanced-token-seq '}' 02836 /// any token but '(', ')', '[', ']', '{', or '}' 02837 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, 02838 SourceLocation *endLoc) { 02839 if (Tok.is(tok::kw_alignas)) { 02840 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas); 02841 ParseAlignmentSpecifier(attrs, endLoc); 02842 return; 02843 } 02844 02845 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) 02846 && "Not a C++11 attribute list"); 02847 02848 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute); 02849 02850 ConsumeBracket(); 02851 ConsumeBracket(); 02852 02853 while (Tok.isNot(tok::r_square)) { 02854 // attribute not present 02855 if (Tok.is(tok::comma)) { 02856 ConsumeToken(); 02857 continue; 02858 } 02859 02860 SourceLocation ScopeLoc, AttrLoc; 02861 IdentifierInfo *ScopeName = 0, *AttrName = 0; 02862 02863 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); 02864 if (!AttrName) 02865 // Break out to the "expected ']'" diagnostic. 02866 break; 02867 02868 // scoped attribute 02869 if (Tok.is(tok::coloncolon)) { 02870 ConsumeToken(); 02871 02872 ScopeName = AttrName; 02873 ScopeLoc = AttrLoc; 02874 02875 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); 02876 if (!AttrName) { 02877 Diag(Tok.getLocation(), diag::err_expected_ident); 02878 SkipUntil(tok::r_square, tok::comma, true, true); 02879 continue; 02880 } 02881 } 02882 02883 bool AttrParsed = false; 02884 switch (AttributeList::getKind(AttrName, ScopeName)) { 02885 // No arguments 02886 case AttributeList::AT_carries_dependency: 02887 // FIXME: implement generic support of attributes with C++11 syntax 02888 // see Parse/ParseDecl.cpp: ParseGNUAttributes 02889 case AttributeList::AT_clang___fallthrough: 02890 case AttributeList::AT_noreturn: { 02891 if (Tok.is(tok::l_paren)) { 02892 Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments) 02893 << AttrName->getName(); 02894 break; 02895 } 02896 02897 attrs.addNew(AttrName, 02898 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, 02899 AttrLoc), 02900 ScopeName, ScopeLoc, 0, 02901 SourceLocation(), 0, 0, false, true); 02902 AttrParsed = true; 02903 break; 02904 } 02905 02906 // Silence warnings 02907 default: break; 02908 } 02909 02910 // Skip the entire parameter clause, if any 02911 if (!AttrParsed && Tok.is(tok::l_paren)) { 02912 ConsumeParen(); 02913 // SkipUntil maintains the balancedness of tokens. 02914 SkipUntil(tok::r_paren, false); 02915 } 02916 02917 if (Tok.is(tok::ellipsis)) { 02918 if (AttrParsed) 02919 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) 02920 << AttrName->getName(); 02921 ConsumeToken(); 02922 } 02923 } 02924 02925 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 02926 SkipUntil(tok::r_square, false); 02927 if (endLoc) 02928 *endLoc = Tok.getLocation(); 02929 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 02930 SkipUntil(tok::r_square, false); 02931 } 02932 02933 /// ParseCXX11Attributes - Parse a C++0x attribute-specifier-seq. 02934 /// 02935 /// attribute-specifier-seq: 02936 /// attribute-specifier-seq[opt] attribute-specifier 02937 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs, 02938 SourceLocation *endLoc) { 02939 SourceLocation StartLoc = Tok.getLocation(), Loc; 02940 if (!endLoc) 02941 endLoc = &Loc; 02942 02943 do { 02944 ParseCXX11AttributeSpecifier(attrs, endLoc); 02945 } while (isCXX11AttributeSpecifier()); 02946 02947 attrs.Range = SourceRange(StartLoc, *endLoc); 02948 } 02949 02950 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr] 02951 /// 02952 /// [MS] ms-attribute: 02953 /// '[' token-seq ']' 02954 /// 02955 /// [MS] ms-attribute-seq: 02956 /// ms-attribute[opt] 02957 /// ms-attribute ms-attribute-seq 02958 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs, 02959 SourceLocation *endLoc) { 02960 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list"); 02961 02962 while (Tok.is(tok::l_square)) { 02963 // FIXME: If this is actually a C++11 attribute, parse it as one. 02964 ConsumeBracket(); 02965 SkipUntil(tok::r_square, true, true); 02966 if (endLoc) *endLoc = Tok.getLocation(); 02967 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); 02968 } 02969 } 02970 02971 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, 02972 AccessSpecifier& CurAS) { 02973 IfExistsCondition Result; 02974 if (ParseMicrosoftIfExistsCondition(Result)) 02975 return; 02976 02977 BalancedDelimiterTracker Braces(*this, tok::l_brace); 02978 if (Braces.consumeOpen()) { 02979 Diag(Tok, diag::err_expected_lbrace); 02980 return; 02981 } 02982 02983 switch (Result.Behavior) { 02984 case IEB_Parse: 02985 // Parse the declarations below. 02986 break; 02987 02988 case IEB_Dependent: 02989 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) 02990 << Result.IsIfExists; 02991 // Fall through to skip. 02992 02993 case IEB_Skip: 02994 Braces.skipToEnd(); 02995 return; 02996 } 02997 02998 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 02999 // __if_exists, __if_not_exists can nest. 03000 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) { 03001 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); 03002 continue; 03003 } 03004 03005 // Check for extraneous top-level semicolon. 03006 if (Tok.is(tok::semi)) { 03007 ConsumeExtraSemi(InsideStruct, 03008 DeclSpec::getSpecifierName((DeclSpec::TST)TagType)); 03009 continue; 03010 } 03011 03012 AccessSpecifier AS = getAccessSpecifierIfPresent(); 03013 if (AS != AS_none) { 03014 // Current token is a C++ access specifier. 03015 CurAS = AS; 03016 SourceLocation ASLoc = Tok.getLocation(); 03017 ConsumeToken(); 03018 if (Tok.is(tok::colon)) 03019 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); 03020 else 03021 Diag(Tok, diag::err_expected_colon); 03022 ConsumeToken(); 03023 continue; 03024 } 03025 03026 // Parse all the comma separated declarators. 03027 ParseCXXClassMemberDeclaration(CurAS, 0); 03028 } 03029 03030 Braces.consumeClose(); 03031 }