clang API Documentation
00001 //===--- ParseDecl.cpp - 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 Declaration portions of the Parser interfaces. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Parse/Parser.h" 00015 #include "clang/Parse/ParseDiagnostic.h" 00016 #include "clang/Basic/OpenCL.h" 00017 #include "clang/Sema/Lookup.h" 00018 #include "clang/Sema/Scope.h" 00019 #include "clang/Sema/ParsedTemplate.h" 00020 #include "clang/Sema/PrettyDeclStackTrace.h" 00021 #include "RAIIObjectsForParser.h" 00022 #include "llvm/ADT/SmallSet.h" 00023 #include "llvm/ADT/SmallString.h" 00024 #include "llvm/ADT/StringSwitch.h" 00025 using namespace clang; 00026 00027 //===----------------------------------------------------------------------===// 00028 // C99 6.7: Declarations. 00029 //===----------------------------------------------------------------------===// 00030 00031 /// ParseTypeName 00032 /// type-name: [C99 6.7.6] 00033 /// specifier-qualifier-list abstract-declarator[opt] 00034 /// 00035 /// Called type-id in C++. 00036 TypeResult Parser::ParseTypeName(SourceRange *Range, 00037 Declarator::TheContext Context, 00038 AccessSpecifier AS, 00039 Decl **OwnedType) { 00040 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context); 00041 if (DSC == DSC_normal) 00042 DSC = DSC_type_specifier; 00043 00044 // Parse the common declaration-specifiers piece. 00045 DeclSpec DS(AttrFactory); 00046 ParseSpecifierQualifierList(DS, AS, DSC); 00047 if (OwnedType) 00048 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0; 00049 00050 // Parse the abstract-declarator, if present. 00051 Declarator DeclaratorInfo(DS, Context); 00052 ParseDeclarator(DeclaratorInfo); 00053 if (Range) 00054 *Range = DeclaratorInfo.getSourceRange(); 00055 00056 if (DeclaratorInfo.isInvalidType()) 00057 return true; 00058 00059 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 00060 } 00061 00062 00063 /// isAttributeLateParsed - Return true if the attribute has arguments that 00064 /// require late parsing. 00065 static bool isAttributeLateParsed(const IdentifierInfo &II) { 00066 return llvm::StringSwitch<bool>(II.getName()) 00067 #include "clang/Parse/AttrLateParsed.inc" 00068 .Default(false); 00069 } 00070 00071 00072 /// ParseGNUAttributes - Parse a non-empty attributes list. 00073 /// 00074 /// [GNU] attributes: 00075 /// attribute 00076 /// attributes attribute 00077 /// 00078 /// [GNU] attribute: 00079 /// '__attribute__' '(' '(' attribute-list ')' ')' 00080 /// 00081 /// [GNU] attribute-list: 00082 /// attrib 00083 /// attribute_list ',' attrib 00084 /// 00085 /// [GNU] attrib: 00086 /// empty 00087 /// attrib-name 00088 /// attrib-name '(' identifier ')' 00089 /// attrib-name '(' identifier ',' nonempty-expr-list ')' 00090 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 00091 /// 00092 /// [GNU] attrib-name: 00093 /// identifier 00094 /// typespec 00095 /// typequal 00096 /// storageclass 00097 /// 00098 /// FIXME: The GCC grammar/code for this construct implies we need two 00099 /// token lookahead. Comment from gcc: "If they start with an identifier 00100 /// which is followed by a comma or close parenthesis, then the arguments 00101 /// start with that identifier; otherwise they are an expression list." 00102 /// 00103 /// GCC does not require the ',' between attribs in an attribute-list. 00104 /// 00105 /// At the moment, I am not doing 2 token lookahead. I am also unaware of 00106 /// any attributes that don't work (based on my limited testing). Most 00107 /// attributes are very simple in practice. Until we find a bug, I don't see 00108 /// a pressing need to implement the 2 token lookahead. 00109 00110 void Parser::ParseGNUAttributes(ParsedAttributes &attrs, 00111 SourceLocation *endLoc, 00112 LateParsedAttrList *LateAttrs) { 00113 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); 00114 00115 while (Tok.is(tok::kw___attribute)) { 00116 ConsumeToken(); 00117 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 00118 "attribute")) { 00119 SkipUntil(tok::r_paren, true); // skip until ) or ; 00120 return; 00121 } 00122 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 00123 SkipUntil(tok::r_paren, true); // skip until ) or ; 00124 return; 00125 } 00126 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 00127 while (Tok.is(tok::identifier) || isDeclarationSpecifier() || 00128 Tok.is(tok::comma)) { 00129 if (Tok.is(tok::comma)) { 00130 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,)) 00131 ConsumeToken(); 00132 continue; 00133 } 00134 // we have an identifier or declaration specifier (const, int, etc.) 00135 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00136 SourceLocation AttrNameLoc = ConsumeToken(); 00137 00138 if (Tok.is(tok::l_paren)) { 00139 // handle "parameterized" attributes 00140 if (LateAttrs && isAttributeLateParsed(*AttrName)) { 00141 LateParsedAttribute *LA = 00142 new LateParsedAttribute(this, *AttrName, AttrNameLoc); 00143 LateAttrs->push_back(LA); 00144 00145 // Attributes in a class are parsed at the end of the class, along 00146 // with other late-parsed declarations. 00147 if (!ClassStack.empty()) 00148 getCurrentClass().LateParsedDeclarations.push_back(LA); 00149 00150 // consume everything up to and including the matching right parens 00151 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false); 00152 00153 Token Eof; 00154 Eof.startToken(); 00155 Eof.setLocation(Tok.getLocation()); 00156 LA->Toks.push_back(Eof); 00157 } else { 00158 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc); 00159 } 00160 } else { 00161 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 00162 0, SourceLocation(), 0, 0); 00163 } 00164 } 00165 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 00166 SkipUntil(tok::r_paren, false); 00167 SourceLocation Loc = Tok.getLocation(); 00168 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 00169 SkipUntil(tok::r_paren, false); 00170 } 00171 if (endLoc) 00172 *endLoc = Loc; 00173 } 00174 } 00175 00176 00177 /// Parse the arguments to a parameterized GNU attribute 00178 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName, 00179 SourceLocation AttrNameLoc, 00180 ParsedAttributes &Attrs, 00181 SourceLocation *EndLoc) { 00182 00183 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 00184 00185 // Availability attributes have their own grammar. 00186 if (AttrName->isStr("availability")) { 00187 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc); 00188 return; 00189 } 00190 // Thread safety attributes fit into the FIXME case above, so we 00191 // just parse the arguments as a list of expressions 00192 if (IsThreadSafetyAttribute(AttrName->getName())) { 00193 ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc); 00194 return; 00195 } 00196 00197 ConsumeParen(); // ignore the left paren loc for now 00198 00199 IdentifierInfo *ParmName = 0; 00200 SourceLocation ParmLoc; 00201 bool BuiltinType = false; 00202 00203 switch (Tok.getKind()) { 00204 case tok::kw_char: 00205 case tok::kw_wchar_t: 00206 case tok::kw_char16_t: 00207 case tok::kw_char32_t: 00208 case tok::kw_bool: 00209 case tok::kw_short: 00210 case tok::kw_int: 00211 case tok::kw_long: 00212 case tok::kw___int64: 00213 case tok::kw___int128: 00214 case tok::kw_signed: 00215 case tok::kw_unsigned: 00216 case tok::kw_float: 00217 case tok::kw_double: 00218 case tok::kw_void: 00219 case tok::kw_typeof: 00220 // __attribute__(( vec_type_hint(char) )) 00221 // FIXME: Don't just discard the builtin type token. 00222 ConsumeToken(); 00223 BuiltinType = true; 00224 break; 00225 00226 case tok::identifier: 00227 ParmName = Tok.getIdentifierInfo(); 00228 ParmLoc = ConsumeToken(); 00229 break; 00230 00231 default: 00232 break; 00233 } 00234 00235 ExprVector ArgExprs(Actions); 00236 00237 if (!BuiltinType && 00238 (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) { 00239 // Eat the comma. 00240 if (ParmLoc.isValid()) 00241 ConsumeToken(); 00242 00243 // Parse the non-empty comma-separated list of expressions. 00244 while (1) { 00245 ExprResult ArgExpr(ParseAssignmentExpression()); 00246 if (ArgExpr.isInvalid()) { 00247 SkipUntil(tok::r_paren); 00248 return; 00249 } 00250 ArgExprs.push_back(ArgExpr.release()); 00251 if (Tok.isNot(tok::comma)) 00252 break; 00253 ConsumeToken(); // Eat the comma, move to the next argument 00254 } 00255 } 00256 else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) { 00257 if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<", 00258 tok::greater)) { 00259 while (Tok.is(tok::identifier)) { 00260 ConsumeToken(); 00261 if (Tok.is(tok::greater)) 00262 break; 00263 if (Tok.is(tok::comma)) { 00264 ConsumeToken(); 00265 continue; 00266 } 00267 } 00268 if (Tok.isNot(tok::greater)) 00269 Diag(Tok, diag::err_iboutletcollection_with_protocol); 00270 SkipUntil(tok::r_paren, false, true); // skip until ')' 00271 } 00272 } 00273 00274 SourceLocation RParen = Tok.getLocation(); 00275 if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 00276 AttributeList *attr = 00277 Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrNameLoc, 00278 ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size()); 00279 if (BuiltinType && attr->getKind() == AttributeList::AT_iboutletcollection) 00280 Diag(Tok, diag::err_iboutletcollection_builtintype); 00281 } 00282 } 00283 00284 00285 /// ParseMicrosoftDeclSpec - Parse an __declspec construct 00286 /// 00287 /// [MS] decl-specifier: 00288 /// __declspec ( extended-decl-modifier-seq ) 00289 /// 00290 /// [MS] extended-decl-modifier-seq: 00291 /// extended-decl-modifier[opt] 00292 /// extended-decl-modifier extended-decl-modifier-seq 00293 00294 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) { 00295 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 00296 00297 ConsumeToken(); 00298 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 00299 "declspec")) { 00300 SkipUntil(tok::r_paren, true); // skip until ) or ; 00301 return; 00302 } 00303 00304 while (Tok.getIdentifierInfo()) { 00305 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00306 SourceLocation AttrNameLoc = ConsumeToken(); 00307 00308 // FIXME: Remove this when we have proper __declspec(property()) support. 00309 // Just skip everything inside property(). 00310 if (AttrName->getName() == "property") { 00311 ConsumeParen(); 00312 SkipUntil(tok::r_paren); 00313 } 00314 if (Tok.is(tok::l_paren)) { 00315 ConsumeParen(); 00316 // FIXME: This doesn't parse __declspec(property(get=get_func_name)) 00317 // correctly. 00318 ExprResult ArgExpr(ParseAssignmentExpression()); 00319 if (!ArgExpr.isInvalid()) { 00320 Expr *ExprList = ArgExpr.take(); 00321 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 00322 SourceLocation(), &ExprList, 1, true); 00323 } 00324 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 00325 SkipUntil(tok::r_paren, false); 00326 } else { 00327 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 00328 0, SourceLocation(), 0, 0, true); 00329 } 00330 } 00331 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 00332 SkipUntil(tok::r_paren, false); 00333 return; 00334 } 00335 00336 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { 00337 // Treat these like attributes 00338 // FIXME: Allow Sema to distinguish between these and real attributes! 00339 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) || 00340 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) || 00341 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) || 00342 Tok.is(tok::kw___ptr32) || 00343 Tok.is(tok::kw___unaligned)) { 00344 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00345 SourceLocation AttrNameLoc = ConsumeToken(); 00346 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) || 00347 Tok.is(tok::kw___ptr32)) 00348 // FIXME: Support these properly! 00349 continue; 00350 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 00351 SourceLocation(), 0, 0, true); 00352 } 00353 } 00354 00355 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 00356 // Treat these like attributes 00357 while (Tok.is(tok::kw___pascal)) { 00358 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00359 SourceLocation AttrNameLoc = ConsumeToken(); 00360 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 00361 SourceLocation(), 0, 0, true); 00362 } 00363 } 00364 00365 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { 00366 // Treat these like attributes 00367 while (Tok.is(tok::kw___kernel)) { 00368 SourceLocation AttrNameLoc = ConsumeToken(); 00369 attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"), 00370 AttrNameLoc, 0, AttrNameLoc, 0, 00371 SourceLocation(), 0, 0, false); 00372 } 00373 } 00374 00375 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) { 00376 SourceLocation Loc = Tok.getLocation(); 00377 switch(Tok.getKind()) { 00378 // OpenCL qualifiers: 00379 case tok::kw___private: 00380 case tok::kw_private: 00381 DS.getAttributes().addNewInteger( 00382 Actions.getASTContext(), 00383 PP.getIdentifierInfo("address_space"), Loc, 0); 00384 break; 00385 00386 case tok::kw___global: 00387 DS.getAttributes().addNewInteger( 00388 Actions.getASTContext(), 00389 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global); 00390 break; 00391 00392 case tok::kw___local: 00393 DS.getAttributes().addNewInteger( 00394 Actions.getASTContext(), 00395 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local); 00396 break; 00397 00398 case tok::kw___constant: 00399 DS.getAttributes().addNewInteger( 00400 Actions.getASTContext(), 00401 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant); 00402 break; 00403 00404 case tok::kw___read_only: 00405 DS.getAttributes().addNewInteger( 00406 Actions.getASTContext(), 00407 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only); 00408 break; 00409 00410 case tok::kw___write_only: 00411 DS.getAttributes().addNewInteger( 00412 Actions.getASTContext(), 00413 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only); 00414 break; 00415 00416 case tok::kw___read_write: 00417 DS.getAttributes().addNewInteger( 00418 Actions.getASTContext(), 00419 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write); 00420 break; 00421 default: break; 00422 } 00423 } 00424 00425 /// \brief Parse a version number. 00426 /// 00427 /// version: 00428 /// simple-integer 00429 /// simple-integer ',' simple-integer 00430 /// simple-integer ',' simple-integer ',' simple-integer 00431 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { 00432 Range = Tok.getLocation(); 00433 00434 if (!Tok.is(tok::numeric_constant)) { 00435 Diag(Tok, diag::err_expected_version); 00436 SkipUntil(tok::comma, tok::r_paren, true, true, true); 00437 return VersionTuple(); 00438 } 00439 00440 // Parse the major (and possibly minor and subminor) versions, which 00441 // are stored in the numeric constant. We utilize a quirk of the 00442 // lexer, which is that it handles something like 1.2.3 as a single 00443 // numeric constant, rather than two separate tokens. 00444 SmallString<512> Buffer; 00445 Buffer.resize(Tok.getLength()+1); 00446 const char *ThisTokBegin = &Buffer[0]; 00447 00448 // Get the spelling of the token, which eliminates trigraphs, etc. 00449 bool Invalid = false; 00450 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 00451 if (Invalid) 00452 return VersionTuple(); 00453 00454 // Parse the major version. 00455 unsigned AfterMajor = 0; 00456 unsigned Major = 0; 00457 while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) { 00458 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; 00459 ++AfterMajor; 00460 } 00461 00462 if (AfterMajor == 0) { 00463 Diag(Tok, diag::err_expected_version); 00464 SkipUntil(tok::comma, tok::r_paren, true, true, true); 00465 return VersionTuple(); 00466 } 00467 00468 if (AfterMajor == ActualLength) { 00469 ConsumeToken(); 00470 00471 // We only had a single version component. 00472 if (Major == 0) { 00473 Diag(Tok, diag::err_zero_version); 00474 return VersionTuple(); 00475 } 00476 00477 return VersionTuple(Major); 00478 } 00479 00480 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) { 00481 Diag(Tok, diag::err_expected_version); 00482 SkipUntil(tok::comma, tok::r_paren, true, true, true); 00483 return VersionTuple(); 00484 } 00485 00486 // Parse the minor version. 00487 unsigned AfterMinor = AfterMajor + 1; 00488 unsigned Minor = 0; 00489 while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) { 00490 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; 00491 ++AfterMinor; 00492 } 00493 00494 if (AfterMinor == ActualLength) { 00495 ConsumeToken(); 00496 00497 // We had major.minor. 00498 if (Major == 0 && Minor == 0) { 00499 Diag(Tok, diag::err_zero_version); 00500 return VersionTuple(); 00501 } 00502 00503 return VersionTuple(Major, Minor); 00504 } 00505 00506 // If what follows is not a '.', we have a problem. 00507 if (ThisTokBegin[AfterMinor] != '.') { 00508 Diag(Tok, diag::err_expected_version); 00509 SkipUntil(tok::comma, tok::r_paren, true, true, true); 00510 return VersionTuple(); 00511 } 00512 00513 // Parse the subminor version. 00514 unsigned AfterSubminor = AfterMinor + 1; 00515 unsigned Subminor = 0; 00516 while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) { 00517 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; 00518 ++AfterSubminor; 00519 } 00520 00521 if (AfterSubminor != ActualLength) { 00522 Diag(Tok, diag::err_expected_version); 00523 SkipUntil(tok::comma, tok::r_paren, true, true, true); 00524 return VersionTuple(); 00525 } 00526 ConsumeToken(); 00527 return VersionTuple(Major, Minor, Subminor); 00528 } 00529 00530 /// \brief Parse the contents of the "availability" attribute. 00531 /// 00532 /// availability-attribute: 00533 /// 'availability' '(' platform ',' version-arg-list, opt-message')' 00534 /// 00535 /// platform: 00536 /// identifier 00537 /// 00538 /// version-arg-list: 00539 /// version-arg 00540 /// version-arg ',' version-arg-list 00541 /// 00542 /// version-arg: 00543 /// 'introduced' '=' version 00544 /// 'deprecated' '=' version 00545 /// 'obsoleted' = version 00546 /// 'unavailable' 00547 /// opt-message: 00548 /// 'message' '=' <string> 00549 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, 00550 SourceLocation AvailabilityLoc, 00551 ParsedAttributes &attrs, 00552 SourceLocation *endLoc) { 00553 SourceLocation PlatformLoc; 00554 IdentifierInfo *Platform = 0; 00555 00556 enum { Introduced, Deprecated, Obsoleted, Unknown }; 00557 AvailabilityChange Changes[Unknown]; 00558 ExprResult MessageExpr; 00559 00560 // Opening '('. 00561 BalancedDelimiterTracker T(*this, tok::l_paren); 00562 if (T.consumeOpen()) { 00563 Diag(Tok, diag::err_expected_lparen); 00564 return; 00565 } 00566 00567 // Parse the platform name, 00568 if (Tok.isNot(tok::identifier)) { 00569 Diag(Tok, diag::err_availability_expected_platform); 00570 SkipUntil(tok::r_paren); 00571 return; 00572 } 00573 Platform = Tok.getIdentifierInfo(); 00574 PlatformLoc = ConsumeToken(); 00575 00576 // Parse the ',' following the platform name. 00577 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren)) 00578 return; 00579 00580 // If we haven't grabbed the pointers for the identifiers 00581 // "introduced", "deprecated", and "obsoleted", do so now. 00582 if (!Ident_introduced) { 00583 Ident_introduced = PP.getIdentifierInfo("introduced"); 00584 Ident_deprecated = PP.getIdentifierInfo("deprecated"); 00585 Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); 00586 Ident_unavailable = PP.getIdentifierInfo("unavailable"); 00587 Ident_message = PP.getIdentifierInfo("message"); 00588 } 00589 00590 // Parse the set of introductions/deprecations/removals. 00591 SourceLocation UnavailableLoc; 00592 do { 00593 if (Tok.isNot(tok::identifier)) { 00594 Diag(Tok, diag::err_availability_expected_change); 00595 SkipUntil(tok::r_paren); 00596 return; 00597 } 00598 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 00599 SourceLocation KeywordLoc = ConsumeToken(); 00600 00601 if (Keyword == Ident_unavailable) { 00602 if (UnavailableLoc.isValid()) { 00603 Diag(KeywordLoc, diag::err_availability_redundant) 00604 << Keyword << SourceRange(UnavailableLoc); 00605 } 00606 UnavailableLoc = KeywordLoc; 00607 00608 if (Tok.isNot(tok::comma)) 00609 break; 00610 00611 ConsumeToken(); 00612 continue; 00613 } 00614 00615 if (Tok.isNot(tok::equal)) { 00616 Diag(Tok, diag::err_expected_equal_after) 00617 << Keyword; 00618 SkipUntil(tok::r_paren); 00619 return; 00620 } 00621 ConsumeToken(); 00622 if (Keyword == Ident_message) { 00623 if (!isTokenStringLiteral()) { 00624 Diag(Tok, diag::err_expected_string_literal); 00625 SkipUntil(tok::r_paren); 00626 return; 00627 } 00628 MessageExpr = ParseStringLiteralExpression(); 00629 break; 00630 } 00631 00632 SourceRange VersionRange; 00633 VersionTuple Version = ParseVersionTuple(VersionRange); 00634 00635 if (Version.empty()) { 00636 SkipUntil(tok::r_paren); 00637 return; 00638 } 00639 00640 unsigned Index; 00641 if (Keyword == Ident_introduced) 00642 Index = Introduced; 00643 else if (Keyword == Ident_deprecated) 00644 Index = Deprecated; 00645 else if (Keyword == Ident_obsoleted) 00646 Index = Obsoleted; 00647 else 00648 Index = Unknown; 00649 00650 if (Index < Unknown) { 00651 if (!Changes[Index].KeywordLoc.isInvalid()) { 00652 Diag(KeywordLoc, diag::err_availability_redundant) 00653 << Keyword 00654 << SourceRange(Changes[Index].KeywordLoc, 00655 Changes[Index].VersionRange.getEnd()); 00656 } 00657 00658 Changes[Index].KeywordLoc = KeywordLoc; 00659 Changes[Index].Version = Version; 00660 Changes[Index].VersionRange = VersionRange; 00661 } else { 00662 Diag(KeywordLoc, diag::err_availability_unknown_change) 00663 << Keyword << VersionRange; 00664 } 00665 00666 if (Tok.isNot(tok::comma)) 00667 break; 00668 00669 ConsumeToken(); 00670 } while (true); 00671 00672 // Closing ')'. 00673 if (T.consumeClose()) 00674 return; 00675 00676 if (endLoc) 00677 *endLoc = T.getCloseLocation(); 00678 00679 // The 'unavailable' availability cannot be combined with any other 00680 // availability changes. Make sure that hasn't happened. 00681 if (UnavailableLoc.isValid()) { 00682 bool Complained = false; 00683 for (unsigned Index = Introduced; Index != Unknown; ++Index) { 00684 if (Changes[Index].KeywordLoc.isValid()) { 00685 if (!Complained) { 00686 Diag(UnavailableLoc, diag::warn_availability_and_unavailable) 00687 << SourceRange(Changes[Index].KeywordLoc, 00688 Changes[Index].VersionRange.getEnd()); 00689 Complained = true; 00690 } 00691 00692 // Clear out the availability. 00693 Changes[Index] = AvailabilityChange(); 00694 } 00695 } 00696 } 00697 00698 // Record this attribute 00699 attrs.addNew(&Availability, 00700 SourceRange(AvailabilityLoc, T.getCloseLocation()), 00701 0, AvailabilityLoc, 00702 Platform, PlatformLoc, 00703 Changes[Introduced], 00704 Changes[Deprecated], 00705 Changes[Obsoleted], 00706 UnavailableLoc, MessageExpr.take(), 00707 false, false); 00708 } 00709 00710 00711 // Late Parsed Attributes: 00712 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods 00713 00714 void Parser::LateParsedDeclaration::ParseLexedAttributes() {} 00715 00716 void Parser::LateParsedClass::ParseLexedAttributes() { 00717 Self->ParseLexedAttributes(*Class); 00718 } 00719 00720 void Parser::LateParsedAttribute::ParseLexedAttributes() { 00721 Self->ParseLexedAttribute(*this, true, false); 00722 } 00723 00724 /// Wrapper class which calls ParseLexedAttribute, after setting up the 00725 /// scope appropriately. 00726 void Parser::ParseLexedAttributes(ParsingClass &Class) { 00727 // Deal with templates 00728 // FIXME: Test cases to make sure this does the right thing for templates. 00729 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 00730 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 00731 HasTemplateScope); 00732 if (HasTemplateScope) 00733 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 00734 00735 // Set or update the scope flags. 00736 bool AlreadyHasClassScope = Class.TopLevelClass; 00737 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; 00738 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 00739 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 00740 00741 // Enter the scope of nested classes 00742 if (!AlreadyHasClassScope) 00743 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), 00744 Class.TagOrTemplate); 00745 if (!Class.LateParsedDeclarations.empty()) { 00746 // Allow 'this' within late-parsed attributes. 00747 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate, 00748 /*TypeQuals=*/0); 00749 00750 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){ 00751 Class.LateParsedDeclarations[i]->ParseLexedAttributes(); 00752 } 00753 } 00754 00755 if (!AlreadyHasClassScope) 00756 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), 00757 Class.TagOrTemplate); 00758 } 00759 00760 00761 /// \brief Parse all attributes in LAs, and attach them to Decl D. 00762 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 00763 bool EnterScope, bool OnDefinition) { 00764 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { 00765 LAs[i]->addDecl(D); 00766 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); 00767 delete LAs[i]; 00768 } 00769 LAs.clear(); 00770 } 00771 00772 00773 /// \brief Finish parsing an attribute for which parsing was delayed. 00774 /// This will be called at the end of parsing a class declaration 00775 /// for each LateParsedAttribute. We consume the saved tokens and 00776 /// create an attribute with the arguments filled in. We add this 00777 /// to the Attribute list for the decl. 00778 void Parser::ParseLexedAttribute(LateParsedAttribute &LA, 00779 bool EnterScope, bool OnDefinition) { 00780 // Save the current token position. 00781 SourceLocation OrigLoc = Tok.getLocation(); 00782 00783 // Append the current token at the end of the new token stream so that it 00784 // doesn't get lost. 00785 LA.Toks.push_back(Tok); 00786 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false); 00787 // Consume the previously pushed token. 00788 ConsumeAnyToken(); 00789 00790 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) { 00791 Diag(Tok, diag::warn_attribute_on_function_definition) 00792 << LA.AttrName.getName(); 00793 } 00794 00795 ParsedAttributes Attrs(AttrFactory); 00796 SourceLocation endLoc; 00797 00798 if (LA.Decls.size() == 1) { 00799 Decl *D = LA.Decls[0]; 00800 00801 // If the Decl is templatized, add template parameters to scope. 00802 bool HasTemplateScope = EnterScope && D->isTemplateDecl(); 00803 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope); 00804 if (HasTemplateScope) 00805 Actions.ActOnReenterTemplateScope(Actions.CurScope, D); 00806 00807 // If the Decl is on a function, add function parameters to the scope. 00808 bool HasFunctionScope = EnterScope && D->isFunctionOrFunctionTemplate(); 00809 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunctionScope); 00810 if (HasFunctionScope) 00811 Actions.ActOnReenterFunctionContext(Actions.CurScope, D); 00812 00813 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc); 00814 00815 if (HasFunctionScope) { 00816 Actions.ActOnExitFunctionContext(); 00817 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver 00818 } 00819 if (HasTemplateScope) { 00820 TempScope.Exit(); 00821 } 00822 } else if (LA.Decls.size() > 0) { 00823 // If there are multiple decls, then the decl cannot be within the 00824 // function scope. 00825 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc); 00826 } else { 00827 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName(); 00828 } 00829 00830 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) { 00831 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs); 00832 } 00833 00834 if (Tok.getLocation() != OrigLoc) { 00835 // Due to a parsing error, we either went over the cached tokens or 00836 // there are still cached tokens left, so we skip the leftover tokens. 00837 // Since this is an uncommon situation that should be avoided, use the 00838 // expensive isBeforeInTranslationUnit call. 00839 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 00840 OrigLoc)) 00841 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof)) 00842 ConsumeAnyToken(); 00843 } 00844 } 00845 00846 /// \brief Wrapper around a case statement checking if AttrName is 00847 /// one of the thread safety attributes 00848 bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){ 00849 return llvm::StringSwitch<bool>(AttrName) 00850 .Case("guarded_by", true) 00851 .Case("guarded_var", true) 00852 .Case("pt_guarded_by", true) 00853 .Case("pt_guarded_var", true) 00854 .Case("lockable", true) 00855 .Case("scoped_lockable", true) 00856 .Case("no_thread_safety_analysis", true) 00857 .Case("acquired_after", true) 00858 .Case("acquired_before", true) 00859 .Case("exclusive_lock_function", true) 00860 .Case("shared_lock_function", true) 00861 .Case("exclusive_trylock_function", true) 00862 .Case("shared_trylock_function", true) 00863 .Case("unlock_function", true) 00864 .Case("lock_returned", true) 00865 .Case("locks_excluded", true) 00866 .Case("exclusive_locks_required", true) 00867 .Case("shared_locks_required", true) 00868 .Default(false); 00869 } 00870 00871 /// \brief Parse the contents of thread safety attributes. These 00872 /// should always be parsed as an expression list. 00873 /// 00874 /// We need to special case the parsing due to the fact that if the first token 00875 /// of the first argument is an identifier, the main parse loop will store 00876 /// that token as a "parameter" and the rest of 00877 /// the arguments will be added to a list of "arguments". However, 00878 /// subsequent tokens in the first argument are lost. We instead parse each 00879 /// argument as an expression and add all arguments to the list of "arguments". 00880 /// In future, we will take advantage of this special case to also 00881 /// deal with some argument scoping issues here (for example, referring to a 00882 /// function parameter in the attribute on that function). 00883 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName, 00884 SourceLocation AttrNameLoc, 00885 ParsedAttributes &Attrs, 00886 SourceLocation *EndLoc) { 00887 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 00888 00889 BalancedDelimiterTracker T(*this, tok::l_paren); 00890 T.consumeOpen(); 00891 00892 ExprVector ArgExprs(Actions); 00893 bool ArgExprsOk = true; 00894 00895 // now parse the list of expressions 00896 while (Tok.isNot(tok::r_paren)) { 00897 ExprResult ArgExpr(ParseAssignmentExpression()); 00898 if (ArgExpr.isInvalid()) { 00899 ArgExprsOk = false; 00900 T.consumeClose(); 00901 break; 00902 } else { 00903 ArgExprs.push_back(ArgExpr.release()); 00904 } 00905 if (Tok.isNot(tok::comma)) 00906 break; 00907 ConsumeToken(); // Eat the comma, move to the next argument 00908 } 00909 // Match the ')'. 00910 if (ArgExprsOk && !T.consumeClose()) { 00911 Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(), 00912 ArgExprs.take(), ArgExprs.size()); 00913 } 00914 if (EndLoc) 00915 *EndLoc = T.getCloseLocation(); 00916 } 00917 00918 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets 00919 /// of a C++11 attribute-specifier in a location where an attribute is not 00920 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this 00921 /// situation. 00922 /// 00923 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if 00924 /// this doesn't appear to actually be an attribute-specifier, and the caller 00925 /// should try to parse it. 00926 bool Parser::DiagnoseProhibitedCXX11Attribute() { 00927 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)); 00928 00929 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) { 00930 case CAK_NotAttributeSpecifier: 00931 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute. 00932 return false; 00933 00934 case CAK_InvalidAttributeSpecifier: 00935 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute); 00936 return false; 00937 00938 case CAK_AttributeSpecifier: 00939 // Parse and discard the attributes. 00940 SourceLocation BeginLoc = ConsumeBracket(); 00941 ConsumeBracket(); 00942 SkipUntil(tok::r_square, /*StopAtSemi*/ false); 00943 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied"); 00944 SourceLocation EndLoc = ConsumeBracket(); 00945 Diag(BeginLoc, diag::err_attributes_not_allowed) 00946 << SourceRange(BeginLoc, EndLoc); 00947 return true; 00948 } 00949 llvm_unreachable("All cases handled above."); 00950 } 00951 00952 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { 00953 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) 00954 << attrs.Range; 00955 } 00956 00957 /// ParseDeclaration - Parse a full 'declaration', which consists of 00958 /// declaration-specifiers, some number of declarators, and a semicolon. 00959 /// 'Context' should be a Declarator::TheContext value. This returns the 00960 /// location of the semicolon in DeclEnd. 00961 /// 00962 /// declaration: [C99 6.7] 00963 /// block-declaration -> 00964 /// simple-declaration 00965 /// others [FIXME] 00966 /// [C++] template-declaration 00967 /// [C++] namespace-definition 00968 /// [C++] using-directive 00969 /// [C++] using-declaration 00970 /// [C++11/C11] static_assert-declaration 00971 /// others... [FIXME] 00972 /// 00973 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts, 00974 unsigned Context, 00975 SourceLocation &DeclEnd, 00976 ParsedAttributesWithRange &attrs) { 00977 ParenBraceBracketBalancer BalancerRAIIObj(*this); 00978 // Must temporarily exit the objective-c container scope for 00979 // parsing c none objective-c decls. 00980 ObjCDeclContextSwitch ObjCDC(*this); 00981 00982 Decl *SingleDecl = 0; 00983 Decl *OwnedType = 0; 00984 switch (Tok.getKind()) { 00985 case tok::kw_template: 00986 case tok::kw_export: 00987 ProhibitAttributes(attrs); 00988 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 00989 break; 00990 case tok::kw_inline: 00991 // Could be the start of an inline namespace. Allowed as an ext in C++03. 00992 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) { 00993 ProhibitAttributes(attrs); 00994 SourceLocation InlineLoc = ConsumeToken(); 00995 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); 00996 break; 00997 } 00998 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, 00999 true); 01000 case tok::kw_namespace: 01001 ProhibitAttributes(attrs); 01002 SingleDecl = ParseNamespace(Context, DeclEnd); 01003 break; 01004 case tok::kw_using: 01005 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 01006 DeclEnd, attrs, &OwnedType); 01007 break; 01008 case tok::kw_static_assert: 01009 case tok::kw__Static_assert: 01010 ProhibitAttributes(attrs); 01011 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 01012 break; 01013 default: 01014 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true); 01015 } 01016 01017 // This routine returns a DeclGroup, if the thing we parsed only contains a 01018 // single decl, convert it now. Alias declarations can also declare a type; 01019 // include that too if it is present. 01020 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType); 01021 } 01022 01023 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 01024 /// declaration-specifiers init-declarator-list[opt] ';' 01025 ///[C90/C++]init-declarator-list ';' [TODO] 01026 /// [OMP] threadprivate-directive [TODO] 01027 /// 01028 /// for-range-declaration: [C++0x 6.5p1: stmt.ranged] 01029 /// attribute-specifier-seq[opt] type-specifier-seq declarator 01030 /// 01031 /// If RequireSemi is false, this does not check for a ';' at the end of the 01032 /// declaration. If it is true, it checks for and eats it. 01033 /// 01034 /// If FRI is non-null, we might be parsing a for-range-declaration instead 01035 /// of a simple-declaration. If we find that we are, we also parse the 01036 /// for-range-initializer, and place it here. 01037 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts, 01038 unsigned Context, 01039 SourceLocation &DeclEnd, 01040 ParsedAttributes &attrs, 01041 bool RequireSemi, 01042 ForRangeInit *FRI) { 01043 // Parse the common declaration-specifiers piece. 01044 ParsingDeclSpec DS(*this); 01045 DS.takeAttributesFrom(attrs); 01046 01047 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, 01048 getDeclSpecContextFromDeclaratorContext(Context)); 01049 01050 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 01051 // declaration-specifiers init-declarator-list[opt] ';' 01052 if (Tok.is(tok::semi)) { 01053 DeclEnd = Tok.getLocation(); 01054 if (RequireSemi) ConsumeToken(); 01055 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 01056 DS); 01057 DS.complete(TheDecl); 01058 return Actions.ConvertDeclToDeclGroup(TheDecl); 01059 } 01060 01061 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI); 01062 } 01063 01064 /// Returns true if this might be the start of a declarator, or a common typo 01065 /// for a declarator. 01066 bool Parser::MightBeDeclarator(unsigned Context) { 01067 switch (Tok.getKind()) { 01068 case tok::annot_cxxscope: 01069 case tok::annot_template_id: 01070 case tok::caret: 01071 case tok::code_completion: 01072 case tok::coloncolon: 01073 case tok::ellipsis: 01074 case tok::kw___attribute: 01075 case tok::kw_operator: 01076 case tok::l_paren: 01077 case tok::star: 01078 return true; 01079 01080 case tok::amp: 01081 case tok::ampamp: 01082 return getLangOpts().CPlusPlus; 01083 01084 case tok::l_square: // Might be an attribute on an unnamed bit-field. 01085 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus0x && 01086 NextToken().is(tok::l_square); 01087 01088 case tok::colon: // Might be a typo for '::' or an unnamed bit-field. 01089 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus; 01090 01091 case tok::identifier: 01092 switch (NextToken().getKind()) { 01093 case tok::code_completion: 01094 case tok::coloncolon: 01095 case tok::comma: 01096 case tok::equal: 01097 case tok::equalequal: // Might be a typo for '='. 01098 case tok::kw_alignas: 01099 case tok::kw_asm: 01100 case tok::kw___attribute: 01101 case tok::l_brace: 01102 case tok::l_paren: 01103 case tok::l_square: 01104 case tok::less: 01105 case tok::r_brace: 01106 case tok::r_paren: 01107 case tok::r_square: 01108 case tok::semi: 01109 return true; 01110 01111 case tok::colon: 01112 // At namespace scope, 'identifier:' is probably a typo for 'identifier::' 01113 // and in block scope it's probably a label. Inside a class definition, 01114 // this is a bit-field. 01115 return Context == Declarator::MemberContext || 01116 (getLangOpts().CPlusPlus && Context == Declarator::FileContext); 01117 01118 case tok::identifier: // Possible virt-specifier. 01119 return getLangOpts().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken()); 01120 01121 default: 01122 return false; 01123 } 01124 01125 default: 01126 return false; 01127 } 01128 } 01129 01130 /// Skip until we reach something which seems like a sensible place to pick 01131 /// up parsing after a malformed declaration. This will sometimes stop sooner 01132 /// than SkipUntil(tok::r_brace) would, but will never stop later. 01133 void Parser::SkipMalformedDecl() { 01134 while (true) { 01135 switch (Tok.getKind()) { 01136 case tok::l_brace: 01137 // Skip until matching }, then stop. We've probably skipped over 01138 // a malformed class or function definition or similar. 01139 ConsumeBrace(); 01140 SkipUntil(tok::r_brace, /*StopAtSemi*/false); 01141 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) { 01142 // This declaration isn't over yet. Keep skipping. 01143 continue; 01144 } 01145 if (Tok.is(tok::semi)) 01146 ConsumeToken(); 01147 return; 01148 01149 case tok::l_square: 01150 ConsumeBracket(); 01151 SkipUntil(tok::r_square, /*StopAtSemi*/false); 01152 continue; 01153 01154 case tok::l_paren: 01155 ConsumeParen(); 01156 SkipUntil(tok::r_paren, /*StopAtSemi*/false); 01157 continue; 01158 01159 case tok::r_brace: 01160 return; 01161 01162 case tok::semi: 01163 ConsumeToken(); 01164 return; 01165 01166 case tok::kw_inline: 01167 // 'inline namespace' at the start of a line is almost certainly 01168 // a good place to pick back up parsing. 01169 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace)) 01170 return; 01171 break; 01172 01173 case tok::kw_namespace: 01174 // 'namespace' at the start of a line is almost certainly a good 01175 // place to pick back up parsing. 01176 if (Tok.isAtStartOfLine()) 01177 return; 01178 break; 01179 01180 case tok::eof: 01181 return; 01182 01183 default: 01184 break; 01185 } 01186 01187 ConsumeAnyToken(); 01188 } 01189 } 01190 01191 /// ParseDeclGroup - Having concluded that this is either a function 01192 /// definition or a group of object declarations, actually parse the 01193 /// result. 01194 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 01195 unsigned Context, 01196 bool AllowFunctionDefinitions, 01197 SourceLocation *DeclEnd, 01198 ForRangeInit *FRI) { 01199 // Parse the first declarator. 01200 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); 01201 ParseDeclarator(D); 01202 01203 // Bail out if the first declarator didn't seem well-formed. 01204 if (!D.hasName() && !D.mayOmitIdentifier()) { 01205 SkipMalformedDecl(); 01206 return DeclGroupPtrTy(); 01207 } 01208 01209 // Save late-parsed attributes for now; they need to be parsed in the 01210 // appropriate function scope after the function Decl has been constructed. 01211 LateParsedAttrList LateParsedAttrs; 01212 if (D.isFunctionDeclarator()) 01213 MaybeParseGNUAttributes(D, &LateParsedAttrs); 01214 01215 // Check to see if we have a function *definition* which must have a body. 01216 if (AllowFunctionDefinitions && D.isFunctionDeclarator() && 01217 // Look at the next token to make sure that this isn't a function 01218 // declaration. We have to check this because __attribute__ might be the 01219 // start of a function definition in GCC-extended K&R C. 01220 !isDeclarationAfterDeclarator()) { 01221 01222 if (isStartOfFunctionDefinition(D)) { 01223 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 01224 Diag(Tok, diag::err_function_declared_typedef); 01225 01226 // Recover by treating the 'typedef' as spurious. 01227 DS.ClearStorageClassSpecs(); 01228 } 01229 01230 Decl *TheDecl = 01231 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs); 01232 return Actions.ConvertDeclToDeclGroup(TheDecl); 01233 } 01234 01235 if (isDeclarationSpecifier()) { 01236 // If there is an invalid declaration specifier right after the function 01237 // prototype, then we must be in a missing semicolon case where this isn't 01238 // actually a body. Just fall through into the code that handles it as a 01239 // prototype, and let the top-level code handle the erroneous declspec 01240 // where it would otherwise expect a comma or semicolon. 01241 } else { 01242 Diag(Tok, diag::err_expected_fn_body); 01243 SkipUntil(tok::semi); 01244 return DeclGroupPtrTy(); 01245 } 01246 } 01247 01248 if (ParseAsmAttributesAfterDeclarator(D)) 01249 return DeclGroupPtrTy(); 01250 01251 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we 01252 // must parse and analyze the for-range-initializer before the declaration is 01253 // analyzed. 01254 if (FRI && Tok.is(tok::colon)) { 01255 FRI->ColonLoc = ConsumeToken(); 01256 if (Tok.is(tok::l_brace)) 01257 FRI->RangeExpr = ParseBraceInitializer(); 01258 else 01259 FRI->RangeExpr = ParseExpression(); 01260 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 01261 Actions.ActOnCXXForRangeDecl(ThisDecl); 01262 Actions.FinalizeDeclaration(ThisDecl); 01263 D.complete(ThisDecl); 01264 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1); 01265 } 01266 01267 SmallVector<Decl *, 8> DeclsInGroup; 01268 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D); 01269 if (LateParsedAttrs.size() > 0) 01270 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false); 01271 D.complete(FirstDecl); 01272 if (FirstDecl) 01273 DeclsInGroup.push_back(FirstDecl); 01274 01275 bool ExpectSemi = Context != Declarator::ForContext; 01276 01277 // If we don't have a comma, it is either the end of the list (a ';') or an 01278 // error, bail out. 01279 while (Tok.is(tok::comma)) { 01280 SourceLocation CommaLoc = ConsumeToken(); 01281 01282 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) { 01283 // This comma was followed by a line-break and something which can't be 01284 // the start of a declarator. The comma was probably a typo for a 01285 // semicolon. 01286 Diag(CommaLoc, diag::err_expected_semi_declaration) 01287 << FixItHint::CreateReplacement(CommaLoc, ";"); 01288 ExpectSemi = false; 01289 break; 01290 } 01291 01292 // Parse the next declarator. 01293 D.clear(); 01294 D.setCommaLoc(CommaLoc); 01295 01296 // Accept attributes in an init-declarator. In the first declarator in a 01297 // declaration, these would be part of the declspec. In subsequent 01298 // declarators, they become part of the declarator itself, so that they 01299 // don't apply to declarators after *this* one. Examples: 01300 // short __attribute__((common)) var; -> declspec 01301 // short var __attribute__((common)); -> declarator 01302 // short x, __attribute__((common)) var; -> declarator 01303 MaybeParseGNUAttributes(D); 01304 01305 ParseDeclarator(D); 01306 if (!D.isInvalidType()) { 01307 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 01308 D.complete(ThisDecl); 01309 if (ThisDecl) 01310 DeclsInGroup.push_back(ThisDecl); 01311 } 01312 } 01313 01314 if (DeclEnd) 01315 *DeclEnd = Tok.getLocation(); 01316 01317 if (ExpectSemi && 01318 ExpectAndConsumeSemi(Context == Declarator::FileContext 01319 ? diag::err_invalid_token_after_toplevel_declarator 01320 : diag::err_expected_semi_declaration)) { 01321 // Okay, there was no semicolon and one was expected. If we see a 01322 // declaration specifier, just assume it was missing and continue parsing. 01323 // Otherwise things are very confused and we skip to recover. 01324 if (!isDeclarationSpecifier()) { 01325 SkipUntil(tok::r_brace, true, true); 01326 if (Tok.is(tok::semi)) 01327 ConsumeToken(); 01328 } 01329 } 01330 01331 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, 01332 DeclsInGroup.data(), 01333 DeclsInGroup.size()); 01334 } 01335 01336 /// Parse an optional simple-asm-expr and attributes, and attach them to a 01337 /// declarator. Returns true on an error. 01338 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) { 01339 // If a simple-asm-expr is present, parse it. 01340 if (Tok.is(tok::kw_asm)) { 01341 SourceLocation Loc; 01342 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 01343 if (AsmLabel.isInvalid()) { 01344 SkipUntil(tok::semi, true, true); 01345 return true; 01346 } 01347 01348 D.setAsmLabel(AsmLabel.release()); 01349 D.SetRangeEnd(Loc); 01350 } 01351 01352 MaybeParseGNUAttributes(D); 01353 return false; 01354 } 01355 01356 /// \brief Parse 'declaration' after parsing 'declaration-specifiers 01357 /// declarator'. This method parses the remainder of the declaration 01358 /// (including any attributes or initializer, among other things) and 01359 /// finalizes the declaration. 01360 /// 01361 /// init-declarator: [C99 6.7] 01362 /// declarator 01363 /// declarator '=' initializer 01364 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] 01365 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 01366 /// [C++] declarator initializer[opt] 01367 /// 01368 /// [C++] initializer: 01369 /// [C++] '=' initializer-clause 01370 /// [C++] '(' expression-list ')' 01371 /// [C++0x] '=' 'default' [TODO] 01372 /// [C++0x] '=' 'delete' 01373 /// [C++0x] braced-init-list 01374 /// 01375 /// According to the standard grammar, =default and =delete are function 01376 /// definitions, but that definitely doesn't fit with the parser here. 01377 /// 01378 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D, 01379 const ParsedTemplateInfo &TemplateInfo) { 01380 if (ParseAsmAttributesAfterDeclarator(D)) 01381 return 0; 01382 01383 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 01384 } 01385 01386 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D, 01387 const ParsedTemplateInfo &TemplateInfo) { 01388 // Inform the current actions module that we just parsed this declarator. 01389 Decl *ThisDecl = 0; 01390 switch (TemplateInfo.Kind) { 01391 case ParsedTemplateInfo::NonTemplate: 01392 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 01393 break; 01394 01395 case ParsedTemplateInfo::Template: 01396 case ParsedTemplateInfo::ExplicitSpecialization: 01397 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 01398 MultiTemplateParamsArg(Actions, 01399 TemplateInfo.TemplateParams->data(), 01400 TemplateInfo.TemplateParams->size()), 01401 D); 01402 break; 01403 01404 case ParsedTemplateInfo::ExplicitInstantiation: { 01405 DeclResult ThisRes 01406 = Actions.ActOnExplicitInstantiation(getCurScope(), 01407 TemplateInfo.ExternLoc, 01408 TemplateInfo.TemplateLoc, 01409 D); 01410 if (ThisRes.isInvalid()) { 01411 SkipUntil(tok::semi, true, true); 01412 return 0; 01413 } 01414 01415 ThisDecl = ThisRes.get(); 01416 break; 01417 } 01418 } 01419 01420 bool TypeContainsAuto = 01421 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 01422 01423 // Parse declarator '=' initializer. 01424 // If a '==' or '+=' is found, suggest a fixit to '='. 01425 if (isTokenEqualOrEqualTypo()) { 01426 ConsumeToken(); 01427 if (Tok.is(tok::kw_delete)) { 01428 if (D.isFunctionDeclarator()) 01429 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 01430 << 1 /* delete */; 01431 else 01432 Diag(ConsumeToken(), diag::err_deleted_non_function); 01433 } else if (Tok.is(tok::kw_default)) { 01434 if (D.isFunctionDeclarator()) 01435 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 01436 << 0 /* default */; 01437 else 01438 Diag(ConsumeToken(), diag::err_default_special_members); 01439 } else { 01440 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01441 EnterScope(0); 01442 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 01443 } 01444 01445 if (Tok.is(tok::code_completion)) { 01446 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 01447 cutOffParsing(); 01448 return 0; 01449 } 01450 01451 ExprResult Init(ParseInitializer()); 01452 01453 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01454 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01455 ExitScope(); 01456 } 01457 01458 if (Init.isInvalid()) { 01459 SkipUntil(tok::comma, true, true); 01460 Actions.ActOnInitializerError(ThisDecl); 01461 } else 01462 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 01463 /*DirectInit=*/false, TypeContainsAuto); 01464 } 01465 } else if (Tok.is(tok::l_paren)) { 01466 // Parse C++ direct initializer: '(' expression-list ')' 01467 BalancedDelimiterTracker T(*this, tok::l_paren); 01468 T.consumeOpen(); 01469 01470 ExprVector Exprs(Actions); 01471 CommaLocsTy CommaLocs; 01472 01473 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01474 EnterScope(0); 01475 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 01476 } 01477 01478 if (ParseExpressionList(Exprs, CommaLocs)) { 01479 SkipUntil(tok::r_paren); 01480 01481 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01482 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01483 ExitScope(); 01484 } 01485 } else { 01486 // Match the ')'. 01487 T.consumeClose(); 01488 01489 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 01490 "Unexpected number of commas!"); 01491 01492 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01493 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01494 ExitScope(); 01495 } 01496 01497 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(), 01498 T.getCloseLocation(), 01499 move_arg(Exprs)); 01500 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(), 01501 /*DirectInit=*/true, TypeContainsAuto); 01502 } 01503 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 01504 // Parse C++0x braced-init-list. 01505 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 01506 01507 if (D.getCXXScopeSpec().isSet()) { 01508 EnterScope(0); 01509 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 01510 } 01511 01512 ExprResult Init(ParseBraceInitializer()); 01513 01514 if (D.getCXXScopeSpec().isSet()) { 01515 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01516 ExitScope(); 01517 } 01518 01519 if (Init.isInvalid()) { 01520 Actions.ActOnInitializerError(ThisDecl); 01521 } else 01522 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 01523 /*DirectInit=*/true, TypeContainsAuto); 01524 01525 } else { 01526 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); 01527 } 01528 01529 Actions.FinalizeDeclaration(ThisDecl); 01530 01531 return ThisDecl; 01532 } 01533 01534 /// ParseSpecifierQualifierList 01535 /// specifier-qualifier-list: 01536 /// type-specifier specifier-qualifier-list[opt] 01537 /// type-qualifier specifier-qualifier-list[opt] 01538 /// [GNU] attributes specifier-qualifier-list[opt] 01539 /// 01540 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS, 01541 DeclSpecContext DSC) { 01542 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 01543 /// parse declaration-specifiers and complain about extra stuff. 01544 /// TODO: diagnose attribute-specifiers and alignment-specifiers. 01545 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC); 01546 01547 // Validate declspec for type-name. 01548 unsigned Specs = DS.getParsedSpecifiers(); 01549 if ((DSC == DSC_type_specifier || DSC == DSC_trailing) && 01550 !DS.hasTypeSpecifier()) { 01551 Diag(Tok, diag::err_expected_type); 01552 DS.SetTypeSpecError(); 01553 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 01554 !DS.hasAttributes()) { 01555 Diag(Tok, diag::err_typename_requires_specqual); 01556 if (!DS.hasTypeSpecifier()) 01557 DS.SetTypeSpecError(); 01558 } 01559 01560 // Issue diagnostic and remove storage class if present. 01561 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 01562 if (DS.getStorageClassSpecLoc().isValid()) 01563 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 01564 else 01565 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 01566 DS.ClearStorageClassSpecs(); 01567 } 01568 01569 // Issue diagnostic and remove function specfier if present. 01570 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 01571 if (DS.isInlineSpecified()) 01572 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 01573 if (DS.isVirtualSpecified()) 01574 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 01575 if (DS.isExplicitSpecified()) 01576 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 01577 DS.ClearFunctionSpecs(); 01578 } 01579 01580 // Issue diagnostic and remove constexpr specfier if present. 01581 if (DS.isConstexprSpecified()) { 01582 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr); 01583 DS.ClearConstexprSpec(); 01584 } 01585 } 01586 01587 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 01588 /// specified token is valid after the identifier in a declarator which 01589 /// immediately follows the declspec. For example, these things are valid: 01590 /// 01591 /// int x [ 4]; // direct-declarator 01592 /// int x ( int y); // direct-declarator 01593 /// int(int x ) // direct-declarator 01594 /// int x ; // simple-declaration 01595 /// int x = 17; // init-declarator-list 01596 /// int x , y; // init-declarator-list 01597 /// int x __asm__ ("foo"); // init-declarator-list 01598 /// int x : 4; // struct-declarator 01599 /// int x { 5}; // C++'0x unified initializers 01600 /// 01601 /// This is not, because 'x' does not immediately follow the declspec (though 01602 /// ')' happens to be valid anyway). 01603 /// int (x) 01604 /// 01605 static bool isValidAfterIdentifierInDeclarator(const Token &T) { 01606 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 01607 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 01608 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 01609 } 01610 01611 01612 /// ParseImplicitInt - This method is called when we have an non-typename 01613 /// identifier in a declspec (which normally terminates the decl spec) when 01614 /// the declspec has no type specifier. In this case, the declspec is either 01615 /// malformed or is "implicit int" (in K&R and C89). 01616 /// 01617 /// This method handles diagnosing this prettily and returns false if the 01618 /// declspec is done being processed. If it recovers and thinks there may be 01619 /// other pieces of declspec after it, it returns true. 01620 /// 01621 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 01622 const ParsedTemplateInfo &TemplateInfo, 01623 AccessSpecifier AS, DeclSpecContext DSC) { 01624 assert(Tok.is(tok::identifier) && "should have identifier"); 01625 01626 SourceLocation Loc = Tok.getLocation(); 01627 // If we see an identifier that is not a type name, we normally would 01628 // parse it as the identifer being declared. However, when a typename 01629 // is typo'd or the definition is not included, this will incorrectly 01630 // parse the typename as the identifier name and fall over misparsing 01631 // later parts of the diagnostic. 01632 // 01633 // As such, we try to do some look-ahead in cases where this would 01634 // otherwise be an "implicit-int" case to see if this is invalid. For 01635 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 01636 // an identifier with implicit int, we'd get a parse error because the 01637 // next token is obviously invalid for a type. Parse these as a case 01638 // with an invalid type specifier. 01639 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 01640 01641 // Since we know that this either implicit int (which is rare) or an 01642 // error, do lookahead to try to do better recovery. This never applies 01643 // within a type specifier. Outside of C++, we allow this even if the 01644 // language doesn't "officially" support implicit int -- we support 01645 // implicit int as an extension in C99 and C11. Allegedly, MS also 01646 // supports implicit int in C++ mode. 01647 if (DSC != DSC_type_specifier && DSC != DSC_trailing && 01648 (!getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt) && 01649 isValidAfterIdentifierInDeclarator(NextToken())) { 01650 // If this token is valid for implicit int, e.g. "static x = 4", then 01651 // we just avoid eating the identifier, so it will be parsed as the 01652 // identifier in the declarator. 01653 return false; 01654 } 01655 01656 if (getLangOpts().CPlusPlus && 01657 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 01658 // Don't require a type specifier if we have the 'auto' storage class 01659 // specifier in C++98 -- we'll promote it to a type specifier. 01660 return false; 01661 } 01662 01663 // Otherwise, if we don't consume this token, we are going to emit an 01664 // error anyway. Try to recover from various common problems. Check 01665 // to see if this was a reference to a tag name without a tag specified. 01666 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 01667 // 01668 // C++ doesn't need this, and isTagName doesn't take SS. 01669 if (SS == 0) { 01670 const char *TagName = 0, *FixitTagName = 0; 01671 tok::TokenKind TagKind = tok::unknown; 01672 01673 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 01674 default: break; 01675 case DeclSpec::TST_enum: 01676 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; 01677 case DeclSpec::TST_union: 01678 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; 01679 case DeclSpec::TST_struct: 01680 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; 01681 case DeclSpec::TST_class: 01682 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; 01683 } 01684 01685 if (TagName) { 01686 IdentifierInfo *TokenName = Tok.getIdentifierInfo(); 01687 LookupResult R(Actions, TokenName, SourceLocation(), 01688 Sema::LookupOrdinaryName); 01689 01690 Diag(Loc, diag::err_use_of_tag_name_without_tag) 01691 << TokenName << TagName << getLangOpts().CPlusPlus 01692 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); 01693 01694 if (Actions.LookupParsedName(R, getCurScope(), SS)) { 01695 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); 01696 I != IEnd; ++I) 01697 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 01698 << TokenName << TagName; 01699 } 01700 01701 // Parse this as a tag as if the missing tag were present. 01702 if (TagKind == tok::kw_enum) 01703 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal); 01704 else 01705 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS, 01706 /*EnteringContext*/ false, DSC_normal); 01707 return true; 01708 } 01709 } 01710 01711 // Determine whether this identifier could plausibly be the name of something 01712 // being declared (with a missing type). 01713 if (DSC != DSC_type_specifier && DSC != DSC_trailing && 01714 (!SS || DSC == DSC_top_level || DSC == DSC_class)) { 01715 // Look ahead to the next token to try to figure out what this declaration 01716 // was supposed to be. 01717 switch (NextToken().getKind()) { 01718 case tok::comma: 01719 case tok::equal: 01720 case tok::kw_asm: 01721 case tok::l_brace: 01722 case tok::l_square: 01723 case tok::semi: 01724 // This looks like a variable declaration. The type is probably missing. 01725 // We're done parsing decl-specifiers. 01726 return false; 01727 01728 case tok::l_paren: { 01729 // static x(4); // 'x' is not a type 01730 // x(int n); // 'x' is not a type 01731 // x (*p)[]; // 'x' is a type 01732 // 01733 // Since we're in an error case (or the rare 'implicit int in C++' MS 01734 // extension), we can afford to perform a tentative parse to determine 01735 // which case we're in. 01736 TentativeParsingAction PA(*this); 01737 ConsumeToken(); 01738 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false); 01739 PA.Revert(); 01740 if (TPR == TPResult::False()) 01741 return false; 01742 // The identifier is followed by a parenthesized declarator. 01743 // It's supposed to be a type. 01744 break; 01745 } 01746 01747 default: 01748 // This is probably supposed to be a type. This includes cases like: 01749 // int f(itn); 01750 // struct S { unsinged : 4; }; 01751 break; 01752 } 01753 } 01754 01755 // This is almost certainly an invalid type name. Let the action emit a 01756 // diagnostic and attempt to recover. 01757 ParsedType T; 01758 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc, 01759 getCurScope(), SS, T)) { 01760 // The action emitted a diagnostic, so we don't have to. 01761 if (T) { 01762 // The action has suggested that the type T could be used. Set that as 01763 // the type in the declaration specifiers, consume the would-be type 01764 // name token, and we're done. 01765 const char *PrevSpec; 01766 unsigned DiagID; 01767 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T); 01768 DS.SetRangeEnd(Tok.getLocation()); 01769 ConsumeToken(); 01770 01771 // There may be other declaration specifiers after this. 01772 return true; 01773 } 01774 01775 // Fall through; the action had no suggestion for us. 01776 } else { 01777 // The action did not emit a diagnostic, so emit one now. 01778 SourceRange R; 01779 if (SS) R = SS->getRange(); 01780 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; 01781 } 01782 01783 // Mark this as an error. 01784 DS.SetTypeSpecError(); 01785 DS.SetRangeEnd(Tok.getLocation()); 01786 ConsumeToken(); 01787 01788 // TODO: Could inject an invalid typedef decl in an enclosing scope to 01789 // avoid rippling error messages on subsequent uses of the same type, 01790 // could be useful if #include was forgotten. 01791 return false; 01792 } 01793 01794 /// \brief Determine the declaration specifier context from the declarator 01795 /// context. 01796 /// 01797 /// \param Context the declarator context, which is one of the 01798 /// Declarator::TheContext enumerator values. 01799 Parser::DeclSpecContext 01800 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 01801 if (Context == Declarator::MemberContext) 01802 return DSC_class; 01803 if (Context == Declarator::FileContext) 01804 return DSC_top_level; 01805 if (Context == Declarator::TrailingReturnContext) 01806 return DSC_trailing; 01807 return DSC_normal; 01808 } 01809 01810 /// ParseAlignArgument - Parse the argument to an alignment-specifier. 01811 /// 01812 /// FIXME: Simply returns an alignof() expression if the argument is a 01813 /// type. Ideally, the type should be propagated directly into Sema. 01814 /// 01815 /// [C11] type-id 01816 /// [C11] constant-expression 01817 /// [C++0x] type-id ...[opt] 01818 /// [C++0x] assignment-expression ...[opt] 01819 ExprResult Parser::ParseAlignArgument(SourceLocation Start, 01820 SourceLocation &EllipsisLoc) { 01821 ExprResult ER; 01822 if (isTypeIdInParens()) { 01823 SourceLocation TypeLoc = Tok.getLocation(); 01824 ParsedType Ty = ParseTypeName().get(); 01825 SourceRange TypeRange(Start, Tok.getLocation()); 01826 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, 01827 Ty.getAsOpaquePtr(), TypeRange); 01828 } else 01829 ER = ParseConstantExpression(); 01830 01831 if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis)) 01832 EllipsisLoc = ConsumeToken(); 01833 01834 return ER; 01835 } 01836 01837 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the 01838 /// attribute to Attrs. 01839 /// 01840 /// alignment-specifier: 01841 /// [C11] '_Alignas' '(' type-id ')' 01842 /// [C11] '_Alignas' '(' constant-expression ')' 01843 /// [C++0x] 'alignas' '(' type-id ...[opt] ')' 01844 /// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')' 01845 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs, 01846 SourceLocation *endLoc) { 01847 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) && 01848 "Not an alignment-specifier!"); 01849 01850 SourceLocation KWLoc = Tok.getLocation(); 01851 ConsumeToken(); 01852 01853 BalancedDelimiterTracker T(*this, tok::l_paren); 01854 if (T.expectAndConsume(diag::err_expected_lparen)) 01855 return; 01856 01857 SourceLocation EllipsisLoc; 01858 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc); 01859 if (ArgExpr.isInvalid()) { 01860 SkipUntil(tok::r_paren); 01861 return; 01862 } 01863 01864 T.consumeClose(); 01865 if (endLoc) 01866 *endLoc = T.getCloseLocation(); 01867 01868 // FIXME: Handle pack-expansions here. 01869 if (EllipsisLoc.isValid()) { 01870 Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported); 01871 return; 01872 } 01873 01874 ExprVector ArgExprs(Actions); 01875 ArgExprs.push_back(ArgExpr.release()); 01876 Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc, 01877 0, T.getOpenLocation(), ArgExprs.take(), 1, false, true); 01878 } 01879 01880 /// ParseDeclarationSpecifiers 01881 /// declaration-specifiers: [C99 6.7] 01882 /// storage-class-specifier declaration-specifiers[opt] 01883 /// type-specifier declaration-specifiers[opt] 01884 /// [C99] function-specifier declaration-specifiers[opt] 01885 /// [C11] alignment-specifier declaration-specifiers[opt] 01886 /// [GNU] attributes declaration-specifiers[opt] 01887 /// [Clang] '__module_private__' declaration-specifiers[opt] 01888 /// 01889 /// storage-class-specifier: [C99 6.7.1] 01890 /// 'typedef' 01891 /// 'extern' 01892 /// 'static' 01893 /// 'auto' 01894 /// 'register' 01895 /// [C++] 'mutable' 01896 /// [GNU] '__thread' 01897 /// function-specifier: [C99 6.7.4] 01898 /// [C99] 'inline' 01899 /// [C++] 'virtual' 01900 /// [C++] 'explicit' 01901 /// [OpenCL] '__kernel' 01902 /// 'friend': [C++ dcl.friend] 01903 /// 'constexpr': [C++0x dcl.constexpr] 01904 01905 /// 01906 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 01907 const ParsedTemplateInfo &TemplateInfo, 01908 AccessSpecifier AS, 01909 DeclSpecContext DSContext, 01910 LateParsedAttrList *LateAttrs) { 01911 if (DS.getSourceRange().isInvalid()) { 01912 DS.SetRangeStart(Tok.getLocation()); 01913 DS.SetRangeEnd(Tok.getLocation()); 01914 } 01915 01916 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); 01917 while (1) { 01918 bool isInvalid = false; 01919 const char *PrevSpec = 0; 01920 unsigned DiagID = 0; 01921 01922 SourceLocation Loc = Tok.getLocation(); 01923 01924 switch (Tok.getKind()) { 01925 default: 01926 DoneWithDeclSpec: 01927 // [C++0x] decl-specifier-seq: decl-specifier attribute-specifier-seq[opt] 01928 MaybeParseCXX0XAttributes(DS.getAttributes()); 01929 01930 // If this is not a declaration specifier token, we're done reading decl 01931 // specifiers. First verify that DeclSpec's are consistent. 01932 DS.Finish(Diags, PP); 01933 return; 01934 01935 case tok::code_completion: { 01936 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 01937 if (DS.hasTypeSpecifier()) { 01938 bool AllowNonIdentifiers 01939 = (getCurScope()->getFlags() & (Scope::ControlScope | 01940 Scope::BlockScope | 01941 Scope::TemplateParamScope | 01942 Scope::FunctionPrototypeScope | 01943 Scope::AtCatchScope)) == 0; 01944 bool AllowNestedNameSpecifiers 01945 = DSContext == DSC_top_level || 01946 (DSContext == DSC_class && DS.isFriendSpecified()); 01947 01948 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 01949 AllowNonIdentifiers, 01950 AllowNestedNameSpecifiers); 01951 return cutOffParsing(); 01952 } 01953 01954 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 01955 CCC = Sema::PCC_LocalDeclarationSpecifiers; 01956 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 01957 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 01958 : Sema::PCC_Template; 01959 else if (DSContext == DSC_class) 01960 CCC = Sema::PCC_Class; 01961 else if (CurParsedObjCImpl) 01962 CCC = Sema::PCC_ObjCImplementation; 01963 01964 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 01965 return cutOffParsing(); 01966 } 01967 01968 case tok::coloncolon: // ::foo::bar 01969 // C++ scope specifier. Annotate and loop, or bail out on error. 01970 if (TryAnnotateCXXScopeToken(true)) { 01971 if (!DS.hasTypeSpecifier()) 01972 DS.SetTypeSpecError(); 01973 goto DoneWithDeclSpec; 01974 } 01975 if (Tok.is(tok::coloncolon)) // ::new or ::delete 01976 goto DoneWithDeclSpec; 01977 continue; 01978 01979 case tok::annot_cxxscope: { 01980 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector()) 01981 goto DoneWithDeclSpec; 01982 01983 CXXScopeSpec SS; 01984 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 01985 Tok.getAnnotationRange(), 01986 SS); 01987 01988 // We are looking for a qualified typename. 01989 Token Next = NextToken(); 01990 if (Next.is(tok::annot_template_id) && 01991 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 01992 ->Kind == TNK_Type_template) { 01993 // We have a qualified template-id, e.g., N::A<int> 01994 01995 // C++ [class.qual]p2: 01996 // In a lookup in which the constructor is an acceptable lookup 01997 // result and the nested-name-specifier nominates a class C: 01998 // 01999 // - if the name specified after the 02000 // nested-name-specifier, when looked up in C, is the 02001 // injected-class-name of C (Clause 9), or 02002 // 02003 // - if the name specified after the nested-name-specifier 02004 // is the same as the identifier or the 02005 // simple-template-id's template-name in the last 02006 // component of the nested-name-specifier, 02007 // 02008 // the name is instead considered to name the constructor of 02009 // class C. 02010 // 02011 // Thus, if the template-name is actually the constructor 02012 // name, then the code is ill-formed; this interpretation is 02013 // reinforced by the NAD status of core issue 635. 02014 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 02015 if ((DSContext == DSC_top_level || 02016 (DSContext == DSC_class && DS.isFriendSpecified())) && 02017 TemplateId->Name && 02018 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 02019 if (isConstructorDeclarator()) { 02020 // The user meant this to be an out-of-line constructor 02021 // definition, but template arguments are not allowed 02022 // there. Just allow this as a constructor; we'll 02023 // complain about it later. 02024 goto DoneWithDeclSpec; 02025 } 02026 02027 // The user meant this to name a type, but it actually names 02028 // a constructor with some extraneous template 02029 // arguments. Complain, then parse it as a type as the user 02030 // intended. 02031 Diag(TemplateId->TemplateNameLoc, 02032 diag::err_out_of_line_template_id_names_constructor) 02033 << TemplateId->Name; 02034 } 02035 02036 DS.getTypeSpecScope() = SS; 02037 ConsumeToken(); // The C++ scope. 02038 assert(Tok.is(tok::annot_template_id) && 02039 "ParseOptionalCXXScopeSpecifier not working"); 02040 AnnotateTemplateIdTokenAsType(); 02041 continue; 02042 } 02043 02044 if (Next.is(tok::annot_typename)) { 02045 DS.getTypeSpecScope() = SS; 02046 ConsumeToken(); // The C++ scope. 02047 if (Tok.getAnnotationValue()) { 02048 ParsedType T = getTypeAnnotation(Tok); 02049 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 02050 Tok.getAnnotationEndLoc(), 02051 PrevSpec, DiagID, T); 02052 } 02053 else 02054 DS.SetTypeSpecError(); 02055 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 02056 ConsumeToken(); // The typename 02057 } 02058 02059 if (Next.isNot(tok::identifier)) 02060 goto DoneWithDeclSpec; 02061 02062 // If we're in a context where the identifier could be a class name, 02063 // check whether this is a constructor declaration. 02064 if ((DSContext == DSC_top_level || 02065 (DSContext == DSC_class && DS.isFriendSpecified())) && 02066 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 02067 &SS)) { 02068 if (isConstructorDeclarator()) 02069 goto DoneWithDeclSpec; 02070 02071 // As noted in C++ [class.qual]p2 (cited above), when the name 02072 // of the class is qualified in a context where it could name 02073 // a constructor, its a constructor name. However, we've 02074 // looked at the declarator, and the user probably meant this 02075 // to be a type. Complain that it isn't supposed to be treated 02076 // as a type, then proceed to parse it as a type. 02077 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 02078 << Next.getIdentifierInfo(); 02079 } 02080 02081 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 02082 Next.getLocation(), 02083 getCurScope(), &SS, 02084 false, false, ParsedType(), 02085 /*IsCtorOrDtorName=*/false, 02086 /*NonTrivialSourceInfo=*/true); 02087 02088 // If the referenced identifier is not a type, then this declspec is 02089 // erroneous: We already checked about that it has no type specifier, and 02090 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 02091 // typename. 02092 if (TypeRep == 0) { 02093 ConsumeToken(); // Eat the scope spec so the identifier is current. 02094 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) continue; 02095 goto DoneWithDeclSpec; 02096 } 02097 02098 DS.getTypeSpecScope() = SS; 02099 ConsumeToken(); // The C++ scope. 02100 02101 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 02102 DiagID, TypeRep); 02103 if (isInvalid) 02104 break; 02105 02106 DS.SetRangeEnd(Tok.getLocation()); 02107 ConsumeToken(); // The typename. 02108 02109 continue; 02110 } 02111 02112 case tok::annot_typename: { 02113 if (Tok.getAnnotationValue()) { 02114 ParsedType T = getTypeAnnotation(Tok); 02115 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 02116 DiagID, T); 02117 } else 02118 DS.SetTypeSpecError(); 02119 02120 if (isInvalid) 02121 break; 02122 02123 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 02124 ConsumeToken(); // The typename 02125 02126 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 02127 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 02128 // Objective-C interface. 02129 if (Tok.is(tok::less) && getLangOpts().ObjC1) 02130 ParseObjCProtocolQualifiers(DS); 02131 02132 continue; 02133 } 02134 02135 case tok::kw___is_signed: 02136 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang 02137 // typically treats it as a trait. If we see __is_signed as it appears 02138 // in libstdc++, e.g., 02139 // 02140 // static const bool __is_signed; 02141 // 02142 // then treat __is_signed as an identifier rather than as a keyword. 02143 if (DS.getTypeSpecType() == TST_bool && 02144 DS.getTypeQualifiers() == DeclSpec::TQ_const && 02145 DS.getStorageClassSpec() == DeclSpec::SCS_static) { 02146 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 02147 Tok.setKind(tok::identifier); 02148 } 02149 02150 // We're done with the declaration-specifiers. 02151 goto DoneWithDeclSpec; 02152 02153 // typedef-name 02154 case tok::kw_decltype: 02155 case tok::identifier: { 02156 // In C++, check to see if this is a scope specifier like foo::bar::, if 02157 // so handle it as such. This is important for ctor parsing. 02158 if (getLangOpts().CPlusPlus) { 02159 if (TryAnnotateCXXScopeToken(true)) { 02160 if (!DS.hasTypeSpecifier()) 02161 DS.SetTypeSpecError(); 02162 goto DoneWithDeclSpec; 02163 } 02164 if (!Tok.is(tok::identifier)) 02165 continue; 02166 } 02167 02168 // This identifier can only be a typedef name if we haven't already seen 02169 // a type-specifier. Without this check we misparse: 02170 // typedef int X; struct Y { short X; }; as 'short int'. 02171 if (DS.hasTypeSpecifier()) 02172 goto DoneWithDeclSpec; 02173 02174 // Check for need to substitute AltiVec keyword tokens. 02175 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 02176 break; 02177 02178 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not 02179 // allow the use of a typedef name as a type specifier. 02180 if (DS.isTypeAltiVecVector()) 02181 goto DoneWithDeclSpec; 02182 02183 ParsedType TypeRep = 02184 Actions.getTypeName(*Tok.getIdentifierInfo(), 02185 Tok.getLocation(), getCurScope()); 02186 02187 // If this is not a typedef name, don't parse it as part of the declspec, 02188 // it must be an implicit int or an error. 02189 if (!TypeRep) { 02190 if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue; 02191 goto DoneWithDeclSpec; 02192 } 02193 02194 // If we're in a context where the identifier could be a class name, 02195 // check whether this is a constructor declaration. 02196 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 02197 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 02198 isConstructorDeclarator()) 02199 goto DoneWithDeclSpec; 02200 02201 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 02202 DiagID, TypeRep); 02203 if (isInvalid) 02204 break; 02205 02206 DS.SetRangeEnd(Tok.getLocation()); 02207 ConsumeToken(); // The identifier 02208 02209 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 02210 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 02211 // Objective-C interface. 02212 if (Tok.is(tok::less) && getLangOpts().ObjC1) 02213 ParseObjCProtocolQualifiers(DS); 02214 02215 // Need to support trailing type qualifiers (e.g. "id<p> const"). 02216 // If a type specifier follows, it will be diagnosed elsewhere. 02217 continue; 02218 } 02219 02220 // type-name 02221 case tok::annot_template_id: { 02222 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 02223 if (TemplateId->Kind != TNK_Type_template) { 02224 // This template-id does not refer to a type name, so we're 02225 // done with the type-specifiers. 02226 goto DoneWithDeclSpec; 02227 } 02228 02229 // If we're in a context where the template-id could be a 02230 // constructor name or specialization, check whether this is a 02231 // constructor declaration. 02232 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 02233 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 02234 isConstructorDeclarator()) 02235 goto DoneWithDeclSpec; 02236 02237 // Turn the template-id annotation token into a type annotation 02238 // token, then try again to parse it as a type-specifier. 02239 AnnotateTemplateIdTokenAsType(); 02240 continue; 02241 } 02242 02243 // GNU attributes support. 02244 case tok::kw___attribute: 02245 ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs); 02246 continue; 02247 02248 // Microsoft declspec support. 02249 case tok::kw___declspec: 02250 ParseMicrosoftDeclSpec(DS.getAttributes()); 02251 continue; 02252 02253 // Microsoft single token adornments. 02254 case tok::kw___forceinline: 02255 // FIXME: Add handling here! 02256 break; 02257 02258 case tok::kw___ptr64: 02259 case tok::kw___ptr32: 02260 case tok::kw___w64: 02261 case tok::kw___cdecl: 02262 case tok::kw___stdcall: 02263 case tok::kw___fastcall: 02264 case tok::kw___thiscall: 02265 case tok::kw___unaligned: 02266 ParseMicrosoftTypeAttributes(DS.getAttributes()); 02267 continue; 02268 02269 // Borland single token adornments. 02270 case tok::kw___pascal: 02271 ParseBorlandTypeAttributes(DS.getAttributes()); 02272 continue; 02273 02274 // OpenCL single token adornments. 02275 case tok::kw___kernel: 02276 ParseOpenCLAttributes(DS.getAttributes()); 02277 continue; 02278 02279 // storage-class-specifier 02280 case tok::kw_typedef: 02281 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, 02282 PrevSpec, DiagID); 02283 break; 02284 case tok::kw_extern: 02285 if (DS.isThreadSpecified()) 02286 Diag(Tok, diag::ext_thread_before) << "extern"; 02287 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, 02288 PrevSpec, DiagID); 02289 break; 02290 case tok::kw___private_extern__: 02291 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, 02292 Loc, PrevSpec, DiagID); 02293 break; 02294 case tok::kw_static: 02295 if (DS.isThreadSpecified()) 02296 Diag(Tok, diag::ext_thread_before) << "static"; 02297 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, 02298 PrevSpec, DiagID); 02299 break; 02300 case tok::kw_auto: 02301 if (getLangOpts().CPlusPlus0x) { 02302 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 02303 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 02304 PrevSpec, DiagID); 02305 if (!isInvalid) 02306 Diag(Tok, diag::ext_auto_storage_class) 02307 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 02308 } else 02309 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 02310 DiagID); 02311 } else 02312 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 02313 PrevSpec, DiagID); 02314 break; 02315 case tok::kw_register: 02316 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, 02317 PrevSpec, DiagID); 02318 break; 02319 case tok::kw_mutable: 02320 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, 02321 PrevSpec, DiagID); 02322 break; 02323 case tok::kw___thread: 02324 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 02325 break; 02326 02327 // function-specifier 02328 case tok::kw_inline: 02329 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 02330 break; 02331 case tok::kw_virtual: 02332 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 02333 break; 02334 case tok::kw_explicit: 02335 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 02336 break; 02337 02338 // alignment-specifier 02339 case tok::kw__Alignas: 02340 if (!getLangOpts().C11) 02341 Diag(Tok, diag::ext_c11_alignas); 02342 ParseAlignmentSpecifier(DS.getAttributes()); 02343 continue; 02344 02345 // friend 02346 case tok::kw_friend: 02347 if (DSContext == DSC_class) 02348 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 02349 else { 02350 PrevSpec = ""; // not actually used by the diagnostic 02351 DiagID = diag::err_friend_invalid_in_context; 02352 isInvalid = true; 02353 } 02354 break; 02355 02356 // Modules 02357 case tok::kw___module_private__: 02358 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); 02359 break; 02360 02361 // constexpr 02362 case tok::kw_constexpr: 02363 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 02364 break; 02365 02366 // type-specifier 02367 case tok::kw_short: 02368 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 02369 DiagID); 02370 break; 02371 case tok::kw_long: 02372 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 02373 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 02374 DiagID); 02375 else 02376 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 02377 DiagID); 02378 break; 02379 case tok::kw___int64: 02380 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 02381 DiagID); 02382 break; 02383 case tok::kw_signed: 02384 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 02385 DiagID); 02386 break; 02387 case tok::kw_unsigned: 02388 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 02389 DiagID); 02390 break; 02391 case tok::kw__Complex: 02392 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 02393 DiagID); 02394 break; 02395 case tok::kw__Imaginary: 02396 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 02397 DiagID); 02398 break; 02399 case tok::kw_void: 02400 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 02401 DiagID); 02402 break; 02403 case tok::kw_char: 02404 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 02405 DiagID); 02406 break; 02407 case tok::kw_int: 02408 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 02409 DiagID); 02410 break; 02411 case tok::kw___int128: 02412 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, 02413 DiagID); 02414 break; 02415 case tok::kw_half: 02416 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, 02417 DiagID); 02418 break; 02419 case tok::kw_float: 02420 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 02421 DiagID); 02422 break; 02423 case tok::kw_double: 02424 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 02425 DiagID); 02426 break; 02427 case tok::kw_wchar_t: 02428 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 02429 DiagID); 02430 break; 02431 case tok::kw_char16_t: 02432 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 02433 DiagID); 02434 break; 02435 case tok::kw_char32_t: 02436 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 02437 DiagID); 02438 break; 02439 case tok::kw_bool: 02440 case tok::kw__Bool: 02441 if (Tok.is(tok::kw_bool) && 02442 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 02443 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 02444 PrevSpec = ""; // Not used by the diagnostic. 02445 DiagID = diag::err_bool_redeclaration; 02446 // For better error recovery. 02447 Tok.setKind(tok::identifier); 02448 isInvalid = true; 02449 } else { 02450 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 02451 DiagID); 02452 } 02453 break; 02454 case tok::kw__Decimal32: 02455 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 02456 DiagID); 02457 break; 02458 case tok::kw__Decimal64: 02459 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 02460 DiagID); 02461 break; 02462 case tok::kw__Decimal128: 02463 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 02464 DiagID); 02465 break; 02466 case tok::kw___vector: 02467 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 02468 break; 02469 case tok::kw___pixel: 02470 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 02471 break; 02472 case tok::kw___unknown_anytype: 02473 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 02474 PrevSpec, DiagID); 02475 break; 02476 02477 // class-specifier: 02478 case tok::kw_class: 02479 case tok::kw_struct: 02480 case tok::kw_union: { 02481 tok::TokenKind Kind = Tok.getKind(); 02482 ConsumeToken(); 02483 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, 02484 EnteringContext, DSContext); 02485 continue; 02486 } 02487 02488 // enum-specifier: 02489 case tok::kw_enum: 02490 ConsumeToken(); 02491 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); 02492 continue; 02493 02494 // cv-qualifier: 02495 case tok::kw_const: 02496 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 02497 getLangOpts()); 02498 break; 02499 case tok::kw_volatile: 02500 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 02501 getLangOpts()); 02502 break; 02503 case tok::kw_restrict: 02504 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 02505 getLangOpts()); 02506 break; 02507 02508 // C++ typename-specifier: 02509 case tok::kw_typename: 02510 if (TryAnnotateTypeOrScopeToken()) { 02511 DS.SetTypeSpecError(); 02512 goto DoneWithDeclSpec; 02513 } 02514 if (!Tok.is(tok::kw_typename)) 02515 continue; 02516 break; 02517 02518 // GNU typeof support. 02519 case tok::kw_typeof: 02520 ParseTypeofSpecifier(DS); 02521 continue; 02522 02523 case tok::annot_decltype: 02524 ParseDecltypeSpecifier(DS); 02525 continue; 02526 02527 case tok::kw___underlying_type: 02528 ParseUnderlyingTypeSpecifier(DS); 02529 continue; 02530 02531 case tok::kw__Atomic: 02532 ParseAtomicSpecifier(DS); 02533 continue; 02534 02535 // OpenCL qualifiers: 02536 case tok::kw_private: 02537 if (!getLangOpts().OpenCL) 02538 goto DoneWithDeclSpec; 02539 case tok::kw___private: 02540 case tok::kw___global: 02541 case tok::kw___local: 02542 case tok::kw___constant: 02543 case tok::kw___read_only: 02544 case tok::kw___write_only: 02545 case tok::kw___read_write: 02546 ParseOpenCLQualifiers(DS); 02547 break; 02548 02549 case tok::less: 02550 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 02551 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 02552 // but we support it. 02553 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) 02554 goto DoneWithDeclSpec; 02555 02556 if (!ParseObjCProtocolQualifiers(DS)) 02557 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 02558 << FixItHint::CreateInsertion(Loc, "id") 02559 << SourceRange(Loc, DS.getSourceRange().getEnd()); 02560 02561 // Need to support trailing type qualifiers (e.g. "id<p> const"). 02562 // If a type specifier follows, it will be diagnosed elsewhere. 02563 continue; 02564 } 02565 // If the specifier wasn't legal, issue a diagnostic. 02566 if (isInvalid) { 02567 assert(PrevSpec && "Method did not return previous specifier!"); 02568 assert(DiagID); 02569 02570 if (DiagID == diag::ext_duplicate_declspec) 02571 Diag(Tok, DiagID) 02572 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 02573 else 02574 Diag(Tok, DiagID) << PrevSpec; 02575 } 02576 02577 DS.SetRangeEnd(Tok.getLocation()); 02578 if (DiagID != diag::err_bool_redeclaration) 02579 ConsumeToken(); 02580 } 02581 } 02582 02583 /// ParseStructDeclaration - Parse a struct declaration without the terminating 02584 /// semicolon. 02585 /// 02586 /// struct-declaration: 02587 /// specifier-qualifier-list struct-declarator-list 02588 /// [GNU] __extension__ struct-declaration 02589 /// [GNU] specifier-qualifier-list 02590 /// struct-declarator-list: 02591 /// struct-declarator 02592 /// struct-declarator-list ',' struct-declarator 02593 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 02594 /// struct-declarator: 02595 /// declarator 02596 /// [GNU] declarator attributes[opt] 02597 /// declarator[opt] ':' constant-expression 02598 /// [GNU] declarator[opt] ':' constant-expression attributes[opt] 02599 /// 02600 void Parser:: 02601 ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 02602 02603 if (Tok.is(tok::kw___extension__)) { 02604 // __extension__ silences extension warnings in the subexpression. 02605 ExtensionRAIIObject O(Diags); // Use RAII to do this. 02606 ConsumeToken(); 02607 return ParseStructDeclaration(DS, Fields); 02608 } 02609 02610 // Parse the common specifier-qualifiers-list piece. 02611 ParseSpecifierQualifierList(DS); 02612 02613 // If there are no declarators, this is a free-standing declaration 02614 // specifier. Let the actions module cope with it. 02615 if (Tok.is(tok::semi)) { 02616 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); 02617 return; 02618 } 02619 02620 // Read struct-declarators until we find the semicolon. 02621 bool FirstDeclarator = true; 02622 SourceLocation CommaLoc; 02623 while (1) { 02624 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 02625 FieldDeclarator DeclaratorInfo(DS); 02626 DeclaratorInfo.D.setCommaLoc(CommaLoc); 02627 02628 // Attributes are only allowed here on successive declarators. 02629 if (!FirstDeclarator) 02630 MaybeParseGNUAttributes(DeclaratorInfo.D); 02631 02632 /// struct-declarator: declarator 02633 /// struct-declarator: declarator[opt] ':' constant-expression 02634 if (Tok.isNot(tok::colon)) { 02635 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 02636 ColonProtectionRAIIObject X(*this); 02637 ParseDeclarator(DeclaratorInfo.D); 02638 } 02639 02640 if (Tok.is(tok::colon)) { 02641 ConsumeToken(); 02642 ExprResult Res(ParseConstantExpression()); 02643 if (Res.isInvalid()) 02644 SkipUntil(tok::semi, true, true); 02645 else 02646 DeclaratorInfo.BitfieldSize = Res.release(); 02647 } 02648 02649 // If attributes exist after the declarator, parse them. 02650 MaybeParseGNUAttributes(DeclaratorInfo.D); 02651 02652 // We're done with this declarator; invoke the callback. 02653 Decl *D = Fields.invoke(DeclaratorInfo); 02654 PD.complete(D); 02655 02656 // If we don't have a comma, it is either the end of the list (a ';') 02657 // or an error, bail out. 02658 if (Tok.isNot(tok::comma)) 02659 return; 02660 02661 // Consume the comma. 02662 CommaLoc = ConsumeToken(); 02663 02664 FirstDeclarator = false; 02665 } 02666 } 02667 02668 /// ParseStructUnionBody 02669 /// struct-contents: 02670 /// struct-declaration-list 02671 /// [EXT] empty 02672 /// [GNU] "struct-declaration-list" without terminatoring ';' 02673 /// struct-declaration-list: 02674 /// struct-declaration 02675 /// struct-declaration-list struct-declaration 02676 /// [OBC] '@' 'defs' '(' class-name ')' 02677 /// 02678 void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 02679 unsigned TagType, Decl *TagDecl) { 02680 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 02681 "parsing struct/union body"); 02682 02683 BalancedDelimiterTracker T(*this, tok::l_brace); 02684 if (T.consumeOpen()) 02685 return; 02686 02687 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 02688 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 02689 02690 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 02691 // C++. 02692 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) { 02693 Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union); 02694 Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union); 02695 } 02696 02697 SmallVector<Decl *, 32> FieldDecls; 02698 02699 // While we still have something to read, read the declarations in the struct. 02700 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 02701 // Each iteration of this loop reads one struct-declaration. 02702 02703 // Check for extraneous top-level semicolon. 02704 if (Tok.is(tok::semi)) { 02705 ConsumeExtraSemi(InsideStruct, 02706 DeclSpec::getSpecifierName((DeclSpec::TST)TagType)); 02707 continue; 02708 } 02709 02710 // Parse all the comma separated declarators. 02711 DeclSpec DS(AttrFactory); 02712 02713 if (!Tok.is(tok::at)) { 02714 struct CFieldCallback : FieldCallback { 02715 Parser &P; 02716 Decl *TagDecl; 02717 SmallVectorImpl<Decl *> &FieldDecls; 02718 02719 CFieldCallback(Parser &P, Decl *TagDecl, 02720 SmallVectorImpl<Decl *> &FieldDecls) : 02721 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 02722 02723 virtual Decl *invoke(FieldDeclarator &FD) { 02724 // Install the declarator into the current TagDecl. 02725 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl, 02726 FD.D.getDeclSpec().getSourceRange().getBegin(), 02727 FD.D, FD.BitfieldSize); 02728 FieldDecls.push_back(Field); 02729 return Field; 02730 } 02731 } Callback(*this, TagDecl, FieldDecls); 02732 02733 ParseStructDeclaration(DS, Callback); 02734 } else { // Handle @defs 02735 ConsumeToken(); 02736 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 02737 Diag(Tok, diag::err_unexpected_at); 02738 SkipUntil(tok::semi, true); 02739 continue; 02740 } 02741 ConsumeToken(); 02742 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 02743 if (!Tok.is(tok::identifier)) { 02744 Diag(Tok, diag::err_expected_ident); 02745 SkipUntil(tok::semi, true); 02746 continue; 02747 } 02748 SmallVector<Decl *, 16> Fields; 02749 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 02750 Tok.getIdentifierInfo(), Fields); 02751 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 02752 ConsumeToken(); 02753 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 02754 } 02755 02756 if (Tok.is(tok::semi)) { 02757 ConsumeToken(); 02758 } else if (Tok.is(tok::r_brace)) { 02759 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 02760 break; 02761 } else { 02762 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 02763 // Skip to end of block or statement to avoid ext-warning on extra ';'. 02764 SkipUntil(tok::r_brace, true, true); 02765 // If we stopped at a ';', eat it. 02766 if (Tok.is(tok::semi)) ConsumeToken(); 02767 } 02768 } 02769 02770 T.consumeClose(); 02771 02772 ParsedAttributes attrs(AttrFactory); 02773 // If attributes exist after struct contents, parse them. 02774 MaybeParseGNUAttributes(attrs); 02775 02776 Actions.ActOnFields(getCurScope(), 02777 RecordLoc, TagDecl, FieldDecls, 02778 T.getOpenLocation(), T.getCloseLocation(), 02779 attrs.getList()); 02780 StructScope.Exit(); 02781 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 02782 T.getCloseLocation()); 02783 } 02784 02785 /// ParseEnumSpecifier 02786 /// enum-specifier: [C99 6.7.2.2] 02787 /// 'enum' identifier[opt] '{' enumerator-list '}' 02788 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 02789 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 02790 /// '}' attributes[opt] 02791 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] 02792 /// '}' 02793 /// 'enum' identifier 02794 /// [GNU] 'enum' attributes[opt] identifier 02795 /// 02796 /// [C++11] enum-head '{' enumerator-list[opt] '}' 02797 /// [C++11] enum-head '{' enumerator-list ',' '}' 02798 /// 02799 /// enum-head: [C++11] 02800 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] 02801 /// enum-key attribute-specifier-seq[opt] nested-name-specifier 02802 /// identifier enum-base[opt] 02803 /// 02804 /// enum-key: [C++11] 02805 /// 'enum' 02806 /// 'enum' 'class' 02807 /// 'enum' 'struct' 02808 /// 02809 /// enum-base: [C++11] 02810 /// ':' type-specifier-seq 02811 /// 02812 /// [C++] elaborated-type-specifier: 02813 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 02814 /// 02815 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 02816 const ParsedTemplateInfo &TemplateInfo, 02817 AccessSpecifier AS, DeclSpecContext DSC) { 02818 // Parse the tag portion of this. 02819 if (Tok.is(tok::code_completion)) { 02820 // Code completion for an enum name. 02821 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 02822 return cutOffParsing(); 02823 } 02824 02825 SourceLocation ScopedEnumKWLoc; 02826 bool IsScopedUsingClassTag = false; 02827 02828 if (getLangOpts().CPlusPlus0x && 02829 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) { 02830 Diag(Tok, diag::warn_cxx98_compat_scoped_enum); 02831 IsScopedUsingClassTag = Tok.is(tok::kw_class); 02832 ScopedEnumKWLoc = ConsumeToken(); 02833 } 02834 02835 // C++11 [temp.explicit]p12: 02836 // The usual access controls do not apply to names used to specify 02837 // explicit instantiations. 02838 // We extend this to also cover explicit specializations. Note that 02839 // we don't suppress if this turns out to be an elaborated type 02840 // specifier. 02841 bool shouldDelayDiagsInTag = 02842 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 02843 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 02844 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 02845 02846 // If attributes exist after tag, parse them. 02847 ParsedAttributes attrs(AttrFactory); 02848 MaybeParseGNUAttributes(attrs); 02849 02850 // If declspecs exist after tag, parse them. 02851 while (Tok.is(tok::kw___declspec)) 02852 ParseMicrosoftDeclSpec(attrs); 02853 02854 // Enum definitions should not be parsed in a trailing-return-type. 02855 bool AllowDeclaration = DSC != DSC_trailing; 02856 02857 bool AllowFixedUnderlyingType = AllowDeclaration && 02858 (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt || 02859 getLangOpts().ObjC2); 02860 02861 CXXScopeSpec &SS = DS.getTypeSpecScope(); 02862 if (getLangOpts().CPlusPlus) { 02863 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 02864 // if a fixed underlying type is allowed. 02865 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 02866 02867 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 02868 /*EnteringContext=*/false)) 02869 return; 02870 02871 if (SS.isSet() && Tok.isNot(tok::identifier)) { 02872 Diag(Tok, diag::err_expected_ident); 02873 if (Tok.isNot(tok::l_brace)) { 02874 // Has no name and is not a definition. 02875 // Skip the rest of this declarator, up until the comma or semicolon. 02876 SkipUntil(tok::comma, true); 02877 return; 02878 } 02879 } 02880 } 02881 02882 // Must have either 'enum name' or 'enum {...}'. 02883 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 02884 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { 02885 Diag(Tok, diag::err_expected_ident_lbrace); 02886 02887 // Skip the rest of this declarator, up until the comma or semicolon. 02888 SkipUntil(tok::comma, true); 02889 return; 02890 } 02891 02892 // If an identifier is present, consume and remember it. 02893 IdentifierInfo *Name = 0; 02894 SourceLocation NameLoc; 02895 if (Tok.is(tok::identifier)) { 02896 Name = Tok.getIdentifierInfo(); 02897 NameLoc = ConsumeToken(); 02898 } 02899 02900 if (!Name && ScopedEnumKWLoc.isValid()) { 02901 // C++0x 7.2p2: The optional identifier shall not be omitted in the 02902 // declaration of a scoped enumeration. 02903 Diag(Tok, diag::err_scoped_enum_missing_identifier); 02904 ScopedEnumKWLoc = SourceLocation(); 02905 IsScopedUsingClassTag = false; 02906 } 02907 02908 // Okay, end the suppression area. We'll decide whether to emit the 02909 // diagnostics in a second. 02910 if (shouldDelayDiagsInTag) 02911 diagsFromTag.done(); 02912 02913 TypeResult BaseType; 02914 02915 // Parse the fixed underlying type. 02916 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 02917 bool PossibleBitfield = false; 02918 if (getCurScope()->getFlags() & Scope::ClassScope) { 02919 // If we're in class scope, this can either be an enum declaration with 02920 // an underlying type, or a declaration of a bitfield member. We try to 02921 // use a simple disambiguation scheme first to catch the common cases 02922 // (integer literal, sizeof); if it's still ambiguous, we then consider 02923 // anything that's a simple-type-specifier followed by '(' as an 02924 // expression. This suffices because function types are not valid 02925 // underlying types anyway. 02926 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 02927 // If the next token starts an expression, we know we're parsing a 02928 // bit-field. This is the common case. 02929 if (TPR == TPResult::True()) 02930 PossibleBitfield = true; 02931 // If the next token starts a type-specifier-seq, it may be either a 02932 // a fixed underlying type or the start of a function-style cast in C++; 02933 // lookahead one more token to see if it's obvious that we have a 02934 // fixed underlying type. 02935 else if (TPR == TPResult::False() && 02936 GetLookAheadToken(2).getKind() == tok::semi) { 02937 // Consume the ':'. 02938 ConsumeToken(); 02939 } else { 02940 // We have the start of a type-specifier-seq, so we have to perform 02941 // tentative parsing to determine whether we have an expression or a 02942 // type. 02943 TentativeParsingAction TPA(*this); 02944 02945 // Consume the ':'. 02946 ConsumeToken(); 02947 02948 // If we see a type specifier followed by an open-brace, we have an 02949 // ambiguity between an underlying type and a C++11 braced 02950 // function-style cast. Resolve this by always treating it as an 02951 // underlying type. 02952 // FIXME: The standard is not entirely clear on how to disambiguate in 02953 // this case. 02954 if ((getLangOpts().CPlusPlus && 02955 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) || 02956 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { 02957 // We'll parse this as a bitfield later. 02958 PossibleBitfield = true; 02959 TPA.Revert(); 02960 } else { 02961 // We have a type-specifier-seq. 02962 TPA.Commit(); 02963 } 02964 } 02965 } else { 02966 // Consume the ':'. 02967 ConsumeToken(); 02968 } 02969 02970 if (!PossibleBitfield) { 02971 SourceRange Range; 02972 BaseType = ParseTypeName(&Range); 02973 02974 if (!getLangOpts().CPlusPlus0x && !getLangOpts().ObjC2) 02975 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type) 02976 << Range; 02977 if (getLangOpts().CPlusPlus0x) 02978 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 02979 } 02980 } 02981 02982 // There are four options here. If we have 'friend enum foo;' then this is a 02983 // friend declaration, and cannot have an accompanying definition. If we have 02984 // 'enum foo;', then this is a forward declaration. If we have 02985 // 'enum foo {...' then this is a definition. Otherwise we have something 02986 // like 'enum foo xyz', a reference. 02987 // 02988 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 02989 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 02990 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 02991 // 02992 Sema::TagUseKind TUK; 02993 if (!AllowDeclaration) { 02994 TUK = Sema::TUK_Reference; 02995 } else if (Tok.is(tok::l_brace)) { 02996 if (DS.isFriendSpecified()) { 02997 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 02998 << SourceRange(DS.getFriendSpecLoc()); 02999 ConsumeBrace(); 03000 SkipUntil(tok::r_brace); 03001 TUK = Sema::TUK_Friend; 03002 } else { 03003 TUK = Sema::TUK_Definition; 03004 } 03005 } else if (Tok.is(tok::semi) && DSC != DSC_type_specifier) { 03006 TUK = (DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration); 03007 } else { 03008 TUK = Sema::TUK_Reference; 03009 } 03010 03011 // If this is an elaborated type specifier, and we delayed 03012 // diagnostics before, just merge them into the current pool. 03013 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { 03014 diagsFromTag.redelay(); 03015 } 03016 03017 MultiTemplateParamsArg TParams; 03018 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 03019 TUK != Sema::TUK_Reference) { 03020 if (!getLangOpts().CPlusPlus0x || !SS.isSet()) { 03021 // Skip the rest of this declarator, up until the comma or semicolon. 03022 Diag(Tok, diag::err_enum_template); 03023 SkipUntil(tok::comma, true); 03024 return; 03025 } 03026 03027 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 03028 // Enumerations can't be explicitly instantiated. 03029 DS.SetTypeSpecError(); 03030 Diag(StartLoc, diag::err_explicit_instantiation_enum); 03031 return; 03032 } 03033 03034 assert(TemplateInfo.TemplateParams && "no template parameters"); 03035 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), 03036 TemplateInfo.TemplateParams->size()); 03037 } 03038 03039 if (!Name && TUK != Sema::TUK_Definition) { 03040 Diag(Tok, diag::err_enumerator_unnamed_no_def); 03041 03042 // Skip the rest of this declarator, up until the comma or semicolon. 03043 SkipUntil(tok::comma, true); 03044 return; 03045 } 03046 03047 bool Owned = false; 03048 bool IsDependent = false; 03049 const char *PrevSpec = 0; 03050 unsigned DiagID; 03051 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 03052 StartLoc, SS, Name, NameLoc, attrs.getList(), 03053 AS, DS.getModulePrivateSpecLoc(), TParams, 03054 Owned, IsDependent, ScopedEnumKWLoc, 03055 IsScopedUsingClassTag, BaseType); 03056 03057 if (IsDependent) { 03058 // This enum has a dependent nested-name-specifier. Handle it as a 03059 // dependent tag. 03060 if (!Name) { 03061 DS.SetTypeSpecError(); 03062 Diag(Tok, diag::err_expected_type_name_after_typename); 03063 return; 03064 } 03065 03066 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum, 03067 TUK, SS, Name, StartLoc, 03068 NameLoc); 03069 if (Type.isInvalid()) { 03070 DS.SetTypeSpecError(); 03071 return; 03072 } 03073 03074 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 03075 NameLoc.isValid() ? NameLoc : StartLoc, 03076 PrevSpec, DiagID, Type.get())) 03077 Diag(StartLoc, DiagID) << PrevSpec; 03078 03079 return; 03080 } 03081 03082 if (!TagDecl) { 03083 // The action failed to produce an enumeration tag. If this is a 03084 // definition, consume the entire definition. 03085 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 03086 ConsumeBrace(); 03087 SkipUntil(tok::r_brace); 03088 } 03089 03090 DS.SetTypeSpecError(); 03091 return; 03092 } 03093 03094 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 03095 ParseEnumBody(StartLoc, TagDecl); 03096 } 03097 03098 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 03099 NameLoc.isValid() ? NameLoc : StartLoc, 03100 PrevSpec, DiagID, TagDecl, Owned)) 03101 Diag(StartLoc, DiagID) << PrevSpec; 03102 } 03103 03104 /// ParseEnumBody - Parse a {} enclosed enumerator-list. 03105 /// enumerator-list: 03106 /// enumerator 03107 /// enumerator-list ',' enumerator 03108 /// enumerator: 03109 /// enumeration-constant 03110 /// enumeration-constant '=' constant-expression 03111 /// enumeration-constant: 03112 /// identifier 03113 /// 03114 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 03115 // Enter the scope of the enum body and start the definition. 03116 ParseScope EnumScope(this, Scope::DeclScope); 03117 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 03118 03119 BalancedDelimiterTracker T(*this, tok::l_brace); 03120 T.consumeOpen(); 03121 03122 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 03123 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) 03124 Diag(Tok, diag::error_empty_enum); 03125 03126 SmallVector<Decl *, 32> EnumConstantDecls; 03127 03128 Decl *LastEnumConstDecl = 0; 03129 03130 // Parse the enumerator-list. 03131 while (Tok.is(tok::identifier)) { 03132 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 03133 SourceLocation IdentLoc = ConsumeToken(); 03134 03135 // If attributes exist after the enumerator, parse them. 03136 ParsedAttributes attrs(AttrFactory); 03137 MaybeParseGNUAttributes(attrs); 03138 03139 SourceLocation EqualLoc; 03140 ExprResult AssignedVal; 03141 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 03142 03143 if (Tok.is(tok::equal)) { 03144 EqualLoc = ConsumeToken(); 03145 AssignedVal = ParseConstantExpression(); 03146 if (AssignedVal.isInvalid()) 03147 SkipUntil(tok::comma, tok::r_brace, true, true); 03148 } 03149 03150 // Install the enumerator constant into EnumDecl. 03151 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 03152 LastEnumConstDecl, 03153 IdentLoc, Ident, 03154 attrs.getList(), EqualLoc, 03155 AssignedVal.release()); 03156 PD.complete(EnumConstDecl); 03157 03158 EnumConstantDecls.push_back(EnumConstDecl); 03159 LastEnumConstDecl = EnumConstDecl; 03160 03161 if (Tok.is(tok::identifier)) { 03162 // We're missing a comma between enumerators. 03163 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 03164 Diag(Loc, diag::err_enumerator_list_missing_comma) 03165 << FixItHint::CreateInsertion(Loc, ", "); 03166 continue; 03167 } 03168 03169 if (Tok.isNot(tok::comma)) 03170 break; 03171 SourceLocation CommaLoc = ConsumeToken(); 03172 03173 if (Tok.isNot(tok::identifier)) { 03174 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x) 03175 Diag(CommaLoc, diag::ext_enumerator_list_comma) 03176 << getLangOpts().CPlusPlus 03177 << FixItHint::CreateRemoval(CommaLoc); 03178 else if (getLangOpts().CPlusPlus0x) 03179 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 03180 << FixItHint::CreateRemoval(CommaLoc); 03181 } 03182 } 03183 03184 // Eat the }. 03185 T.consumeClose(); 03186 03187 // If attributes exist after the identifier list, parse them. 03188 ParsedAttributes attrs(AttrFactory); 03189 MaybeParseGNUAttributes(attrs); 03190 03191 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), 03192 EnumDecl, EnumConstantDecls.data(), 03193 EnumConstantDecls.size(), getCurScope(), 03194 attrs.getList()); 03195 03196 EnumScope.Exit(); 03197 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, 03198 T.getCloseLocation()); 03199 } 03200 03201 /// isTypeSpecifierQualifier - Return true if the current token could be the 03202 /// start of a type-qualifier-list. 03203 bool Parser::isTypeQualifier() const { 03204 switch (Tok.getKind()) { 03205 default: return false; 03206 03207 // type-qualifier only in OpenCL 03208 case tok::kw_private: 03209 return getLangOpts().OpenCL; 03210 03211 // type-qualifier 03212 case tok::kw_const: 03213 case tok::kw_volatile: 03214 case tok::kw_restrict: 03215 case tok::kw___private: 03216 case tok::kw___local: 03217 case tok::kw___global: 03218 case tok::kw___constant: 03219 case tok::kw___read_only: 03220 case tok::kw___read_write: 03221 case tok::kw___write_only: 03222 return true; 03223 } 03224 } 03225 03226 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token 03227 /// is definitely a type-specifier. Return false if it isn't part of a type 03228 /// specifier or if we're not sure. 03229 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 03230 switch (Tok.getKind()) { 03231 default: return false; 03232 // type-specifiers 03233 case tok::kw_short: 03234 case tok::kw_long: 03235 case tok::kw___int64: 03236 case tok::kw___int128: 03237 case tok::kw_signed: 03238 case tok::kw_unsigned: 03239 case tok::kw__Complex: 03240 case tok::kw__Imaginary: 03241 case tok::kw_void: 03242 case tok::kw_char: 03243 case tok::kw_wchar_t: 03244 case tok::kw_char16_t: 03245 case tok::kw_char32_t: 03246 case tok::kw_int: 03247 case tok::kw_half: 03248 case tok::kw_float: 03249 case tok::kw_double: 03250 case tok::kw_bool: 03251 case tok::kw__Bool: 03252 case tok::kw__Decimal32: 03253 case tok::kw__Decimal64: 03254 case tok::kw__Decimal128: 03255 case tok::kw___vector: 03256 03257 // struct-or-union-specifier (C99) or class-specifier (C++) 03258 case tok::kw_class: 03259 case tok::kw_struct: 03260 case tok::kw_union: 03261 // enum-specifier 03262 case tok::kw_enum: 03263 03264 // typedef-name 03265 case tok::annot_typename: 03266 return true; 03267 } 03268 } 03269 03270 /// isTypeSpecifierQualifier - Return true if the current token could be the 03271 /// start of a specifier-qualifier-list. 03272 bool Parser::isTypeSpecifierQualifier() { 03273 switch (Tok.getKind()) { 03274 default: return false; 03275 03276 case tok::identifier: // foo::bar 03277 if (TryAltiVecVectorToken()) 03278 return true; 03279 // Fall through. 03280 case tok::kw_typename: // typename T::type 03281 // Annotate typenames and C++ scope specifiers. If we get one, just 03282 // recurse to handle whatever we get. 03283 if (TryAnnotateTypeOrScopeToken()) 03284 return true; 03285 if (Tok.is(tok::identifier)) 03286 return false; 03287 return isTypeSpecifierQualifier(); 03288 03289 case tok::coloncolon: // ::foo::bar 03290 if (NextToken().is(tok::kw_new) || // ::new 03291 NextToken().is(tok::kw_delete)) // ::delete 03292 return false; 03293 03294 if (TryAnnotateTypeOrScopeToken()) 03295 return true; 03296 return isTypeSpecifierQualifier(); 03297 03298 // GNU attributes support. 03299 case tok::kw___attribute: 03300 // GNU typeof support. 03301 case tok::kw_typeof: 03302 03303 // type-specifiers 03304 case tok::kw_short: 03305 case tok::kw_long: 03306 case tok::kw___int64: 03307 case tok::kw___int128: 03308 case tok::kw_signed: 03309 case tok::kw_unsigned: 03310 case tok::kw__Complex: 03311 case tok::kw__Imaginary: 03312 case tok::kw_void: 03313 case tok::kw_char: 03314 case tok::kw_wchar_t: 03315 case tok::kw_char16_t: 03316 case tok::kw_char32_t: 03317 case tok::kw_int: 03318 case tok::kw_half: 03319 case tok::kw_float: 03320 case tok::kw_double: 03321 case tok::kw_bool: 03322 case tok::kw__Bool: 03323 case tok::kw__Decimal32: 03324 case tok::kw__Decimal64: 03325 case tok::kw__Decimal128: 03326 case tok::kw___vector: 03327 03328 // struct-or-union-specifier (C99) or class-specifier (C++) 03329 case tok::kw_class: 03330 case tok::kw_struct: 03331 case tok::kw_union: 03332 // enum-specifier 03333 case tok::kw_enum: 03334 03335 // type-qualifier 03336 case tok::kw_const: 03337 case tok::kw_volatile: 03338 case tok::kw_restrict: 03339 03340 // typedef-name 03341 case tok::annot_typename: 03342 return true; 03343 03344 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 03345 case tok::less: 03346 return getLangOpts().ObjC1; 03347 03348 case tok::kw___cdecl: 03349 case tok::kw___stdcall: 03350 case tok::kw___fastcall: 03351 case tok::kw___thiscall: 03352 case tok::kw___w64: 03353 case tok::kw___ptr64: 03354 case tok::kw___ptr32: 03355 case tok::kw___pascal: 03356 case tok::kw___unaligned: 03357 03358 case tok::kw___private: 03359 case tok::kw___local: 03360 case tok::kw___global: 03361 case tok::kw___constant: 03362 case tok::kw___read_only: 03363 case tok::kw___read_write: 03364 case tok::kw___write_only: 03365 03366 return true; 03367 03368 case tok::kw_private: 03369 return getLangOpts().OpenCL; 03370 03371 // C11 _Atomic() 03372 case tok::kw__Atomic: 03373 return true; 03374 } 03375 } 03376 03377 /// isDeclarationSpecifier() - Return true if the current token is part of a 03378 /// declaration specifier. 03379 /// 03380 /// \param DisambiguatingWithExpression True to indicate that the purpose of 03381 /// this check is to disambiguate between an expression and a declaration. 03382 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 03383 switch (Tok.getKind()) { 03384 default: return false; 03385 03386 case tok::kw_private: 03387 return getLangOpts().OpenCL; 03388 03389 case tok::identifier: // foo::bar 03390 // Unfortunate hack to support "Class.factoryMethod" notation. 03391 if (getLangOpts().ObjC1 && NextToken().is(tok::period)) 03392 return false; 03393 if (TryAltiVecVectorToken()) 03394 return true; 03395 // Fall through. 03396 case tok::kw_decltype: // decltype(T())::type 03397 case tok::kw_typename: // typename T::type 03398 // Annotate typenames and C++ scope specifiers. If we get one, just 03399 // recurse to handle whatever we get. 03400 if (TryAnnotateTypeOrScopeToken()) 03401 return true; 03402 if (Tok.is(tok::identifier)) 03403 return false; 03404 03405 // If we're in Objective-C and we have an Objective-C class type followed 03406 // by an identifier and then either ':' or ']', in a place where an 03407 // expression is permitted, then this is probably a class message send 03408 // missing the initial '['. In this case, we won't consider this to be 03409 // the start of a declaration. 03410 if (DisambiguatingWithExpression && 03411 isStartOfObjCClassMessageMissingOpenBracket()) 03412 return false; 03413 03414 return isDeclarationSpecifier(); 03415 03416 case tok::coloncolon: // ::foo::bar 03417 if (NextToken().is(tok::kw_new) || // ::new 03418 NextToken().is(tok::kw_delete)) // ::delete 03419 return false; 03420 03421 // Annotate typenames and C++ scope specifiers. If we get one, just 03422 // recurse to handle whatever we get. 03423 if (TryAnnotateTypeOrScopeToken()) 03424 return true; 03425 return isDeclarationSpecifier(); 03426 03427 // storage-class-specifier 03428 case tok::kw_typedef: 03429 case tok::kw_extern: 03430 case tok::kw___private_extern__: 03431 case tok::kw_static: 03432 case tok::kw_auto: 03433 case tok::kw_register: 03434 case tok::kw___thread: 03435 03436 // Modules 03437 case tok::kw___module_private__: 03438 03439 // type-specifiers 03440 case tok::kw_short: 03441 case tok::kw_long: 03442 case tok::kw___int64: 03443 case tok::kw___int128: 03444 case tok::kw_signed: 03445 case tok::kw_unsigned: 03446 case tok::kw__Complex: 03447 case tok::kw__Imaginary: 03448 case tok::kw_void: 03449 case tok::kw_char: 03450 case tok::kw_wchar_t: 03451 case tok::kw_char16_t: 03452 case tok::kw_char32_t: 03453 03454 case tok::kw_int: 03455 case tok::kw_half: 03456 case tok::kw_float: 03457 case tok::kw_double: 03458 case tok::kw_bool: 03459 case tok::kw__Bool: 03460 case tok::kw__Decimal32: 03461 case tok::kw__Decimal64: 03462 case tok::kw__Decimal128: 03463 case tok::kw___vector: 03464 03465 // struct-or-union-specifier (C99) or class-specifier (C++) 03466 case tok::kw_class: 03467 case tok::kw_struct: 03468 case tok::kw_union: 03469 // enum-specifier 03470 case tok::kw_enum: 03471 03472 // type-qualifier 03473 case tok::kw_const: 03474 case tok::kw_volatile: 03475 case tok::kw_restrict: 03476 03477 // function-specifier 03478 case tok::kw_inline: 03479 case tok::kw_virtual: 03480 case tok::kw_explicit: 03481 03482 // static_assert-declaration 03483 case tok::kw__Static_assert: 03484 03485 // GNU typeof support. 03486 case tok::kw_typeof: 03487 03488 // GNU attributes. 03489 case tok::kw___attribute: 03490 return true; 03491 03492 // C++0x decltype. 03493 case tok::annot_decltype: 03494 return true; 03495 03496 // C11 _Atomic() 03497 case tok::kw__Atomic: 03498 return true; 03499 03500 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 03501 case tok::less: 03502 return getLangOpts().ObjC1; 03503 03504 // typedef-name 03505 case tok::annot_typename: 03506 return !DisambiguatingWithExpression || 03507 !isStartOfObjCClassMessageMissingOpenBracket(); 03508 03509 case tok::kw___declspec: 03510 case tok::kw___cdecl: 03511 case tok::kw___stdcall: 03512 case tok::kw___fastcall: 03513 case tok::kw___thiscall: 03514 case tok::kw___w64: 03515 case tok::kw___ptr64: 03516 case tok::kw___ptr32: 03517 case tok::kw___forceinline: 03518 case tok::kw___pascal: 03519 case tok::kw___unaligned: 03520 03521 case tok::kw___private: 03522 case tok::kw___local: 03523 case tok::kw___global: 03524 case tok::kw___constant: 03525 case tok::kw___read_only: 03526 case tok::kw___read_write: 03527 case tok::kw___write_only: 03528 03529 return true; 03530 } 03531 } 03532 03533 bool Parser::isConstructorDeclarator() { 03534 TentativeParsingAction TPA(*this); 03535 03536 // Parse the C++ scope specifier. 03537 CXXScopeSpec SS; 03538 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 03539 /*EnteringContext=*/true)) { 03540 TPA.Revert(); 03541 return false; 03542 } 03543 03544 // Parse the constructor name. 03545 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 03546 // We already know that we have a constructor name; just consume 03547 // the token. 03548 ConsumeToken(); 03549 } else { 03550 TPA.Revert(); 03551 return false; 03552 } 03553 03554 // Current class name must be followed by a left parenthesis. 03555 if (Tok.isNot(tok::l_paren)) { 03556 TPA.Revert(); 03557 return false; 03558 } 03559 ConsumeParen(); 03560 03561 // A right parenthesis, or ellipsis followed by a right parenthesis signals 03562 // that we have a constructor. 03563 if (Tok.is(tok::r_paren) || 03564 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 03565 TPA.Revert(); 03566 return true; 03567 } 03568 03569 // If we need to, enter the specified scope. 03570 DeclaratorScopeObj DeclScopeObj(*this, SS); 03571 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 03572 DeclScopeObj.EnterDeclaratorScope(); 03573 03574 // Optionally skip Microsoft attributes. 03575 ParsedAttributes Attrs(AttrFactory); 03576 MaybeParseMicrosoftAttributes(Attrs); 03577 03578 // Check whether the next token(s) are part of a declaration 03579 // specifier, in which case we have the start of a parameter and, 03580 // therefore, we know that this is a constructor. 03581 bool IsConstructor = false; 03582 if (isDeclarationSpecifier()) 03583 IsConstructor = true; 03584 else if (Tok.is(tok::identifier) || 03585 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 03586 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 03587 // This might be a parenthesized member name, but is more likely to 03588 // be a constructor declaration with an invalid argument type. Keep 03589 // looking. 03590 if (Tok.is(tok::annot_cxxscope)) 03591 ConsumeToken(); 03592 ConsumeToken(); 03593 03594 // If this is not a constructor, we must be parsing a declarator, 03595 // which must have one of the following syntactic forms (see the 03596 // grammar extract at the start of ParseDirectDeclarator): 03597 switch (Tok.getKind()) { 03598 case tok::l_paren: 03599 // C(X ( int)); 03600 case tok::l_square: 03601 // C(X [ 5]); 03602 // C(X [ [attribute]]); 03603 case tok::coloncolon: 03604 // C(X :: Y); 03605 // C(X :: *p); 03606 case tok::r_paren: 03607 // C(X ) 03608 // Assume this isn't a constructor, rather than assuming it's a 03609 // constructor with an unnamed parameter of an ill-formed type. 03610 break; 03611 03612 default: 03613 IsConstructor = true; 03614 break; 03615 } 03616 } 03617 03618 TPA.Revert(); 03619 return IsConstructor; 03620 } 03621 03622 /// ParseTypeQualifierListOpt 03623 /// type-qualifier-list: [C99 6.7.5] 03624 /// type-qualifier 03625 /// [vendor] attributes 03626 /// [ only if VendorAttributesAllowed=true ] 03627 /// type-qualifier-list type-qualifier 03628 /// [vendor] type-qualifier-list attributes 03629 /// [ only if VendorAttributesAllowed=true ] 03630 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 03631 /// [ only if CXX0XAttributesAllowed=true ] 03632 /// Note: vendor can be GNU, MS, etc. 03633 /// 03634 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, 03635 bool VendorAttributesAllowed, 03636 bool CXX11AttributesAllowed) { 03637 if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed && 03638 isCXX11AttributeSpecifier()) { 03639 ParsedAttributesWithRange attrs(AttrFactory); 03640 ParseCXX11Attributes(attrs); 03641 DS.takeAttributesFrom(attrs); 03642 } 03643 03644 SourceLocation EndLoc; 03645 03646 while (1) { 03647 bool isInvalid = false; 03648 const char *PrevSpec = 0; 03649 unsigned DiagID = 0; 03650 SourceLocation Loc = Tok.getLocation(); 03651 03652 switch (Tok.getKind()) { 03653 case tok::code_completion: 03654 Actions.CodeCompleteTypeQualifiers(DS); 03655 return cutOffParsing(); 03656 03657 case tok::kw_const: 03658 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 03659 getLangOpts()); 03660 break; 03661 case tok::kw_volatile: 03662 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 03663 getLangOpts()); 03664 break; 03665 case tok::kw_restrict: 03666 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 03667 getLangOpts()); 03668 break; 03669 03670 // OpenCL qualifiers: 03671 case tok::kw_private: 03672 if (!getLangOpts().OpenCL) 03673 goto DoneWithTypeQuals; 03674 case tok::kw___private: 03675 case tok::kw___global: 03676 case tok::kw___local: 03677 case tok::kw___constant: 03678 case tok::kw___read_only: 03679 case tok::kw___write_only: 03680 case tok::kw___read_write: 03681 ParseOpenCLQualifiers(DS); 03682 break; 03683 03684 case tok::kw___w64: 03685 case tok::kw___ptr64: 03686 case tok::kw___ptr32: 03687 case tok::kw___cdecl: 03688 case tok::kw___stdcall: 03689 case tok::kw___fastcall: 03690 case tok::kw___thiscall: 03691 case tok::kw___unaligned: 03692 if (VendorAttributesAllowed) { 03693 ParseMicrosoftTypeAttributes(DS.getAttributes()); 03694 continue; 03695 } 03696 goto DoneWithTypeQuals; 03697 case tok::kw___pascal: 03698 if (VendorAttributesAllowed) { 03699 ParseBorlandTypeAttributes(DS.getAttributes()); 03700 continue; 03701 } 03702 goto DoneWithTypeQuals; 03703 case tok::kw___attribute: 03704 if (VendorAttributesAllowed) { 03705 ParseGNUAttributes(DS.getAttributes()); 03706 continue; // do *not* consume the next token! 03707 } 03708 // otherwise, FALL THROUGH! 03709 default: 03710 DoneWithTypeQuals: 03711 // If this is not a type-qualifier token, we're done reading type 03712 // qualifiers. First verify that DeclSpec's are consistent. 03713 DS.Finish(Diags, PP); 03714 if (EndLoc.isValid()) 03715 DS.SetRangeEnd(EndLoc); 03716 return; 03717 } 03718 03719 // If the specifier combination wasn't legal, issue a diagnostic. 03720 if (isInvalid) { 03721 assert(PrevSpec && "Method did not return previous specifier!"); 03722 Diag(Tok, DiagID) << PrevSpec; 03723 } 03724 EndLoc = ConsumeToken(); 03725 } 03726 } 03727 03728 03729 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 03730 /// 03731 void Parser::ParseDeclarator(Declarator &D) { 03732 /// This implements the 'declarator' production in the C grammar, then checks 03733 /// for well-formedness and issues diagnostics. 03734 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 03735 } 03736 03737 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) { 03738 if (Kind == tok::star || Kind == tok::caret) 03739 return true; 03740 03741 // We parse rvalue refs in C++03, because otherwise the errors are scary. 03742 if (!Lang.CPlusPlus) 03743 return false; 03744 03745 return Kind == tok::amp || Kind == tok::ampamp; 03746 } 03747 03748 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 03749 /// is parsed by the function passed to it. Pass null, and the direct-declarator 03750 /// isn't parsed at all, making this function effectively parse the C++ 03751 /// ptr-operator production. 03752 /// 03753 /// If the grammar of this construct is extended, matching changes must also be 03754 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to 03755 /// isConstructorDeclarator. 03756 /// 03757 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 03758 /// [C] pointer[opt] direct-declarator 03759 /// [C++] direct-declarator 03760 /// [C++] ptr-operator declarator 03761 /// 03762 /// pointer: [C99 6.7.5] 03763 /// '*' type-qualifier-list[opt] 03764 /// '*' type-qualifier-list[opt] pointer 03765 /// 03766 /// ptr-operator: 03767 /// '*' cv-qualifier-seq[opt] 03768 /// '&' 03769 /// [C++0x] '&&' 03770 /// [GNU] '&' restrict[opt] attributes[opt] 03771 /// [GNU?] '&&' restrict[opt] attributes[opt] 03772 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 03773 void Parser::ParseDeclaratorInternal(Declarator &D, 03774 DirectDeclParseFunction DirectDeclParser) { 03775 if (Diags.hasAllExtensionsSilenced()) 03776 D.setExtension(); 03777 03778 // C++ member pointers start with a '::' or a nested-name. 03779 // Member pointers get special handling, since there's no place for the 03780 // scope spec in the generic path below. 03781 if (getLangOpts().CPlusPlus && 03782 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 03783 Tok.is(tok::annot_cxxscope))) { 03784 bool EnteringContext = D.getContext() == Declarator::FileContext || 03785 D.getContext() == Declarator::MemberContext; 03786 CXXScopeSpec SS; 03787 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext); 03788 03789 if (SS.isNotEmpty()) { 03790 if (Tok.isNot(tok::star)) { 03791 // The scope spec really belongs to the direct-declarator. 03792 D.getCXXScopeSpec() = SS; 03793 if (DirectDeclParser) 03794 (this->*DirectDeclParser)(D); 03795 return; 03796 } 03797 03798 SourceLocation Loc = ConsumeToken(); 03799 D.SetRangeEnd(Loc); 03800 DeclSpec DS(AttrFactory); 03801 ParseTypeQualifierListOpt(DS); 03802 D.ExtendWithDeclSpec(DS); 03803 03804 // Recurse to parse whatever is left. 03805 ParseDeclaratorInternal(D, DirectDeclParser); 03806 03807 // Sema will have to catch (syntactically invalid) pointers into global 03808 // scope. It has to catch pointers into namespace scope anyway. 03809 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 03810 Loc), 03811 DS.getAttributes(), 03812 /* Don't replace range end. */SourceLocation()); 03813 return; 03814 } 03815 } 03816 03817 tok::TokenKind Kind = Tok.getKind(); 03818 // Not a pointer, C++ reference, or block. 03819 if (!isPtrOperatorToken(Kind, getLangOpts())) { 03820 if (DirectDeclParser) 03821 (this->*DirectDeclParser)(D); 03822 return; 03823 } 03824 03825 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 03826 // '&&' -> rvalue reference 03827 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 03828 D.SetRangeEnd(Loc); 03829 03830 if (Kind == tok::star || Kind == tok::caret) { 03831 // Is a pointer. 03832 DeclSpec DS(AttrFactory); 03833 03834 // FIXME: GNU attributes are not allowed here in a new-type-id. 03835 ParseTypeQualifierListOpt(DS); 03836 D.ExtendWithDeclSpec(DS); 03837 03838 // Recursively parse the declarator. 03839 ParseDeclaratorInternal(D, DirectDeclParser); 03840 if (Kind == tok::star) 03841 // Remember that we parsed a pointer type, and remember the type-quals. 03842 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 03843 DS.getConstSpecLoc(), 03844 DS.getVolatileSpecLoc(), 03845 DS.getRestrictSpecLoc()), 03846 DS.getAttributes(), 03847 SourceLocation()); 03848 else 03849 // Remember that we parsed a Block type, and remember the type-quals. 03850 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 03851 Loc), 03852 DS.getAttributes(), 03853 SourceLocation()); 03854 } else { 03855 // Is a reference 03856 DeclSpec DS(AttrFactory); 03857 03858 // Complain about rvalue references in C++03, but then go on and build 03859 // the declarator. 03860 if (Kind == tok::ampamp) 03861 Diag(Loc, getLangOpts().CPlusPlus0x ? 03862 diag::warn_cxx98_compat_rvalue_reference : 03863 diag::ext_rvalue_reference); 03864 03865 // GNU-style and C++11 attributes are allowed here, as is restrict. 03866 ParseTypeQualifierListOpt(DS); 03867 D.ExtendWithDeclSpec(DS); 03868 03869 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 03870 // cv-qualifiers are introduced through the use of a typedef or of a 03871 // template type argument, in which case the cv-qualifiers are ignored. 03872 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 03873 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 03874 Diag(DS.getConstSpecLoc(), 03875 diag::err_invalid_reference_qualifier_application) << "const"; 03876 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 03877 Diag(DS.getVolatileSpecLoc(), 03878 diag::err_invalid_reference_qualifier_application) << "volatile"; 03879 } 03880 03881 // Recursively parse the declarator. 03882 ParseDeclaratorInternal(D, DirectDeclParser); 03883 03884 if (D.getNumTypeObjects() > 0) { 03885 // C++ [dcl.ref]p4: There shall be no references to references. 03886 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 03887 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 03888 if (const IdentifierInfo *II = D.getIdentifier()) 03889 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 03890 << II; 03891 else 03892 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 03893 << "type name"; 03894 03895 // Once we've complained about the reference-to-reference, we 03896 // can go ahead and build the (technically ill-formed) 03897 // declarator: reference collapsing will take care of it. 03898 } 03899 } 03900 03901 // Remember that we parsed a reference type. It doesn't have type-quals. 03902 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 03903 Kind == tok::amp), 03904 DS.getAttributes(), 03905 SourceLocation()); 03906 } 03907 } 03908 03909 static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D, 03910 SourceLocation EllipsisLoc) { 03911 if (EllipsisLoc.isValid()) { 03912 FixItHint Insertion; 03913 if (!D.getEllipsisLoc().isValid()) { 03914 Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "..."); 03915 D.setEllipsisLoc(EllipsisLoc); 03916 } 03917 P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration) 03918 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName(); 03919 } 03920 } 03921 03922 /// ParseDirectDeclarator 03923 /// direct-declarator: [C99 6.7.5] 03924 /// [C99] identifier 03925 /// '(' declarator ')' 03926 /// [GNU] '(' attributes declarator ')' 03927 /// [C90] direct-declarator '[' constant-expression[opt] ']' 03928 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 03929 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 03930 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 03931 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 03932 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 03933 /// attribute-specifier-seq[opt] 03934 /// direct-declarator '(' parameter-type-list ')' 03935 /// direct-declarator '(' identifier-list[opt] ')' 03936 /// [GNU] direct-declarator '(' parameter-forward-declarations 03937 /// parameter-type-list[opt] ')' 03938 /// [C++] direct-declarator '(' parameter-declaration-clause ')' 03939 /// cv-qualifier-seq[opt] exception-specification[opt] 03940 /// [C++11] direct-declarator '(' parameter-declaration-clause ')' 03941 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt] 03942 /// ref-qualifier[opt] exception-specification[opt] 03943 /// [C++] declarator-id 03944 /// [C++11] declarator-id attribute-specifier-seq[opt] 03945 /// 03946 /// declarator-id: [C++ 8] 03947 /// '...'[opt] id-expression 03948 /// '::'[opt] nested-name-specifier[opt] type-name 03949 /// 03950 /// id-expression: [C++ 5.1] 03951 /// unqualified-id 03952 /// qualified-id 03953 /// 03954 /// unqualified-id: [C++ 5.1] 03955 /// identifier 03956 /// operator-function-id 03957 /// conversion-function-id 03958 /// '~' class-name 03959 /// template-id 03960 /// 03961 /// Note, any additional constructs added here may need corresponding changes 03962 /// in isConstructorDeclarator. 03963 void Parser::ParseDirectDeclarator(Declarator &D) { 03964 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 03965 03966 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { 03967 // ParseDeclaratorInternal might already have parsed the scope. 03968 if (D.getCXXScopeSpec().isEmpty()) { 03969 bool EnteringContext = D.getContext() == Declarator::FileContext || 03970 D.getContext() == Declarator::MemberContext; 03971 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), 03972 EnteringContext); 03973 } 03974 03975 if (D.getCXXScopeSpec().isValid()) { 03976 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 03977 // Change the declaration context for name lookup, until this function 03978 // is exited (and the declarator has been parsed). 03979 DeclScopeObj.EnterDeclaratorScope(); 03980 } 03981 03982 // C++0x [dcl.fct]p14: 03983 // There is a syntactic ambiguity when an ellipsis occurs at the end 03984 // of a parameter-declaration-clause without a preceding comma. In 03985 // this case, the ellipsis is parsed as part of the 03986 // abstract-declarator if the type of the parameter names a template 03987 // parameter pack that has not been expanded; otherwise, it is parsed 03988 // as part of the parameter-declaration-clause. 03989 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && 03990 !((D.getContext() == Declarator::PrototypeContext || 03991 D.getContext() == Declarator::BlockLiteralContext) && 03992 NextToken().is(tok::r_paren) && 03993 !Actions.containsUnexpandedParameterPacks(D))) { 03994 SourceLocation EllipsisLoc = ConsumeToken(); 03995 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) { 03996 // The ellipsis was put in the wrong place. Recover, and explain to 03997 // the user what they should have done. 03998 ParseDeclarator(D); 03999 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc); 04000 return; 04001 } else 04002 D.setEllipsisLoc(EllipsisLoc); 04003 04004 // The ellipsis can't be followed by a parenthesized declarator. We 04005 // check for that in ParseParenDeclarator, after we have disambiguated 04006 // the l_paren token. 04007 } 04008 04009 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 04010 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 04011 // We found something that indicates the start of an unqualified-id. 04012 // Parse that unqualified-id. 04013 bool AllowConstructorName; 04014 if (D.getDeclSpec().hasTypeSpecifier()) 04015 AllowConstructorName = false; 04016 else if (D.getCXXScopeSpec().isSet()) 04017 AllowConstructorName = 04018 (D.getContext() == Declarator::FileContext || 04019 (D.getContext() == Declarator::MemberContext && 04020 D.getDeclSpec().isFriendSpecified())); 04021 else 04022 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 04023 04024 SourceLocation TemplateKWLoc; 04025 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 04026 /*EnteringContext=*/true, 04027 /*AllowDestructorName=*/true, 04028 AllowConstructorName, 04029 ParsedType(), 04030 TemplateKWLoc, 04031 D.getName()) || 04032 // Once we're past the identifier, if the scope was bad, mark the 04033 // whole declarator bad. 04034 D.getCXXScopeSpec().isInvalid()) { 04035 D.SetIdentifier(0, Tok.getLocation()); 04036 D.setInvalidType(true); 04037 } else { 04038 // Parsed the unqualified-id; update range information and move along. 04039 if (D.getSourceRange().getBegin().isInvalid()) 04040 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 04041 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 04042 } 04043 goto PastIdentifier; 04044 } 04045 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 04046 assert(!getLangOpts().CPlusPlus && 04047 "There's a C++-specific check for tok::identifier above"); 04048 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 04049 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 04050 ConsumeToken(); 04051 goto PastIdentifier; 04052 } 04053 04054 if (Tok.is(tok::l_paren)) { 04055 // direct-declarator: '(' declarator ')' 04056 // direct-declarator: '(' attributes declarator ')' 04057 // Example: 'char (*X)' or 'int (*XX)(void)' 04058 ParseParenDeclarator(D); 04059 04060 // If the declarator was parenthesized, we entered the declarator 04061 // scope when parsing the parenthesized declarator, then exited 04062 // the scope already. Re-enter the scope, if we need to. 04063 if (D.getCXXScopeSpec().isSet()) { 04064 // If there was an error parsing parenthesized declarator, declarator 04065 // scope may have been entered before. Don't do it again. 04066 if (!D.isInvalidType() && 04067 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 04068 // Change the declaration context for name lookup, until this function 04069 // is exited (and the declarator has been parsed). 04070 DeclScopeObj.EnterDeclaratorScope(); 04071 } 04072 } else if (D.mayOmitIdentifier()) { 04073 // This could be something simple like "int" (in which case the declarator 04074 // portion is empty), if an abstract-declarator is allowed. 04075 D.SetIdentifier(0, Tok.getLocation()); 04076 } else { 04077 if (D.getContext() == Declarator::MemberContext) 04078 Diag(Tok, diag::err_expected_member_name_or_semi) 04079 << D.getDeclSpec().getSourceRange(); 04080 else if (getLangOpts().CPlusPlus) 04081 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; 04082 else 04083 Diag(Tok, diag::err_expected_ident_lparen); 04084 D.SetIdentifier(0, Tok.getLocation()); 04085 D.setInvalidType(true); 04086 } 04087 04088 PastIdentifier: 04089 assert(D.isPastIdentifier() && 04090 "Haven't past the location of the identifier yet?"); 04091 04092 // Don't parse attributes unless we have parsed an unparenthesized name. 04093 if (D.hasName() && !D.getNumTypeObjects()) 04094 MaybeParseCXX0XAttributes(D); 04095 04096 while (1) { 04097 if (Tok.is(tok::l_paren)) { 04098 // Enter function-declaration scope, limiting any declarators to the 04099 // function prototype scope, including parameter declarators. 04100 ParseScope PrototypeScope(this, 04101 Scope::FunctionPrototypeScope|Scope::DeclScope); 04102 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 04103 // In such a case, check if we actually have a function declarator; if it 04104 // is not, the declarator has been fully parsed. 04105 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 04106 // When not in file scope, warn for ambiguous function declarators, just 04107 // in case the author intended it as a variable definition. 04108 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 04109 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 04110 break; 04111 } 04112 ParsedAttributes attrs(AttrFactory); 04113 BalancedDelimiterTracker T(*this, tok::l_paren); 04114 T.consumeOpen(); 04115 ParseFunctionDeclarator(D, attrs, T); 04116 PrototypeScope.Exit(); 04117 } else if (Tok.is(tok::l_square)) { 04118 ParseBracketDeclarator(D); 04119 } else { 04120 break; 04121 } 04122 } 04123 } 04124 04125 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 04126 /// only called before the identifier, so these are most likely just grouping 04127 /// parens for precedence. If we find that these are actually function 04128 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 04129 /// 04130 /// direct-declarator: 04131 /// '(' declarator ')' 04132 /// [GNU] '(' attributes declarator ')' 04133 /// direct-declarator '(' parameter-type-list ')' 04134 /// direct-declarator '(' identifier-list[opt] ')' 04135 /// [GNU] direct-declarator '(' parameter-forward-declarations 04136 /// parameter-type-list[opt] ')' 04137 /// 04138 void Parser::ParseParenDeclarator(Declarator &D) { 04139 BalancedDelimiterTracker T(*this, tok::l_paren); 04140 T.consumeOpen(); 04141 04142 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 04143 04144 // Eat any attributes before we look at whether this is a grouping or function 04145 // declarator paren. If this is a grouping paren, the attribute applies to 04146 // the type being built up, for example: 04147 // int (__attribute__(()) *x)(long y) 04148 // If this ends up not being a grouping paren, the attribute applies to the 04149 // first argument, for example: 04150 // int (__attribute__(()) int x) 04151 // In either case, we need to eat any attributes to be able to determine what 04152 // sort of paren this is. 04153 // 04154 ParsedAttributes attrs(AttrFactory); 04155 bool RequiresArg = false; 04156 if (Tok.is(tok::kw___attribute)) { 04157 ParseGNUAttributes(attrs); 04158 04159 // We require that the argument list (if this is a non-grouping paren) be 04160 // present even if the attribute list was empty. 04161 RequiresArg = true; 04162 } 04163 // Eat any Microsoft extensions. 04164 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 04165 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) || 04166 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) || 04167 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) { 04168 ParseMicrosoftTypeAttributes(attrs); 04169 } 04170 // Eat any Borland extensions. 04171 if (Tok.is(tok::kw___pascal)) 04172 ParseBorlandTypeAttributes(attrs); 04173 04174 // If we haven't past the identifier yet (or where the identifier would be 04175 // stored, if this is an abstract declarator), then this is probably just 04176 // grouping parens. However, if this could be an abstract-declarator, then 04177 // this could also be the start of function arguments (consider 'void()'). 04178 bool isGrouping; 04179 04180 if (!D.mayOmitIdentifier()) { 04181 // If this can't be an abstract-declarator, this *must* be a grouping 04182 // paren, because we haven't seen the identifier yet. 04183 isGrouping = true; 04184 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 04185 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && 04186 NextToken().is(tok::r_paren)) || // C++ int(...) 04187 isDeclarationSpecifier() || // 'int(int)' is a function. 04188 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. 04189 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 04190 // considered to be a type, not a K&R identifier-list. 04191 isGrouping = false; 04192 } else { 04193 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 04194 isGrouping = true; 04195 } 04196 04197 // If this is a grouping paren, handle: 04198 // direct-declarator: '(' declarator ')' 04199 // direct-declarator: '(' attributes declarator ')' 04200 if (isGrouping) { 04201 SourceLocation EllipsisLoc = D.getEllipsisLoc(); 04202 D.setEllipsisLoc(SourceLocation()); 04203 04204 bool hadGroupingParens = D.hasGroupingParens(); 04205 D.setGroupingParens(true); 04206 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 04207 // Match the ')'. 04208 T.consumeClose(); 04209 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), 04210 T.getCloseLocation()), 04211 attrs, T.getCloseLocation()); 04212 04213 D.setGroupingParens(hadGroupingParens); 04214 04215 // An ellipsis cannot be placed outside parentheses. 04216 if (EllipsisLoc.isValid()) 04217 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc); 04218 04219 return; 04220 } 04221 04222 // Okay, if this wasn't a grouping paren, it must be the start of a function 04223 // argument list. Recognize that this declarator will never have an 04224 // identifier (and remember where it would have been), then call into 04225 // ParseFunctionDeclarator to handle of argument list. 04226 D.SetIdentifier(0, Tok.getLocation()); 04227 04228 // Enter function-declaration scope, limiting any declarators to the 04229 // function prototype scope, including parameter declarators. 04230 ParseScope PrototypeScope(this, 04231 Scope::FunctionPrototypeScope|Scope::DeclScope); 04232 ParseFunctionDeclarator(D, attrs, T, RequiresArg); 04233 PrototypeScope.Exit(); 04234 } 04235 04236 /// ParseFunctionDeclarator - We are after the identifier and have parsed the 04237 /// declarator D up to a paren, which indicates that we are parsing function 04238 /// arguments. 04239 /// 04240 /// If FirstArgAttrs is non-null, then the caller parsed those arguments 04241 /// immediately after the open paren - they should be considered to be the 04242 /// first argument of a parameter. 04243 /// 04244 /// If RequiresArg is true, then the first argument of the function is required 04245 /// to be present and required to not be an identifier list. 04246 /// 04247 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], 04248 /// (C++11) ref-qualifier[opt], exception-specification[opt], 04249 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt]. 04250 /// 04251 /// [C++11] exception-specification: 04252 /// dynamic-exception-specification 04253 /// noexcept-specification 04254 /// 04255 void Parser::ParseFunctionDeclarator(Declarator &D, 04256 ParsedAttributes &FirstArgAttrs, 04257 BalancedDelimiterTracker &Tracker, 04258 bool RequiresArg) { 04259 assert(getCurScope()->isFunctionPrototypeScope() && 04260 "Should call from a Function scope"); 04261 // lparen is already consumed! 04262 assert(D.isPastIdentifier() && "Should not call before identifier!"); 04263 04264 // This should be true when the function has typed arguments. 04265 // Otherwise, it is treated as a K&R-style function. 04266 bool HasProto = false; 04267 // Build up an array of information about the parsed arguments. 04268 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 04269 // Remember where we see an ellipsis, if any. 04270 SourceLocation EllipsisLoc; 04271 04272 DeclSpec DS(AttrFactory); 04273 bool RefQualifierIsLValueRef = true; 04274 SourceLocation RefQualifierLoc; 04275 SourceLocation ConstQualifierLoc; 04276 SourceLocation VolatileQualifierLoc; 04277 ExceptionSpecificationType ESpecType = EST_None; 04278 SourceRange ESpecRange; 04279 SmallVector<ParsedType, 2> DynamicExceptions; 04280 SmallVector<SourceRange, 2> DynamicExceptionRanges; 04281 ExprResult NoexceptExpr; 04282 ParsedAttributes FnAttrs(AttrFactory); 04283 ParsedType TrailingReturnType; 04284 04285 Actions.ActOnStartFunctionDeclarator(); 04286 04287 SourceLocation EndLoc; 04288 if (isFunctionDeclaratorIdentifierList()) { 04289 if (RequiresArg) 04290 Diag(Tok, diag::err_argument_required_after_attribute); 04291 04292 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 04293 04294 Tracker.consumeClose(); 04295 EndLoc = Tracker.getCloseLocation(); 04296 } else { 04297 if (Tok.isNot(tok::r_paren)) 04298 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc); 04299 else if (RequiresArg) 04300 Diag(Tok, diag::err_argument_required_after_attribute); 04301 04302 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus; 04303 04304 // If we have the closing ')', eat it. 04305 Tracker.consumeClose(); 04306 EndLoc = Tracker.getCloseLocation(); 04307 04308 if (getLangOpts().CPlusPlus) { 04309 // FIXME: Accept these components in any order, and produce fixits to 04310 // correct the order if the user gets it wrong. Ideally we should deal 04311 // with the virt-specifier-seq and pure-specifier in the same way. 04312 04313 // Parse cv-qualifier-seq[opt]. 04314 ParseTypeQualifierListOpt(DS, false /*no attributes*/, false); 04315 if (!DS.getSourceRange().getEnd().isInvalid()) { 04316 EndLoc = DS.getSourceRange().getEnd(); 04317 ConstQualifierLoc = DS.getConstSpecLoc(); 04318 VolatileQualifierLoc = DS.getVolatileSpecLoc(); 04319 } 04320 04321 // Parse ref-qualifier[opt]. 04322 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 04323 Diag(Tok, getLangOpts().CPlusPlus0x ? 04324 diag::warn_cxx98_compat_ref_qualifier : 04325 diag::ext_ref_qualifier); 04326 04327 RefQualifierIsLValueRef = Tok.is(tok::amp); 04328 RefQualifierLoc = ConsumeToken(); 04329 EndLoc = RefQualifierLoc; 04330 } 04331 04332 // C++11 [expr.prim.general]p3: 04333 // If a declaration declares a member function or member function 04334 // template of a class X, the expression this is a prvalue of type 04335 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 04336 // and the end of the function-definition, member-declarator, or 04337 // declarator. 04338 bool IsCXX11MemberFunction = 04339 getLangOpts().CPlusPlus0x && 04340 (D.getContext() == Declarator::MemberContext || 04341 (D.getContext() == Declarator::FileContext && 04342 D.getCXXScopeSpec().isValid() && 04343 Actions.CurContext->isRecord())); 04344 Sema::CXXThisScopeRAII ThisScope(Actions, 04345 dyn_cast<CXXRecordDecl>(Actions.CurContext), 04346 DS.getTypeQualifiers(), 04347 IsCXX11MemberFunction); 04348 04349 // Parse exception-specification[opt]. 04350 ESpecType = tryParseExceptionSpecification(ESpecRange, 04351 DynamicExceptions, 04352 DynamicExceptionRanges, 04353 NoexceptExpr); 04354 if (ESpecType != EST_None) 04355 EndLoc = ESpecRange.getEnd(); 04356 04357 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes 04358 // after the exception-specification. 04359 MaybeParseCXX0XAttributes(FnAttrs); 04360 04361 // Parse trailing-return-type[opt]. 04362 if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) { 04363 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 04364 SourceRange Range; 04365 TrailingReturnType = ParseTrailingReturnType(Range).get(); 04366 if (Range.getEnd().isValid()) 04367 EndLoc = Range.getEnd(); 04368 } 04369 } 04370 } 04371 04372 // Remember that we parsed a function type, and remember the attributes. 04373 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, 04374 /*isVariadic=*/EllipsisLoc.isValid(), 04375 EllipsisLoc, 04376 ParamInfo.data(), ParamInfo.size(), 04377 DS.getTypeQualifiers(), 04378 RefQualifierIsLValueRef, 04379 RefQualifierLoc, ConstQualifierLoc, 04380 VolatileQualifierLoc, 04381 /*MutableLoc=*/SourceLocation(), 04382 ESpecType, ESpecRange.getBegin(), 04383 DynamicExceptions.data(), 04384 DynamicExceptionRanges.data(), 04385 DynamicExceptions.size(), 04386 NoexceptExpr.isUsable() ? 04387 NoexceptExpr.get() : 0, 04388 Tracker.getOpenLocation(), 04389 EndLoc, D, 04390 TrailingReturnType), 04391 FnAttrs, EndLoc); 04392 04393 Actions.ActOnEndFunctionDeclarator(); 04394 } 04395 04396 /// isFunctionDeclaratorIdentifierList - This parameter list may have an 04397 /// identifier list form for a K&R-style function: void foo(a,b,c) 04398 /// 04399 /// Note that identifier-lists are only allowed for normal declarators, not for 04400 /// abstract-declarators. 04401 bool Parser::isFunctionDeclaratorIdentifierList() { 04402 return !getLangOpts().CPlusPlus 04403 && Tok.is(tok::identifier) 04404 && !TryAltiVecVectorToken() 04405 // K&R identifier lists can't have typedefs as identifiers, per C99 04406 // 6.7.5.3p11. 04407 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 04408 // Identifier lists follow a really simple grammar: the identifiers can 04409 // be followed *only* by a ", identifier" or ")". However, K&R 04410 // identifier lists are really rare in the brave new modern world, and 04411 // it is very common for someone to typo a type in a non-K&R style 04412 // list. If we are presented with something like: "void foo(intptr x, 04413 // float y)", we don't want to start parsing the function declarator as 04414 // though it is a K&R style declarator just because intptr is an 04415 // invalid type. 04416 // 04417 // To handle this, we check to see if the token after the first 04418 // identifier is a "," or ")". Only then do we parse it as an 04419 // identifier list. 04420 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)); 04421 } 04422 04423 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 04424 /// we found a K&R-style identifier list instead of a typed parameter list. 04425 /// 04426 /// After returning, ParamInfo will hold the parsed parameters. 04427 /// 04428 /// identifier-list: [C99 6.7.5] 04429 /// identifier 04430 /// identifier-list ',' identifier 04431 /// 04432 void Parser::ParseFunctionDeclaratorIdentifierList( 04433 Declarator &D, 04434 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) { 04435 // If there was no identifier specified for the declarator, either we are in 04436 // an abstract-declarator, or we are in a parameter declarator which was found 04437 // to be abstract. In abstract-declarators, identifier lists are not valid: 04438 // diagnose this. 04439 if (!D.getIdentifier()) 04440 Diag(Tok, diag::ext_ident_list_in_param); 04441 04442 // Maintain an efficient lookup of params we have seen so far. 04443 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 04444 04445 while (1) { 04446 // If this isn't an identifier, report the error and skip until ')'. 04447 if (Tok.isNot(tok::identifier)) { 04448 Diag(Tok, diag::err_expected_ident); 04449 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true); 04450 // Forget we parsed anything. 04451 ParamInfo.clear(); 04452 return; 04453 } 04454 04455 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 04456 04457 // Reject 'typedef int y; int test(x, y)', but continue parsing. 04458 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 04459 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 04460 04461 // Verify that the argument identifier has not already been mentioned. 04462 if (!ParamsSoFar.insert(ParmII)) { 04463 Diag(Tok, diag::err_param_redefinition) << ParmII; 04464 } else { 04465 // Remember this identifier in ParamInfo. 04466 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 04467 Tok.getLocation(), 04468 0)); 04469 } 04470 04471 // Eat the identifier. 04472 ConsumeToken(); 04473 04474 // The list continues if we see a comma. 04475 if (Tok.isNot(tok::comma)) 04476 break; 04477 ConsumeToken(); 04478 } 04479 } 04480 04481 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 04482 /// after the opening parenthesis. This function will not parse a K&R-style 04483 /// identifier list. 04484 /// 04485 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the 04486 /// caller parsed those arguments immediately after the open paren - they should 04487 /// be considered to be part of the first parameter. 04488 /// 04489 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 04490 /// be the location of the ellipsis, if any was parsed. 04491 /// 04492 /// parameter-type-list: [C99 6.7.5] 04493 /// parameter-list 04494 /// parameter-list ',' '...' 04495 /// [C++] parameter-list '...' 04496 /// 04497 /// parameter-list: [C99 6.7.5] 04498 /// parameter-declaration 04499 /// parameter-list ',' parameter-declaration 04500 /// 04501 /// parameter-declaration: [C99 6.7.5] 04502 /// declaration-specifiers declarator 04503 /// [C++] declaration-specifiers declarator '=' assignment-expression 04504 /// [C++11] initializer-clause 04505 /// [GNU] declaration-specifiers declarator attributes 04506 /// declaration-specifiers abstract-declarator[opt] 04507 /// [C++] declaration-specifiers abstract-declarator[opt] 04508 /// '=' assignment-expression 04509 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes 04510 /// [C++11] attribute-specifier-seq parameter-declaration 04511 /// 04512 void Parser::ParseParameterDeclarationClause( 04513 Declarator &D, 04514 ParsedAttributes &FirstArgAttrs, 04515 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo, 04516 SourceLocation &EllipsisLoc) { 04517 04518 while (1) { 04519 if (Tok.is(tok::ellipsis)) { 04520 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq 04521 // before deciding this was a parameter-declaration-clause. 04522 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 04523 break; 04524 } 04525 04526 // Parse the declaration-specifiers. 04527 // Just use the ParsingDeclaration "scope" of the declarator. 04528 DeclSpec DS(AttrFactory); 04529 04530 // Parse any C++11 attributes. 04531 MaybeParseCXX0XAttributes(DS.getAttributes()); 04532 04533 // Skip any Microsoft attributes before a param. 04534 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) 04535 ParseMicrosoftAttributes(DS.getAttributes()); 04536 04537 SourceLocation DSStart = Tok.getLocation(); 04538 04539 // If the caller parsed attributes for the first argument, add them now. 04540 // Take them so that we only apply the attributes to the first parameter. 04541 // FIXME: If we can leave the attributes in the token stream somehow, we can 04542 // get rid of a parameter (FirstArgAttrs) and this statement. It might be 04543 // too much hassle. 04544 DS.takeAttributesFrom(FirstArgAttrs); 04545 04546 ParseDeclarationSpecifiers(DS); 04547 04548 // Parse the declarator. This is "PrototypeContext", because we must 04549 // accept either 'declarator' or 'abstract-declarator' here. 04550 Declarator ParmDecl(DS, Declarator::PrototypeContext); 04551 ParseDeclarator(ParmDecl); 04552 04553 // Parse GNU attributes, if present. 04554 MaybeParseGNUAttributes(ParmDecl); 04555 04556 // Remember this parsed parameter in ParamInfo. 04557 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 04558 04559 // DefArgToks is used when the parsing of default arguments needs 04560 // to be delayed. 04561 CachedTokens *DefArgToks = 0; 04562 04563 // If no parameter was specified, verify that *something* was specified, 04564 // otherwise we have a missing type and identifier. 04565 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 04566 ParmDecl.getNumTypeObjects() == 0) { 04567 // Completely missing, emit error. 04568 Diag(DSStart, diag::err_missing_param); 04569 } else { 04570 // Otherwise, we have something. Add it and let semantic analysis try 04571 // to grok it and add the result to the ParamInfo we are building. 04572 04573 // Inform the actions module about the parameter declarator, so it gets 04574 // added to the current scope. 04575 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 04576 04577 // Parse the default argument, if any. We parse the default 04578 // arguments in all dialects; the semantic analysis in 04579 // ActOnParamDefaultArgument will reject the default argument in 04580 // C. 04581 if (Tok.is(tok::equal)) { 04582 SourceLocation EqualLoc = Tok.getLocation(); 04583 04584 // Parse the default argument 04585 if (D.getContext() == Declarator::MemberContext) { 04586 // If we're inside a class definition, cache the tokens 04587 // corresponding to the default argument. We'll actually parse 04588 // them when we see the end of the class definition. 04589 // FIXME: Can we use a smart pointer for Toks? 04590 DefArgToks = new CachedTokens; 04591 04592 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 04593 /*StopAtSemi=*/true, 04594 /*ConsumeFinalToken=*/false)) { 04595 delete DefArgToks; 04596 DefArgToks = 0; 04597 Actions.ActOnParamDefaultArgumentError(Param); 04598 } else { 04599 // Mark the end of the default argument so that we know when to 04600 // stop when we parse it later on. 04601 Token DefArgEnd; 04602 DefArgEnd.startToken(); 04603 DefArgEnd.setKind(tok::cxx_defaultarg_end); 04604 DefArgEnd.setLocation(Tok.getLocation()); 04605 DefArgToks->push_back(DefArgEnd); 04606 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 04607 (*DefArgToks)[1].getLocation()); 04608 } 04609 } else { 04610 // Consume the '='. 04611 ConsumeToken(); 04612 04613 // The argument isn't actually potentially evaluated unless it is 04614 // used. 04615 EnterExpressionEvaluationContext Eval(Actions, 04616 Sema::PotentiallyEvaluatedIfUsed, 04617 Param); 04618 04619 ExprResult DefArgResult; 04620 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 04621 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 04622 DefArgResult = ParseBraceInitializer(); 04623 } else 04624 DefArgResult = ParseAssignmentExpression(); 04625 if (DefArgResult.isInvalid()) { 04626 Actions.ActOnParamDefaultArgumentError(Param); 04627 SkipUntil(tok::comma, tok::r_paren, true, true); 04628 } else { 04629 // Inform the actions module about the default argument 04630 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 04631 DefArgResult.take()); 04632 } 04633 } 04634 } 04635 04636 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 04637 ParmDecl.getIdentifierLoc(), Param, 04638 DefArgToks)); 04639 } 04640 04641 // If the next token is a comma, consume it and keep reading arguments. 04642 if (Tok.isNot(tok::comma)) { 04643 if (Tok.is(tok::ellipsis)) { 04644 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 04645 04646 if (!getLangOpts().CPlusPlus) { 04647 // We have ellipsis without a preceding ',', which is ill-formed 04648 // in C. Complain and provide the fix. 04649 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 04650 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 04651 } 04652 } 04653 04654 break; 04655 } 04656 04657 // Consume the comma. 04658 ConsumeToken(); 04659 } 04660 04661 } 04662 04663 /// [C90] direct-declarator '[' constant-expression[opt] ']' 04664 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 04665 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 04666 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 04667 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 04668 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 04669 /// attribute-specifier-seq[opt] 04670 void Parser::ParseBracketDeclarator(Declarator &D) { 04671 if (CheckProhibitedCXX11Attribute()) 04672 return; 04673 04674 BalancedDelimiterTracker T(*this, tok::l_square); 04675 T.consumeOpen(); 04676 04677 // C array syntax has many features, but by-far the most common is [] and [4]. 04678 // This code does a fast path to handle some of the most obvious cases. 04679 if (Tok.getKind() == tok::r_square) { 04680 T.consumeClose(); 04681 ParsedAttributes attrs(AttrFactory); 04682 MaybeParseCXX0XAttributes(attrs); 04683 04684 // Remember that we parsed the empty array type. 04685 ExprResult NumElements; 04686 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, 04687 T.getOpenLocation(), 04688 T.getCloseLocation()), 04689 attrs, T.getCloseLocation()); 04690 return; 04691 } else if (Tok.getKind() == tok::numeric_constant && 04692 GetLookAheadToken(1).is(tok::r_square)) { 04693 // [4] is very common. Parse the numeric constant expression. 04694 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); 04695 ConsumeToken(); 04696 04697 T.consumeClose(); 04698 ParsedAttributes attrs(AttrFactory); 04699 MaybeParseCXX0XAttributes(attrs); 04700 04701 // Remember that we parsed a array type, and remember its features. 04702 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, 04703 ExprRes.release(), 04704 T.getOpenLocation(), 04705 T.getCloseLocation()), 04706 attrs, T.getCloseLocation()); 04707 return; 04708 } 04709 04710 // If valid, this location is the position where we read the 'static' keyword. 04711 SourceLocation StaticLoc; 04712 if (Tok.is(tok::kw_static)) 04713 StaticLoc = ConsumeToken(); 04714 04715 // If there is a type-qualifier-list, read it now. 04716 // Type qualifiers in an array subscript are a C99 feature. 04717 DeclSpec DS(AttrFactory); 04718 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 04719 04720 // If we haven't already read 'static', check to see if there is one after the 04721 // type-qualifier-list. 04722 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 04723 StaticLoc = ConsumeToken(); 04724 04725 // Handle "direct-declarator [ type-qual-list[opt] * ]". 04726 bool isStar = false; 04727 ExprResult NumElements; 04728 04729 // Handle the case where we have '[*]' as the array size. However, a leading 04730 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 04731 // the the token after the star is a ']'. Since stars in arrays are 04732 // infrequent, use of lookahead is not costly here. 04733 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 04734 ConsumeToken(); // Eat the '*'. 04735 04736 if (StaticLoc.isValid()) { 04737 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 04738 StaticLoc = SourceLocation(); // Drop the static. 04739 } 04740 isStar = true; 04741 } else if (Tok.isNot(tok::r_square)) { 04742 // Note, in C89, this production uses the constant-expr production instead 04743 // of assignment-expr. The only difference is that assignment-expr allows 04744 // things like '=' and '*='. Sema rejects these in C89 mode because they 04745 // are not i-c-e's, so we don't need to distinguish between the two here. 04746 04747 // Parse the constant-expression or assignment-expression now (depending 04748 // on dialect). 04749 if (getLangOpts().CPlusPlus) { 04750 NumElements = ParseConstantExpression(); 04751 } else { 04752 EnterExpressionEvaluationContext Unevaluated(Actions, 04753 Sema::ConstantEvaluated); 04754 NumElements = ParseAssignmentExpression(); 04755 } 04756 } 04757 04758 // If there was an error parsing the assignment-expression, recover. 04759 if (NumElements.isInvalid()) { 04760 D.setInvalidType(true); 04761 // If the expression was invalid, skip it. 04762 SkipUntil(tok::r_square); 04763 return; 04764 } 04765 04766 T.consumeClose(); 04767 04768 ParsedAttributes attrs(AttrFactory); 04769 MaybeParseCXX0XAttributes(attrs); 04770 04771 // Remember that we parsed a array type, and remember its features. 04772 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 04773 StaticLoc.isValid(), isStar, 04774 NumElements.release(), 04775 T.getOpenLocation(), 04776 T.getCloseLocation()), 04777 attrs, T.getCloseLocation()); 04778 } 04779 04780 /// [GNU] typeof-specifier: 04781 /// typeof ( expressions ) 04782 /// typeof ( type-name ) 04783 /// [GNU/C++] typeof unary-expression 04784 /// 04785 void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 04786 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 04787 Token OpTok = Tok; 04788 SourceLocation StartLoc = ConsumeToken(); 04789 04790 const bool hasParens = Tok.is(tok::l_paren); 04791 04792 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 04793 04794 bool isCastExpr; 04795 ParsedType CastTy; 04796 SourceRange CastRange; 04797 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, 04798 CastTy, CastRange); 04799 if (hasParens) 04800 DS.setTypeofParensRange(CastRange); 04801 04802 if (CastRange.getEnd().isInvalid()) 04803 // FIXME: Not accurate, the range gets one token more than it should. 04804 DS.SetRangeEnd(Tok.getLocation()); 04805 else 04806 DS.SetRangeEnd(CastRange.getEnd()); 04807 04808 if (isCastExpr) { 04809 if (!CastTy) { 04810 DS.SetTypeSpecError(); 04811 return; 04812 } 04813 04814 const char *PrevSpec = 0; 04815 unsigned DiagID; 04816 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 04817 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 04818 DiagID, CastTy)) 04819 Diag(StartLoc, DiagID) << PrevSpec; 04820 return; 04821 } 04822 04823 // If we get here, the operand to the typeof was an expresion. 04824 if (Operand.isInvalid()) { 04825 DS.SetTypeSpecError(); 04826 return; 04827 } 04828 04829 // We might need to transform the operand if it is potentially evaluated. 04830 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 04831 if (Operand.isInvalid()) { 04832 DS.SetTypeSpecError(); 04833 return; 04834 } 04835 04836 const char *PrevSpec = 0; 04837 unsigned DiagID; 04838 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 04839 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 04840 DiagID, Operand.get())) 04841 Diag(StartLoc, DiagID) << PrevSpec; 04842 } 04843 04844 /// [C11] atomic-specifier: 04845 /// _Atomic ( type-name ) 04846 /// 04847 void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 04848 assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier"); 04849 04850 SourceLocation StartLoc = ConsumeToken(); 04851 BalancedDelimiterTracker T(*this, tok::l_paren); 04852 if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) { 04853 SkipUntil(tok::r_paren); 04854 return; 04855 } 04856 04857 TypeResult Result = ParseTypeName(); 04858 if (Result.isInvalid()) { 04859 SkipUntil(tok::r_paren); 04860 return; 04861 } 04862 04863 // Match the ')' 04864 T.consumeClose(); 04865 04866 if (T.getCloseLocation().isInvalid()) 04867 return; 04868 04869 DS.setTypeofParensRange(T.getRange()); 04870 DS.SetRangeEnd(T.getCloseLocation()); 04871 04872 const char *PrevSpec = 0; 04873 unsigned DiagID; 04874 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 04875 DiagID, Result.release())) 04876 Diag(StartLoc, DiagID) << PrevSpec; 04877 } 04878 04879 04880 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 04881 /// from TryAltiVecVectorToken. 04882 bool Parser::TryAltiVecVectorTokenOutOfLine() { 04883 Token Next = NextToken(); 04884 switch (Next.getKind()) { 04885 default: return false; 04886 case tok::kw_short: 04887 case tok::kw_long: 04888 case tok::kw_signed: 04889 case tok::kw_unsigned: 04890 case tok::kw_void: 04891 case tok::kw_char: 04892 case tok::kw_int: 04893 case tok::kw_float: 04894 case tok::kw_double: 04895 case tok::kw_bool: 04896 case tok::kw___pixel: 04897 Tok.setKind(tok::kw___vector); 04898 return true; 04899 case tok::identifier: 04900 if (Next.getIdentifierInfo() == Ident_pixel) { 04901 Tok.setKind(tok::kw___vector); 04902 return true; 04903 } 04904 return false; 04905 } 04906 } 04907 04908 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 04909 const char *&PrevSpec, unsigned &DiagID, 04910 bool &isInvalid) { 04911 if (Tok.getIdentifierInfo() == Ident_vector) { 04912 Token Next = NextToken(); 04913 switch (Next.getKind()) { 04914 case tok::kw_short: 04915 case tok::kw_long: 04916 case tok::kw_signed: 04917 case tok::kw_unsigned: 04918 case tok::kw_void: 04919 case tok::kw_char: 04920 case tok::kw_int: 04921 case tok::kw_float: 04922 case tok::kw_double: 04923 case tok::kw_bool: 04924 case tok::kw___pixel: 04925 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 04926 return true; 04927 case tok::identifier: 04928 if (Next.getIdentifierInfo() == Ident_pixel) { 04929 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 04930 return true; 04931 } 04932 break; 04933 default: 04934 break; 04935 } 04936 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 04937 DS.isTypeAltiVecVector()) { 04938 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 04939 return true; 04940 } 04941 return false; 04942 }