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