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 "RAIIObjectsForParser.h" 00016 #include "clang/AST/ASTContext.h" 00017 #include "clang/AST/DeclTemplate.h" 00018 #include "clang/Basic/AddressSpaces.h" 00019 #include "clang/Basic/Attributes.h" 00020 #include "clang/Basic/CharInfo.h" 00021 #include "clang/Basic/TargetInfo.h" 00022 #include "clang/Parse/ParseDiagnostic.h" 00023 #include "clang/Sema/Lookup.h" 00024 #include "clang/Sema/ParsedTemplate.h" 00025 #include "clang/Sema/PrettyDeclStackTrace.h" 00026 #include "clang/Sema/Scope.h" 00027 #include "llvm/ADT/SmallSet.h" 00028 #include "llvm/ADT/SmallString.h" 00029 #include "llvm/ADT/StringSwitch.h" 00030 using namespace clang; 00031 00032 //===----------------------------------------------------------------------===// 00033 // C99 6.7: Declarations. 00034 //===----------------------------------------------------------------------===// 00035 00036 /// ParseTypeName 00037 /// type-name: [C99 6.7.6] 00038 /// specifier-qualifier-list abstract-declarator[opt] 00039 /// 00040 /// Called type-id in C++. 00041 TypeResult Parser::ParseTypeName(SourceRange *Range, 00042 Declarator::TheContext Context, 00043 AccessSpecifier AS, 00044 Decl **OwnedType, 00045 ParsedAttributes *Attrs) { 00046 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context); 00047 if (DSC == DSC_normal) 00048 DSC = DSC_type_specifier; 00049 00050 // Parse the common declaration-specifiers piece. 00051 DeclSpec DS(AttrFactory); 00052 if (Attrs) 00053 DS.addAttributes(Attrs->getList()); 00054 ParseSpecifierQualifierList(DS, AS, DSC); 00055 if (OwnedType) 00056 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr; 00057 00058 // Parse the abstract-declarator, if present. 00059 Declarator DeclaratorInfo(DS, Context); 00060 ParseDeclarator(DeclaratorInfo); 00061 if (Range) 00062 *Range = DeclaratorInfo.getSourceRange(); 00063 00064 if (DeclaratorInfo.isInvalidType()) 00065 return true; 00066 00067 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 00068 } 00069 00070 00071 /// isAttributeLateParsed - Return true if the attribute has arguments that 00072 /// require late parsing. 00073 static bool isAttributeLateParsed(const IdentifierInfo &II) { 00074 #define CLANG_ATTR_LATE_PARSED_LIST 00075 return llvm::StringSwitch<bool>(II.getName()) 00076 #include "clang/Parse/AttrParserStringSwitches.inc" 00077 .Default(false); 00078 #undef CLANG_ATTR_LATE_PARSED_LIST 00079 } 00080 00081 /// ParseGNUAttributes - Parse a non-empty attributes list. 00082 /// 00083 /// [GNU] attributes: 00084 /// attribute 00085 /// attributes attribute 00086 /// 00087 /// [GNU] attribute: 00088 /// '__attribute__' '(' '(' attribute-list ')' ')' 00089 /// 00090 /// [GNU] attribute-list: 00091 /// attrib 00092 /// attribute_list ',' attrib 00093 /// 00094 /// [GNU] attrib: 00095 /// empty 00096 /// attrib-name 00097 /// attrib-name '(' identifier ')' 00098 /// attrib-name '(' identifier ',' nonempty-expr-list ')' 00099 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 00100 /// 00101 /// [GNU] attrib-name: 00102 /// identifier 00103 /// typespec 00104 /// typequal 00105 /// storageclass 00106 /// 00107 /// Whether an attribute takes an 'identifier' is determined by the 00108 /// attrib-name. GCC's behavior here is not worth imitating: 00109 /// 00110 /// * In C mode, if the attribute argument list starts with an identifier 00111 /// followed by a ',' or an ')', and the identifier doesn't resolve to 00112 /// a type, it is parsed as an identifier. If the attribute actually 00113 /// wanted an expression, it's out of luck (but it turns out that no 00114 /// attributes work that way, because C constant expressions are very 00115 /// limited). 00116 /// * In C++ mode, if the attribute argument list starts with an identifier, 00117 /// and the attribute *wants* an identifier, it is parsed as an identifier. 00118 /// At block scope, any additional tokens between the identifier and the 00119 /// ',' or ')' are ignored, otherwise they produce a parse error. 00120 /// 00121 /// We follow the C++ model, but don't allow junk after the identifier. 00122 void Parser::ParseGNUAttributes(ParsedAttributes &attrs, 00123 SourceLocation *endLoc, 00124 LateParsedAttrList *LateAttrs, 00125 Declarator *D) { 00126 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); 00127 00128 while (Tok.is(tok::kw___attribute)) { 00129 ConsumeToken(); 00130 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 00131 "attribute")) { 00132 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; 00133 return; 00134 } 00135 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 00136 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; 00137 return; 00138 } 00139 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 00140 while (true) { 00141 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,)) 00142 if (TryConsumeToken(tok::comma)) 00143 continue; 00144 00145 // Expect an identifier or declaration specifier (const, int, etc.) 00146 if (Tok.isNot(tok::identifier) && !isDeclarationSpecifier()) 00147 break; 00148 00149 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00150 SourceLocation AttrNameLoc = ConsumeToken(); 00151 00152 if (Tok.isNot(tok::l_paren)) { 00153 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 00154 AttributeList::AS_GNU); 00155 continue; 00156 } 00157 00158 // Handle "parameterized" attributes 00159 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) { 00160 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr, 00161 SourceLocation(), AttributeList::AS_GNU, D); 00162 continue; 00163 } 00164 00165 // Handle attributes with arguments that require late parsing. 00166 LateParsedAttribute *LA = 00167 new LateParsedAttribute(this, *AttrName, AttrNameLoc); 00168 LateAttrs->push_back(LA); 00169 00170 // Attributes in a class are parsed at the end of the class, along 00171 // with other late-parsed declarations. 00172 if (!ClassStack.empty() && !LateAttrs->parseSoon()) 00173 getCurrentClass().LateParsedDeclarations.push_back(LA); 00174 00175 // consume everything up to and including the matching right parens 00176 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false); 00177 00178 Token Eof; 00179 Eof.startToken(); 00180 Eof.setLocation(Tok.getLocation()); 00181 LA->Toks.push_back(Eof); 00182 } 00183 00184 if (ExpectAndConsume(tok::r_paren)) 00185 SkipUntil(tok::r_paren, StopAtSemi); 00186 SourceLocation Loc = Tok.getLocation(); 00187 if (ExpectAndConsume(tok::r_paren)) 00188 SkipUntil(tok::r_paren, StopAtSemi); 00189 if (endLoc) 00190 *endLoc = Loc; 00191 } 00192 } 00193 00194 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __. 00195 static StringRef normalizeAttrName(StringRef Name) { 00196 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__")) 00197 Name = Name.drop_front(2).drop_back(2); 00198 return Name; 00199 } 00200 00201 /// \brief Determine whether the given attribute has an identifier argument. 00202 static bool attributeHasIdentifierArg(const IdentifierInfo &II) { 00203 #define CLANG_ATTR_IDENTIFIER_ARG_LIST 00204 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 00205 #include "clang/Parse/AttrParserStringSwitches.inc" 00206 .Default(false); 00207 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST 00208 } 00209 00210 /// \brief Determine whether the given attribute parses a type argument. 00211 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) { 00212 #define CLANG_ATTR_TYPE_ARG_LIST 00213 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 00214 #include "clang/Parse/AttrParserStringSwitches.inc" 00215 .Default(false); 00216 #undef CLANG_ATTR_TYPE_ARG_LIST 00217 } 00218 00219 /// \brief Determine whether the given attribute requires parsing its arguments 00220 /// in an unevaluated context or not. 00221 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) { 00222 #define CLANG_ATTR_ARG_CONTEXT_LIST 00223 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) 00224 #include "clang/Parse/AttrParserStringSwitches.inc" 00225 .Default(false); 00226 #undef CLANG_ATTR_ARG_CONTEXT_LIST 00227 } 00228 00229 IdentifierLoc *Parser::ParseIdentifierLoc() { 00230 assert(Tok.is(tok::identifier) && "expected an identifier"); 00231 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context, 00232 Tok.getLocation(), 00233 Tok.getIdentifierInfo()); 00234 ConsumeToken(); 00235 return IL; 00236 } 00237 00238 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName, 00239 SourceLocation AttrNameLoc, 00240 ParsedAttributes &Attrs, 00241 SourceLocation *EndLoc, 00242 IdentifierInfo *ScopeName, 00243 SourceLocation ScopeLoc, 00244 AttributeList::Syntax Syntax) { 00245 BalancedDelimiterTracker Parens(*this, tok::l_paren); 00246 Parens.consumeOpen(); 00247 00248 TypeResult T; 00249 if (Tok.isNot(tok::r_paren)) 00250 T = ParseTypeName(); 00251 00252 if (Parens.consumeClose()) 00253 return; 00254 00255 if (T.isInvalid()) 00256 return; 00257 00258 if (T.isUsable()) 00259 Attrs.addNewTypeAttr(&AttrName, 00260 SourceRange(AttrNameLoc, Parens.getCloseLocation()), 00261 ScopeName, ScopeLoc, T.get(), Syntax); 00262 else 00263 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()), 00264 ScopeName, ScopeLoc, nullptr, 0, Syntax); 00265 } 00266 00267 unsigned Parser::ParseAttributeArgsCommon( 00268 IdentifierInfo *AttrName, SourceLocation AttrNameLoc, 00269 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, 00270 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { 00271 // Ignore the left paren location for now. 00272 ConsumeParen(); 00273 00274 ArgsVector ArgExprs; 00275 if (Tok.is(tok::identifier)) { 00276 // If this attribute wants an 'identifier' argument, make it so. 00277 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName); 00278 AttributeList::Kind AttrKind = 00279 AttributeList::getKind(AttrName, ScopeName, Syntax); 00280 00281 // If we don't know how to parse this attribute, but this is the only 00282 // token in this argument, assume it's meant to be an identifier. 00283 if (AttrKind == AttributeList::UnknownAttribute || 00284 AttrKind == AttributeList::IgnoredAttribute) { 00285 const Token &Next = NextToken(); 00286 IsIdentifierArg = Next.is(tok::r_paren) || Next.is(tok::comma); 00287 } 00288 00289 if (IsIdentifierArg) 00290 ArgExprs.push_back(ParseIdentifierLoc()); 00291 } 00292 00293 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) { 00294 // Eat the comma. 00295 if (!ArgExprs.empty()) 00296 ConsumeToken(); 00297 00298 // Parse the non-empty comma-separated list of expressions. 00299 do { 00300 std::unique_ptr<EnterExpressionEvaluationContext> Unevaluated; 00301 if (attributeParsedArgsUnevaluated(*AttrName)) 00302 Unevaluated.reset( 00303 new EnterExpressionEvaluationContext(Actions, Sema::Unevaluated)); 00304 00305 ExprResult ArgExpr(ParseAssignmentExpression()); 00306 if (ArgExpr.isInvalid()) { 00307 SkipUntil(tok::r_paren, StopAtSemi); 00308 return 0; 00309 } 00310 ArgExprs.push_back(ArgExpr.get()); 00311 // Eat the comma, move to the next argument 00312 } while (TryConsumeToken(tok::comma)); 00313 } 00314 00315 SourceLocation RParen = Tok.getLocation(); 00316 if (!ExpectAndConsume(tok::r_paren)) { 00317 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc; 00318 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc, 00319 ArgExprs.data(), ArgExprs.size(), Syntax); 00320 } 00321 00322 if (EndLoc) 00323 *EndLoc = RParen; 00324 00325 return static_cast<unsigned>(ArgExprs.size()); 00326 } 00327 00328 /// Parse the arguments to a parameterized GNU attribute or 00329 /// a C++11 attribute in "gnu" namespace. 00330 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName, 00331 SourceLocation AttrNameLoc, 00332 ParsedAttributes &Attrs, 00333 SourceLocation *EndLoc, 00334 IdentifierInfo *ScopeName, 00335 SourceLocation ScopeLoc, 00336 AttributeList::Syntax Syntax, 00337 Declarator *D) { 00338 00339 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 00340 00341 AttributeList::Kind AttrKind = 00342 AttributeList::getKind(AttrName, ScopeName, Syntax); 00343 00344 if (AttrKind == AttributeList::AT_Availability) { 00345 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 00346 ScopeLoc, Syntax); 00347 return; 00348 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) { 00349 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 00350 ScopeName, ScopeLoc, Syntax); 00351 return; 00352 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) { 00353 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, 00354 ScopeName, ScopeLoc, Syntax); 00355 return; 00356 } else if (attributeIsTypeArgAttr(*AttrName)) { 00357 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 00358 ScopeLoc, Syntax); 00359 return; 00360 } 00361 00362 // These may refer to the function arguments, but need to be parsed early to 00363 // participate in determining whether it's a redeclaration. 00364 std::unique_ptr<ParseScope> PrototypeScope; 00365 if (AttrName->isStr("enable_if") && D && D->isFunctionDeclarator()) { 00366 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo(); 00367 PrototypeScope.reset(new ParseScope(this, Scope::FunctionPrototypeScope | 00368 Scope::FunctionDeclarationScope | 00369 Scope::DeclScope)); 00370 for (unsigned i = 0; i != FTI.NumParams; ++i) { 00371 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 00372 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param); 00373 } 00374 } 00375 00376 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 00377 ScopeLoc, Syntax); 00378 } 00379 00380 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, 00381 SourceLocation AttrNameLoc, 00382 ParsedAttributes &Attrs) { 00383 // If the attribute isn't known, we will not attempt to parse any 00384 // arguments. 00385 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName, 00386 getTargetInfo().getTriple(), getLangOpts())) { 00387 // Eat the left paren, then skip to the ending right paren. 00388 ConsumeParen(); 00389 SkipUntil(tok::r_paren); 00390 return false; 00391 } 00392 00393 SourceLocation OpenParenLoc = Tok.getLocation(); 00394 00395 if (AttrName->getName() == "property") { 00396 // The property declspec is more complex in that it can take one or two 00397 // assignment expressions as a parameter, but the lhs of the assignment 00398 // must be named get or put. 00399 00400 BalancedDelimiterTracker T(*this, tok::l_paren); 00401 T.expectAndConsume(diag::err_expected_lparen_after, 00402 AttrName->getNameStart(), tok::r_paren); 00403 00404 enum AccessorKind { 00405 AK_Invalid = -1, 00406 AK_Put = 0, 00407 AK_Get = 1 // indices into AccessorNames 00408 }; 00409 IdentifierInfo *AccessorNames[] = {nullptr, nullptr}; 00410 bool HasInvalidAccessor = false; 00411 00412 // Parse the accessor specifications. 00413 while (true) { 00414 // Stop if this doesn't look like an accessor spec. 00415 if (!Tok.is(tok::identifier)) { 00416 // If the user wrote a completely empty list, use a special diagnostic. 00417 if (Tok.is(tok::r_paren) && !HasInvalidAccessor && 00418 AccessorNames[AK_Put] == nullptr && 00419 AccessorNames[AK_Get] == nullptr) { 00420 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter); 00421 break; 00422 } 00423 00424 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor); 00425 break; 00426 } 00427 00428 AccessorKind Kind; 00429 SourceLocation KindLoc = Tok.getLocation(); 00430 StringRef KindStr = Tok.getIdentifierInfo()->getName(); 00431 if (KindStr == "get") { 00432 Kind = AK_Get; 00433 } else if (KindStr == "put") { 00434 Kind = AK_Put; 00435 00436 // Recover from the common mistake of using 'set' instead of 'put'. 00437 } else if (KindStr == "set") { 00438 Diag(KindLoc, diag::err_ms_property_has_set_accessor) 00439 << FixItHint::CreateReplacement(KindLoc, "put"); 00440 Kind = AK_Put; 00441 00442 // Handle the mistake of forgetting the accessor kind by skipping 00443 // this accessor. 00444 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) { 00445 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind); 00446 ConsumeToken(); 00447 HasInvalidAccessor = true; 00448 goto next_property_accessor; 00449 00450 // Otherwise, complain about the unknown accessor kind. 00451 } else { 00452 Diag(KindLoc, diag::err_ms_property_unknown_accessor); 00453 HasInvalidAccessor = true; 00454 Kind = AK_Invalid; 00455 00456 // Try to keep parsing unless it doesn't look like an accessor spec. 00457 if (!NextToken().is(tok::equal)) 00458 break; 00459 } 00460 00461 // Consume the identifier. 00462 ConsumeToken(); 00463 00464 // Consume the '='. 00465 if (!TryConsumeToken(tok::equal)) { 00466 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal) 00467 << KindStr; 00468 break; 00469 } 00470 00471 // Expect the method name. 00472 if (!Tok.is(tok::identifier)) { 00473 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name); 00474 break; 00475 } 00476 00477 if (Kind == AK_Invalid) { 00478 // Just drop invalid accessors. 00479 } else if (AccessorNames[Kind] != nullptr) { 00480 // Complain about the repeated accessor, ignore it, and keep parsing. 00481 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr; 00482 } else { 00483 AccessorNames[Kind] = Tok.getIdentifierInfo(); 00484 } 00485 ConsumeToken(); 00486 00487 next_property_accessor: 00488 // Keep processing accessors until we run out. 00489 if (TryConsumeToken(tok::comma)) 00490 continue; 00491 00492 // If we run into the ')', stop without consuming it. 00493 if (Tok.is(tok::r_paren)) 00494 break; 00495 00496 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen); 00497 break; 00498 } 00499 00500 // Only add the property attribute if it was well-formed. 00501 if (!HasInvalidAccessor) 00502 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(), 00503 AccessorNames[AK_Get], AccessorNames[AK_Put], 00504 AttributeList::AS_Declspec); 00505 T.skipToEnd(); 00506 return !HasInvalidAccessor; 00507 } 00508 00509 unsigned NumArgs = 00510 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr, 00511 SourceLocation(), AttributeList::AS_Declspec); 00512 00513 // If this attribute's args were parsed, and it was expected to have 00514 // arguments but none were provided, emit a diagnostic. 00515 const AttributeList *Attr = Attrs.getList(); 00516 if (Attr && Attr->getMaxArgs() && !NumArgs) { 00517 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName; 00518 return false; 00519 } 00520 return true; 00521 } 00522 00523 /// [MS] decl-specifier: 00524 /// __declspec ( extended-decl-modifier-seq ) 00525 /// 00526 /// [MS] extended-decl-modifier-seq: 00527 /// extended-decl-modifier[opt] 00528 /// extended-decl-modifier extended-decl-modifier-seq 00529 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) { 00530 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 00531 00532 ConsumeToken(); 00533 BalancedDelimiterTracker T(*this, tok::l_paren); 00534 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec", 00535 tok::r_paren)) 00536 return; 00537 00538 // An empty declspec is perfectly legal and should not warn. Additionally, 00539 // you can specify multiple attributes per declspec. 00540 while (Tok.isNot(tok::r_paren)) { 00541 // Attribute not present. 00542 if (TryConsumeToken(tok::comma)) 00543 continue; 00544 00545 // We expect either a well-known identifier or a generic string. Anything 00546 // else is a malformed declspec. 00547 bool IsString = Tok.getKind() == tok::string_literal ? true : false; 00548 if (!IsString && Tok.getKind() != tok::identifier && 00549 Tok.getKind() != tok::kw_restrict) { 00550 Diag(Tok, diag::err_ms_declspec_type); 00551 T.skipToEnd(); 00552 return; 00553 } 00554 00555 IdentifierInfo *AttrName; 00556 SourceLocation AttrNameLoc; 00557 if (IsString) { 00558 SmallString<8> StrBuffer; 00559 bool Invalid = false; 00560 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid); 00561 if (Invalid) { 00562 T.skipToEnd(); 00563 return; 00564 } 00565 AttrName = PP.getIdentifierInfo(Str); 00566 AttrNameLoc = ConsumeStringToken(); 00567 } else { 00568 AttrName = Tok.getIdentifierInfo(); 00569 AttrNameLoc = ConsumeToken(); 00570 } 00571 00572 bool AttrHandled = false; 00573 00574 // Parse attribute arguments. 00575 if (Tok.is(tok::l_paren)) 00576 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs); 00577 else if (AttrName->getName() == "property") 00578 // The property attribute must have an argument list. 00579 Diag(Tok.getLocation(), diag::err_expected_lparen_after) 00580 << AttrName->getName(); 00581 00582 if (!AttrHandled) 00583 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 00584 AttributeList::AS_Declspec); 00585 } 00586 T.consumeClose(); 00587 } 00588 00589 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { 00590 // Treat these like attributes 00591 while (true) { 00592 switch (Tok.getKind()) { 00593 case tok::kw___fastcall: 00594 case tok::kw___stdcall: 00595 case tok::kw___thiscall: 00596 case tok::kw___cdecl: 00597 case tok::kw___vectorcall: 00598 case tok::kw___ptr64: 00599 case tok::kw___w64: 00600 case tok::kw___ptr32: 00601 case tok::kw___unaligned: 00602 case tok::kw___sptr: 00603 case tok::kw___uptr: { 00604 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00605 SourceLocation AttrNameLoc = ConsumeToken(); 00606 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 00607 AttributeList::AS_Keyword); 00608 break; 00609 } 00610 default: 00611 return; 00612 } 00613 } 00614 } 00615 00616 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 00617 // Treat these like attributes 00618 while (Tok.is(tok::kw___pascal)) { 00619 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00620 SourceLocation AttrNameLoc = ConsumeToken(); 00621 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 00622 AttributeList::AS_Keyword); 00623 } 00624 } 00625 00626 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { 00627 // Treat these like attributes 00628 while (Tok.is(tok::kw___kernel)) { 00629 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00630 SourceLocation AttrNameLoc = ConsumeToken(); 00631 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 00632 AttributeList::AS_Keyword); 00633 } 00634 } 00635 00636 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) { 00637 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 00638 SourceLocation AttrNameLoc = Tok.getLocation(); 00639 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, 00640 AttributeList::AS_Keyword); 00641 } 00642 00643 static bool VersionNumberSeparator(const char Separator) { 00644 return (Separator == '.' || Separator == '_'); 00645 } 00646 00647 /// \brief Parse a version number. 00648 /// 00649 /// version: 00650 /// simple-integer 00651 /// simple-integer ',' simple-integer 00652 /// simple-integer ',' simple-integer ',' simple-integer 00653 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { 00654 Range = Tok.getLocation(); 00655 00656 if (!Tok.is(tok::numeric_constant)) { 00657 Diag(Tok, diag::err_expected_version); 00658 SkipUntil(tok::comma, tok::r_paren, 00659 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 00660 return VersionTuple(); 00661 } 00662 00663 // Parse the major (and possibly minor and subminor) versions, which 00664 // are stored in the numeric constant. We utilize a quirk of the 00665 // lexer, which is that it handles something like 1.2.3 as a single 00666 // numeric constant, rather than two separate tokens. 00667 SmallString<512> Buffer; 00668 Buffer.resize(Tok.getLength()+1); 00669 const char *ThisTokBegin = &Buffer[0]; 00670 00671 // Get the spelling of the token, which eliminates trigraphs, etc. 00672 bool Invalid = false; 00673 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 00674 if (Invalid) 00675 return VersionTuple(); 00676 00677 // Parse the major version. 00678 unsigned AfterMajor = 0; 00679 unsigned Major = 0; 00680 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) { 00681 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; 00682 ++AfterMajor; 00683 } 00684 00685 if (AfterMajor == 0) { 00686 Diag(Tok, diag::err_expected_version); 00687 SkipUntil(tok::comma, tok::r_paren, 00688 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 00689 return VersionTuple(); 00690 } 00691 00692 if (AfterMajor == ActualLength) { 00693 ConsumeToken(); 00694 00695 // We only had a single version component. 00696 if (Major == 0) { 00697 Diag(Tok, diag::err_zero_version); 00698 return VersionTuple(); 00699 } 00700 00701 return VersionTuple(Major); 00702 } 00703 00704 const char AfterMajorSeparator = ThisTokBegin[AfterMajor]; 00705 if (!VersionNumberSeparator(AfterMajorSeparator) 00706 || (AfterMajor + 1 == ActualLength)) { 00707 Diag(Tok, diag::err_expected_version); 00708 SkipUntil(tok::comma, tok::r_paren, 00709 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 00710 return VersionTuple(); 00711 } 00712 00713 // Parse the minor version. 00714 unsigned AfterMinor = AfterMajor + 1; 00715 unsigned Minor = 0; 00716 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) { 00717 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; 00718 ++AfterMinor; 00719 } 00720 00721 if (AfterMinor == ActualLength) { 00722 ConsumeToken(); 00723 00724 // We had major.minor. 00725 if (Major == 0 && Minor == 0) { 00726 Diag(Tok, diag::err_zero_version); 00727 return VersionTuple(); 00728 } 00729 00730 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_')); 00731 } 00732 00733 const char AfterMinorSeparator = ThisTokBegin[AfterMinor]; 00734 // If what follows is not a '.' or '_', we have a problem. 00735 if (!VersionNumberSeparator(AfterMinorSeparator)) { 00736 Diag(Tok, diag::err_expected_version); 00737 SkipUntil(tok::comma, tok::r_paren, 00738 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 00739 return VersionTuple(); 00740 } 00741 00742 // Warn if separators, be it '.' or '_', do not match. 00743 if (AfterMajorSeparator != AfterMinorSeparator) 00744 Diag(Tok, diag::warn_expected_consistent_version_separator); 00745 00746 // Parse the subminor version. 00747 unsigned AfterSubminor = AfterMinor + 1; 00748 unsigned Subminor = 0; 00749 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) { 00750 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; 00751 ++AfterSubminor; 00752 } 00753 00754 if (AfterSubminor != ActualLength) { 00755 Diag(Tok, diag::err_expected_version); 00756 SkipUntil(tok::comma, tok::r_paren, 00757 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 00758 return VersionTuple(); 00759 } 00760 ConsumeToken(); 00761 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_')); 00762 } 00763 00764 /// \brief Parse the contents of the "availability" attribute. 00765 /// 00766 /// availability-attribute: 00767 /// 'availability' '(' platform ',' version-arg-list, opt-message')' 00768 /// 00769 /// platform: 00770 /// identifier 00771 /// 00772 /// version-arg-list: 00773 /// version-arg 00774 /// version-arg ',' version-arg-list 00775 /// 00776 /// version-arg: 00777 /// 'introduced' '=' version 00778 /// 'deprecated' '=' version 00779 /// 'obsoleted' = version 00780 /// 'unavailable' 00781 /// opt-message: 00782 /// 'message' '=' <string> 00783 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, 00784 SourceLocation AvailabilityLoc, 00785 ParsedAttributes &attrs, 00786 SourceLocation *endLoc, 00787 IdentifierInfo *ScopeName, 00788 SourceLocation ScopeLoc, 00789 AttributeList::Syntax Syntax) { 00790 enum { Introduced, Deprecated, Obsoleted, Unknown }; 00791 AvailabilityChange Changes[Unknown]; 00792 ExprResult MessageExpr; 00793 00794 // Opening '('. 00795 BalancedDelimiterTracker T(*this, tok::l_paren); 00796 if (T.consumeOpen()) { 00797 Diag(Tok, diag::err_expected) << tok::l_paren; 00798 return; 00799 } 00800 00801 // Parse the platform name, 00802 if (Tok.isNot(tok::identifier)) { 00803 Diag(Tok, diag::err_availability_expected_platform); 00804 SkipUntil(tok::r_paren, StopAtSemi); 00805 return; 00806 } 00807 IdentifierLoc *Platform = ParseIdentifierLoc(); 00808 00809 // Parse the ',' following the platform name. 00810 if (ExpectAndConsume(tok::comma)) { 00811 SkipUntil(tok::r_paren, StopAtSemi); 00812 return; 00813 } 00814 00815 // If we haven't grabbed the pointers for the identifiers 00816 // "introduced", "deprecated", and "obsoleted", do so now. 00817 if (!Ident_introduced) { 00818 Ident_introduced = PP.getIdentifierInfo("introduced"); 00819 Ident_deprecated = PP.getIdentifierInfo("deprecated"); 00820 Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); 00821 Ident_unavailable = PP.getIdentifierInfo("unavailable"); 00822 Ident_message = PP.getIdentifierInfo("message"); 00823 } 00824 00825 // Parse the set of introductions/deprecations/removals. 00826 SourceLocation UnavailableLoc; 00827 do { 00828 if (Tok.isNot(tok::identifier)) { 00829 Diag(Tok, diag::err_availability_expected_change); 00830 SkipUntil(tok::r_paren, StopAtSemi); 00831 return; 00832 } 00833 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 00834 SourceLocation KeywordLoc = ConsumeToken(); 00835 00836 if (Keyword == Ident_unavailable) { 00837 if (UnavailableLoc.isValid()) { 00838 Diag(KeywordLoc, diag::err_availability_redundant) 00839 << Keyword << SourceRange(UnavailableLoc); 00840 } 00841 UnavailableLoc = KeywordLoc; 00842 continue; 00843 } 00844 00845 if (Tok.isNot(tok::equal)) { 00846 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal; 00847 SkipUntil(tok::r_paren, StopAtSemi); 00848 return; 00849 } 00850 ConsumeToken(); 00851 if (Keyword == Ident_message) { 00852 if (Tok.isNot(tok::string_literal)) { 00853 Diag(Tok, diag::err_expected_string_literal) 00854 << /*Source='availability attribute'*/2; 00855 SkipUntil(tok::r_paren, StopAtSemi); 00856 return; 00857 } 00858 MessageExpr = ParseStringLiteralExpression(); 00859 // Also reject wide string literals. 00860 if (StringLiteral *MessageStringLiteral = 00861 cast_or_null<StringLiteral>(MessageExpr.get())) { 00862 if (MessageStringLiteral->getCharByteWidth() != 1) { 00863 Diag(MessageStringLiteral->getSourceRange().getBegin(), 00864 diag::err_expected_string_literal) 00865 << /*Source='availability attribute'*/ 2; 00866 SkipUntil(tok::r_paren, StopAtSemi); 00867 return; 00868 } 00869 } 00870 break; 00871 } 00872 00873 // Special handling of 'NA' only when applied to introduced or 00874 // deprecated. 00875 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) && 00876 Tok.is(tok::identifier)) { 00877 IdentifierInfo *NA = Tok.getIdentifierInfo(); 00878 if (NA->getName() == "NA") { 00879 ConsumeToken(); 00880 if (Keyword == Ident_introduced) 00881 UnavailableLoc = KeywordLoc; 00882 continue; 00883 } 00884 } 00885 00886 SourceRange VersionRange; 00887 VersionTuple Version = ParseVersionTuple(VersionRange); 00888 00889 if (Version.empty()) { 00890 SkipUntil(tok::r_paren, StopAtSemi); 00891 return; 00892 } 00893 00894 unsigned Index; 00895 if (Keyword == Ident_introduced) 00896 Index = Introduced; 00897 else if (Keyword == Ident_deprecated) 00898 Index = Deprecated; 00899 else if (Keyword == Ident_obsoleted) 00900 Index = Obsoleted; 00901 else 00902 Index = Unknown; 00903 00904 if (Index < Unknown) { 00905 if (!Changes[Index].KeywordLoc.isInvalid()) { 00906 Diag(KeywordLoc, diag::err_availability_redundant) 00907 << Keyword 00908 << SourceRange(Changes[Index].KeywordLoc, 00909 Changes[Index].VersionRange.getEnd()); 00910 } 00911 00912 Changes[Index].KeywordLoc = KeywordLoc; 00913 Changes[Index].Version = Version; 00914 Changes[Index].VersionRange = VersionRange; 00915 } else { 00916 Diag(KeywordLoc, diag::err_availability_unknown_change) 00917 << Keyword << VersionRange; 00918 } 00919 00920 } while (TryConsumeToken(tok::comma)); 00921 00922 // Closing ')'. 00923 if (T.consumeClose()) 00924 return; 00925 00926 if (endLoc) 00927 *endLoc = T.getCloseLocation(); 00928 00929 // The 'unavailable' availability cannot be combined with any other 00930 // availability changes. Make sure that hasn't happened. 00931 if (UnavailableLoc.isValid()) { 00932 bool Complained = false; 00933 for (unsigned Index = Introduced; Index != Unknown; ++Index) { 00934 if (Changes[Index].KeywordLoc.isValid()) { 00935 if (!Complained) { 00936 Diag(UnavailableLoc, diag::warn_availability_and_unavailable) 00937 << SourceRange(Changes[Index].KeywordLoc, 00938 Changes[Index].VersionRange.getEnd()); 00939 Complained = true; 00940 } 00941 00942 // Clear out the availability. 00943 Changes[Index] = AvailabilityChange(); 00944 } 00945 } 00946 } 00947 00948 // Record this attribute 00949 attrs.addNew(&Availability, 00950 SourceRange(AvailabilityLoc, T.getCloseLocation()), 00951 ScopeName, ScopeLoc, 00952 Platform, 00953 Changes[Introduced], 00954 Changes[Deprecated], 00955 Changes[Obsoleted], 00956 UnavailableLoc, MessageExpr.get(), 00957 Syntax); 00958 } 00959 00960 /// \brief Parse the contents of the "objc_bridge_related" attribute. 00961 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')' 00962 /// related_class: 00963 /// Identifier 00964 /// 00965 /// opt-class_method: 00966 /// Identifier: | <empty> 00967 /// 00968 /// opt-instance_method: 00969 /// Identifier | <empty> 00970 /// 00971 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, 00972 SourceLocation ObjCBridgeRelatedLoc, 00973 ParsedAttributes &attrs, 00974 SourceLocation *endLoc, 00975 IdentifierInfo *ScopeName, 00976 SourceLocation ScopeLoc, 00977 AttributeList::Syntax Syntax) { 00978 // Opening '('. 00979 BalancedDelimiterTracker T(*this, tok::l_paren); 00980 if (T.consumeOpen()) { 00981 Diag(Tok, diag::err_expected) << tok::l_paren; 00982 return; 00983 } 00984 00985 // Parse the related class name. 00986 if (Tok.isNot(tok::identifier)) { 00987 Diag(Tok, diag::err_objcbridge_related_expected_related_class); 00988 SkipUntil(tok::r_paren, StopAtSemi); 00989 return; 00990 } 00991 IdentifierLoc *RelatedClass = ParseIdentifierLoc(); 00992 if (ExpectAndConsume(tok::comma)) { 00993 SkipUntil(tok::r_paren, StopAtSemi); 00994 return; 00995 } 00996 00997 // Parse optional class method name. 00998 IdentifierLoc *ClassMethod = nullptr; 00999 if (Tok.is(tok::identifier)) { 01000 ClassMethod = ParseIdentifierLoc(); 01001 if (!TryConsumeToken(tok::colon)) { 01002 Diag(Tok, diag::err_objcbridge_related_selector_name); 01003 SkipUntil(tok::r_paren, StopAtSemi); 01004 return; 01005 } 01006 } 01007 if (!TryConsumeToken(tok::comma)) { 01008 if (Tok.is(tok::colon)) 01009 Diag(Tok, diag::err_objcbridge_related_selector_name); 01010 else 01011 Diag(Tok, diag::err_expected) << tok::comma; 01012 SkipUntil(tok::r_paren, StopAtSemi); 01013 return; 01014 } 01015 01016 // Parse optional instance method name. 01017 IdentifierLoc *InstanceMethod = nullptr; 01018 if (Tok.is(tok::identifier)) 01019 InstanceMethod = ParseIdentifierLoc(); 01020 else if (Tok.isNot(tok::r_paren)) { 01021 Diag(Tok, diag::err_expected) << tok::r_paren; 01022 SkipUntil(tok::r_paren, StopAtSemi); 01023 return; 01024 } 01025 01026 // Closing ')'. 01027 if (T.consumeClose()) 01028 return; 01029 01030 if (endLoc) 01031 *endLoc = T.getCloseLocation(); 01032 01033 // Record this attribute 01034 attrs.addNew(&ObjCBridgeRelated, 01035 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()), 01036 ScopeName, ScopeLoc, 01037 RelatedClass, 01038 ClassMethod, 01039 InstanceMethod, 01040 Syntax); 01041 } 01042 01043 // Late Parsed Attributes: 01044 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods 01045 01046 void Parser::LateParsedDeclaration::ParseLexedAttributes() {} 01047 01048 void Parser::LateParsedClass::ParseLexedAttributes() { 01049 Self->ParseLexedAttributes(*Class); 01050 } 01051 01052 void Parser::LateParsedAttribute::ParseLexedAttributes() { 01053 Self->ParseLexedAttribute(*this, true, false); 01054 } 01055 01056 /// Wrapper class which calls ParseLexedAttribute, after setting up the 01057 /// scope appropriately. 01058 void Parser::ParseLexedAttributes(ParsingClass &Class) { 01059 // Deal with templates 01060 // FIXME: Test cases to make sure this does the right thing for templates. 01061 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 01062 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 01063 HasTemplateScope); 01064 if (HasTemplateScope) 01065 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 01066 01067 // Set or update the scope flags. 01068 bool AlreadyHasClassScope = Class.TopLevelClass; 01069 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; 01070 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 01071 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 01072 01073 // Enter the scope of nested classes 01074 if (!AlreadyHasClassScope) 01075 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), 01076 Class.TagOrTemplate); 01077 if (!Class.LateParsedDeclarations.empty()) { 01078 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){ 01079 Class.LateParsedDeclarations[i]->ParseLexedAttributes(); 01080 } 01081 } 01082 01083 if (!AlreadyHasClassScope) 01084 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), 01085 Class.TagOrTemplate); 01086 } 01087 01088 01089 /// \brief Parse all attributes in LAs, and attach them to Decl D. 01090 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 01091 bool EnterScope, bool OnDefinition) { 01092 assert(LAs.parseSoon() && 01093 "Attribute list should be marked for immediate parsing."); 01094 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { 01095 if (D) 01096 LAs[i]->addDecl(D); 01097 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); 01098 delete LAs[i]; 01099 } 01100 LAs.clear(); 01101 } 01102 01103 01104 /// \brief Finish parsing an attribute for which parsing was delayed. 01105 /// This will be called at the end of parsing a class declaration 01106 /// for each LateParsedAttribute. We consume the saved tokens and 01107 /// create an attribute with the arguments filled in. We add this 01108 /// to the Attribute list for the decl. 01109 void Parser::ParseLexedAttribute(LateParsedAttribute &LA, 01110 bool EnterScope, bool OnDefinition) { 01111 // Save the current token position. 01112 SourceLocation OrigLoc = Tok.getLocation(); 01113 01114 // Append the current token at the end of the new token stream so that it 01115 // doesn't get lost. 01116 LA.Toks.push_back(Tok); 01117 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false); 01118 // Consume the previously pushed token. 01119 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 01120 01121 ParsedAttributes Attrs(AttrFactory); 01122 SourceLocation endLoc; 01123 01124 if (LA.Decls.size() > 0) { 01125 Decl *D = LA.Decls[0]; 01126 NamedDecl *ND = dyn_cast<NamedDecl>(D); 01127 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 01128 01129 // Allow 'this' within late-parsed attributes. 01130 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0, 01131 ND && ND->isCXXInstanceMember()); 01132 01133 if (LA.Decls.size() == 1) { 01134 // If the Decl is templatized, add template parameters to scope. 01135 bool HasTemplateScope = EnterScope && D->isTemplateDecl(); 01136 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope); 01137 if (HasTemplateScope) 01138 Actions.ActOnReenterTemplateScope(Actions.CurScope, D); 01139 01140 // If the Decl is on a function, add function parameters to the scope. 01141 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate(); 01142 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope); 01143 if (HasFunScope) 01144 Actions.ActOnReenterFunctionContext(Actions.CurScope, D); 01145 01146 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 01147 nullptr, SourceLocation(), AttributeList::AS_GNU, 01148 nullptr); 01149 01150 if (HasFunScope) { 01151 Actions.ActOnExitFunctionContext(); 01152 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver 01153 } 01154 if (HasTemplateScope) { 01155 TempScope.Exit(); 01156 } 01157 } else { 01158 // If there are multiple decls, then the decl cannot be within the 01159 // function scope. 01160 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 01161 nullptr, SourceLocation(), AttributeList::AS_GNU, 01162 nullptr); 01163 } 01164 } else { 01165 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName(); 01166 } 01167 01168 const AttributeList *AL = Attrs.getList(); 01169 if (OnDefinition && AL && !AL->isCXX11Attribute() && 01170 AL->isKnownToGCC()) 01171 Diag(Tok, diag::warn_attribute_on_function_definition) 01172 << &LA.AttrName; 01173 01174 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) 01175 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs); 01176 01177 if (Tok.getLocation() != OrigLoc) { 01178 // Due to a parsing error, we either went over the cached tokens or 01179 // there are still cached tokens left, so we skip the leftover tokens. 01180 // Since this is an uncommon situation that should be avoided, use the 01181 // expensive isBeforeInTranslationUnit call. 01182 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 01183 OrigLoc)) 01184 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof)) 01185 ConsumeAnyToken(); 01186 } 01187 } 01188 01189 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, 01190 SourceLocation AttrNameLoc, 01191 ParsedAttributes &Attrs, 01192 SourceLocation *EndLoc, 01193 IdentifierInfo *ScopeName, 01194 SourceLocation ScopeLoc, 01195 AttributeList::Syntax Syntax) { 01196 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 01197 01198 BalancedDelimiterTracker T(*this, tok::l_paren); 01199 T.consumeOpen(); 01200 01201 if (Tok.isNot(tok::identifier)) { 01202 Diag(Tok, diag::err_expected) << tok::identifier; 01203 T.skipToEnd(); 01204 return; 01205 } 01206 IdentifierLoc *ArgumentKind = ParseIdentifierLoc(); 01207 01208 if (ExpectAndConsume(tok::comma)) { 01209 T.skipToEnd(); 01210 return; 01211 } 01212 01213 SourceRange MatchingCTypeRange; 01214 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange); 01215 if (MatchingCType.isInvalid()) { 01216 T.skipToEnd(); 01217 return; 01218 } 01219 01220 bool LayoutCompatible = false; 01221 bool MustBeNull = false; 01222 while (TryConsumeToken(tok::comma)) { 01223 if (Tok.isNot(tok::identifier)) { 01224 Diag(Tok, diag::err_expected) << tok::identifier; 01225 T.skipToEnd(); 01226 return; 01227 } 01228 IdentifierInfo *Flag = Tok.getIdentifierInfo(); 01229 if (Flag->isStr("layout_compatible")) 01230 LayoutCompatible = true; 01231 else if (Flag->isStr("must_be_null")) 01232 MustBeNull = true; 01233 else { 01234 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag; 01235 T.skipToEnd(); 01236 return; 01237 } 01238 ConsumeToken(); // consume flag 01239 } 01240 01241 if (!T.consumeClose()) { 01242 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc, 01243 ArgumentKind, MatchingCType.get(), 01244 LayoutCompatible, MustBeNull, Syntax); 01245 } 01246 01247 if (EndLoc) 01248 *EndLoc = T.getCloseLocation(); 01249 } 01250 01251 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets 01252 /// of a C++11 attribute-specifier in a location where an attribute is not 01253 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this 01254 /// situation. 01255 /// 01256 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if 01257 /// this doesn't appear to actually be an attribute-specifier, and the caller 01258 /// should try to parse it. 01259 bool Parser::DiagnoseProhibitedCXX11Attribute() { 01260 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)); 01261 01262 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) { 01263 case CAK_NotAttributeSpecifier: 01264 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute. 01265 return false; 01266 01267 case CAK_InvalidAttributeSpecifier: 01268 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute); 01269 return false; 01270 01271 case CAK_AttributeSpecifier: 01272 // Parse and discard the attributes. 01273 SourceLocation BeginLoc = ConsumeBracket(); 01274 ConsumeBracket(); 01275 SkipUntil(tok::r_square); 01276 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied"); 01277 SourceLocation EndLoc = ConsumeBracket(); 01278 Diag(BeginLoc, diag::err_attributes_not_allowed) 01279 << SourceRange(BeginLoc, EndLoc); 01280 return true; 01281 } 01282 llvm_unreachable("All cases handled above."); 01283 } 01284 01285 /// \brief We have found the opening square brackets of a C++11 01286 /// attribute-specifier in a location where an attribute is not permitted, but 01287 /// we know where the attributes ought to be written. Parse them anyway, and 01288 /// provide a fixit moving them to the right place. 01289 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, 01290 SourceLocation CorrectLocation) { 01291 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) || 01292 Tok.is(tok::kw_alignas)); 01293 01294 // Consume the attributes. 01295 SourceLocation Loc = Tok.getLocation(); 01296 ParseCXX11Attributes(Attrs); 01297 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true); 01298 01299 Diag(Loc, diag::err_attributes_not_allowed) 01300 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange) 01301 << FixItHint::CreateRemoval(AttrRange); 01302 } 01303 01304 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { 01305 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) 01306 << attrs.Range; 01307 } 01308 01309 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) { 01310 AttributeList *AttrList = attrs.getList(); 01311 while (AttrList) { 01312 if (AttrList->isCXX11Attribute()) { 01313 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr) 01314 << AttrList->getName(); 01315 AttrList->setInvalid(); 01316 } 01317 AttrList = AttrList->getNext(); 01318 } 01319 } 01320 01321 /// ParseDeclaration - Parse a full 'declaration', which consists of 01322 /// declaration-specifiers, some number of declarators, and a semicolon. 01323 /// 'Context' should be a Declarator::TheContext value. This returns the 01324 /// location of the semicolon in DeclEnd. 01325 /// 01326 /// declaration: [C99 6.7] 01327 /// block-declaration -> 01328 /// simple-declaration 01329 /// others [FIXME] 01330 /// [C++] template-declaration 01331 /// [C++] namespace-definition 01332 /// [C++] using-directive 01333 /// [C++] using-declaration 01334 /// [C++11/C11] static_assert-declaration 01335 /// others... [FIXME] 01336 /// 01337 Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context, 01338 SourceLocation &DeclEnd, 01339 ParsedAttributesWithRange &attrs) { 01340 ParenBraceBracketBalancer BalancerRAIIObj(*this); 01341 // Must temporarily exit the objective-c container scope for 01342 // parsing c none objective-c decls. 01343 ObjCDeclContextSwitch ObjCDC(*this); 01344 01345 Decl *SingleDecl = nullptr; 01346 Decl *OwnedType = nullptr; 01347 switch (Tok.getKind()) { 01348 case tok::kw_template: 01349 case tok::kw_export: 01350 ProhibitAttributes(attrs); 01351 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 01352 break; 01353 case tok::kw_inline: 01354 // Could be the start of an inline namespace. Allowed as an ext in C++03. 01355 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) { 01356 ProhibitAttributes(attrs); 01357 SourceLocation InlineLoc = ConsumeToken(); 01358 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); 01359 break; 01360 } 01361 return ParseSimpleDeclaration(Context, DeclEnd, attrs, 01362 true); 01363 case tok::kw_namespace: 01364 ProhibitAttributes(attrs); 01365 SingleDecl = ParseNamespace(Context, DeclEnd); 01366 break; 01367 case tok::kw_using: 01368 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 01369 DeclEnd, attrs, &OwnedType); 01370 break; 01371 case tok::kw_static_assert: 01372 case tok::kw__Static_assert: 01373 ProhibitAttributes(attrs); 01374 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 01375 break; 01376 default: 01377 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true); 01378 } 01379 01380 // This routine returns a DeclGroup, if the thing we parsed only contains a 01381 // single decl, convert it now. Alias declarations can also declare a type; 01382 // include that too if it is present. 01383 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType); 01384 } 01385 01386 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 01387 /// declaration-specifiers init-declarator-list[opt] ';' 01388 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt] 01389 /// init-declarator-list ';' 01390 ///[C90/C++]init-declarator-list ';' [TODO] 01391 /// [OMP] threadprivate-directive [TODO] 01392 /// 01393 /// for-range-declaration: [C++11 6.5p1: stmt.ranged] 01394 /// attribute-specifier-seq[opt] type-specifier-seq declarator 01395 /// 01396 /// If RequireSemi is false, this does not check for a ';' at the end of the 01397 /// declaration. If it is true, it checks for and eats it. 01398 /// 01399 /// If FRI is non-null, we might be parsing a for-range-declaration instead 01400 /// of a simple-declaration. If we find that we are, we also parse the 01401 /// for-range-initializer, and place it here. 01402 Parser::DeclGroupPtrTy 01403 Parser::ParseSimpleDeclaration(unsigned Context, 01404 SourceLocation &DeclEnd, 01405 ParsedAttributesWithRange &Attrs, 01406 bool RequireSemi, ForRangeInit *FRI) { 01407 // Parse the common declaration-specifiers piece. 01408 ParsingDeclSpec DS(*this); 01409 01410 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context); 01411 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext); 01412 01413 // If we had a free-standing type definition with a missing semicolon, we 01414 // may get this far before the problem becomes obvious. 01415 if (DS.hasTagDefinition() && 01416 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext)) 01417 return DeclGroupPtrTy(); 01418 01419 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 01420 // declaration-specifiers init-declarator-list[opt] ';' 01421 if (Tok.is(tok::semi)) { 01422 ProhibitAttributes(Attrs); 01423 DeclEnd = Tok.getLocation(); 01424 if (RequireSemi) ConsumeToken(); 01425 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 01426 DS); 01427 DS.complete(TheDecl); 01428 return Actions.ConvertDeclToDeclGroup(TheDecl); 01429 } 01430 01431 DS.takeAttributesFrom(Attrs); 01432 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI); 01433 } 01434 01435 /// Returns true if this might be the start of a declarator, or a common typo 01436 /// for a declarator. 01437 bool Parser::MightBeDeclarator(unsigned Context) { 01438 switch (Tok.getKind()) { 01439 case tok::annot_cxxscope: 01440 case tok::annot_template_id: 01441 case tok::caret: 01442 case tok::code_completion: 01443 case tok::coloncolon: 01444 case tok::ellipsis: 01445 case tok::kw___attribute: 01446 case tok::kw_operator: 01447 case tok::l_paren: 01448 case tok::star: 01449 return true; 01450 01451 case tok::amp: 01452 case tok::ampamp: 01453 return getLangOpts().CPlusPlus; 01454 01455 case tok::l_square: // Might be an attribute on an unnamed bit-field. 01456 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 && 01457 NextToken().is(tok::l_square); 01458 01459 case tok::colon: // Might be a typo for '::' or an unnamed bit-field. 01460 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus; 01461 01462 case tok::identifier: 01463 switch (NextToken().getKind()) { 01464 case tok::code_completion: 01465 case tok::coloncolon: 01466 case tok::comma: 01467 case tok::equal: 01468 case tok::equalequal: // Might be a typo for '='. 01469 case tok::kw_alignas: 01470 case tok::kw_asm: 01471 case tok::kw___attribute: 01472 case tok::l_brace: 01473 case tok::l_paren: 01474 case tok::l_square: 01475 case tok::less: 01476 case tok::r_brace: 01477 case tok::r_paren: 01478 case tok::r_square: 01479 case tok::semi: 01480 return true; 01481 01482 case tok::colon: 01483 // At namespace scope, 'identifier:' is probably a typo for 'identifier::' 01484 // and in block scope it's probably a label. Inside a class definition, 01485 // this is a bit-field. 01486 return Context == Declarator::MemberContext || 01487 (getLangOpts().CPlusPlus && Context == Declarator::FileContext); 01488 01489 case tok::identifier: // Possible virt-specifier. 01490 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken()); 01491 01492 default: 01493 return false; 01494 } 01495 01496 default: 01497 return false; 01498 } 01499 } 01500 01501 /// Skip until we reach something which seems like a sensible place to pick 01502 /// up parsing after a malformed declaration. This will sometimes stop sooner 01503 /// than SkipUntil(tok::r_brace) would, but will never stop later. 01504 void Parser::SkipMalformedDecl() { 01505 while (true) { 01506 switch (Tok.getKind()) { 01507 case tok::l_brace: 01508 // Skip until matching }, then stop. We've probably skipped over 01509 // a malformed class or function definition or similar. 01510 ConsumeBrace(); 01511 SkipUntil(tok::r_brace); 01512 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) { 01513 // This declaration isn't over yet. Keep skipping. 01514 continue; 01515 } 01516 TryConsumeToken(tok::semi); 01517 return; 01518 01519 case tok::l_square: 01520 ConsumeBracket(); 01521 SkipUntil(tok::r_square); 01522 continue; 01523 01524 case tok::l_paren: 01525 ConsumeParen(); 01526 SkipUntil(tok::r_paren); 01527 continue; 01528 01529 case tok::r_brace: 01530 return; 01531 01532 case tok::semi: 01533 ConsumeToken(); 01534 return; 01535 01536 case tok::kw_inline: 01537 // 'inline namespace' at the start of a line is almost certainly 01538 // a good place to pick back up parsing, except in an Objective-C 01539 // @interface context. 01540 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) && 01541 (!ParsingInObjCContainer || CurParsedObjCImpl)) 01542 return; 01543 break; 01544 01545 case tok::kw_namespace: 01546 // 'namespace' at the start of a line is almost certainly a good 01547 // place to pick back up parsing, except in an Objective-C 01548 // @interface context. 01549 if (Tok.isAtStartOfLine() && 01550 (!ParsingInObjCContainer || CurParsedObjCImpl)) 01551 return; 01552 break; 01553 01554 case tok::at: 01555 // @end is very much like } in Objective-C contexts. 01556 if (NextToken().isObjCAtKeyword(tok::objc_end) && 01557 ParsingInObjCContainer) 01558 return; 01559 break; 01560 01561 case tok::minus: 01562 case tok::plus: 01563 // - and + probably start new method declarations in Objective-C contexts. 01564 if (Tok.isAtStartOfLine() && ParsingInObjCContainer) 01565 return; 01566 break; 01567 01568 case tok::eof: 01569 case tok::annot_module_begin: 01570 case tok::annot_module_end: 01571 case tok::annot_module_include: 01572 return; 01573 01574 default: 01575 break; 01576 } 01577 01578 ConsumeAnyToken(); 01579 } 01580 } 01581 01582 /// ParseDeclGroup - Having concluded that this is either a function 01583 /// definition or a group of object declarations, actually parse the 01584 /// result. 01585 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 01586 unsigned Context, 01587 bool AllowFunctionDefinitions, 01588 SourceLocation *DeclEnd, 01589 ForRangeInit *FRI) { 01590 // Parse the first declarator. 01591 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); 01592 ParseDeclarator(D); 01593 01594 // Bail out if the first declarator didn't seem well-formed. 01595 if (!D.hasName() && !D.mayOmitIdentifier()) { 01596 SkipMalformedDecl(); 01597 return DeclGroupPtrTy(); 01598 } 01599 01600 // Save late-parsed attributes for now; they need to be parsed in the 01601 // appropriate function scope after the function Decl has been constructed. 01602 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList. 01603 LateParsedAttrList LateParsedAttrs(true); 01604 if (D.isFunctionDeclarator()) { 01605 MaybeParseGNUAttributes(D, &LateParsedAttrs); 01606 01607 // The _Noreturn keyword can't appear here, unlike the GNU noreturn 01608 // attribute. If we find the keyword here, tell the user to put it 01609 // at the start instead. 01610 if (Tok.is(tok::kw__Noreturn)) { 01611 SourceLocation Loc = ConsumeToken(); 01612 const char *PrevSpec; 01613 unsigned DiagID; 01614 01615 // We can offer a fixit if it's valid to mark this function as _Noreturn 01616 // and we don't have any other declarators in this declaration. 01617 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); 01618 MaybeParseGNUAttributes(D, &LateParsedAttrs); 01619 Fixit &= Tok.is(tok::semi) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try); 01620 01621 Diag(Loc, diag::err_c11_noreturn_misplaced) 01622 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint()) 01623 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ") 01624 : FixItHint()); 01625 } 01626 } 01627 01628 // Check to see if we have a function *definition* which must have a body. 01629 if (D.isFunctionDeclarator() && 01630 // Look at the next token to make sure that this isn't a function 01631 // declaration. We have to check this because __attribute__ might be the 01632 // start of a function definition in GCC-extended K&R C. 01633 !isDeclarationAfterDeclarator()) { 01634 01635 if (AllowFunctionDefinitions) { 01636 if (isStartOfFunctionDefinition(D)) { 01637 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 01638 Diag(Tok, diag::err_function_declared_typedef); 01639 01640 // Recover by treating the 'typedef' as spurious. 01641 DS.ClearStorageClassSpecs(); 01642 } 01643 01644 Decl *TheDecl = 01645 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs); 01646 return Actions.ConvertDeclToDeclGroup(TheDecl); 01647 } 01648 01649 if (isDeclarationSpecifier()) { 01650 // If there is an invalid declaration specifier right after the function 01651 // prototype, then we must be in a missing semicolon case where this isn't 01652 // actually a body. Just fall through into the code that handles it as a 01653 // prototype, and let the top-level code handle the erroneous declspec 01654 // where it would otherwise expect a comma or semicolon. 01655 } else { 01656 Diag(Tok, diag::err_expected_fn_body); 01657 SkipUntil(tok::semi); 01658 return DeclGroupPtrTy(); 01659 } 01660 } else { 01661 if (Tok.is(tok::l_brace)) { 01662 Diag(Tok, diag::err_function_definition_not_allowed); 01663 SkipMalformedDecl(); 01664 return DeclGroupPtrTy(); 01665 } 01666 } 01667 } 01668 01669 if (ParseAsmAttributesAfterDeclarator(D)) 01670 return DeclGroupPtrTy(); 01671 01672 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we 01673 // must parse and analyze the for-range-initializer before the declaration is 01674 // analyzed. 01675 // 01676 // Handle the Objective-C for-in loop variable similarly, although we 01677 // don't need to parse the container in advance. 01678 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) { 01679 bool IsForRangeLoop = false; 01680 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) { 01681 IsForRangeLoop = true; 01682 if (Tok.is(tok::l_brace)) 01683 FRI->RangeExpr = ParseBraceInitializer(); 01684 else 01685 FRI->RangeExpr = ParseExpression(); 01686 } 01687 01688 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 01689 if (IsForRangeLoop) 01690 Actions.ActOnCXXForRangeDecl(ThisDecl); 01691 Actions.FinalizeDeclaration(ThisDecl); 01692 D.complete(ThisDecl); 01693 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl); 01694 } 01695 01696 SmallVector<Decl *, 8> DeclsInGroup; 01697 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes( 01698 D, ParsedTemplateInfo(), FRI); 01699 if (LateParsedAttrs.size() > 0) 01700 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false); 01701 D.complete(FirstDecl); 01702 if (FirstDecl) 01703 DeclsInGroup.push_back(FirstDecl); 01704 01705 bool ExpectSemi = Context != Declarator::ForContext; 01706 01707 // If we don't have a comma, it is either the end of the list (a ';') or an 01708 // error, bail out. 01709 SourceLocation CommaLoc; 01710 while (TryConsumeToken(tok::comma, CommaLoc)) { 01711 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) { 01712 // This comma was followed by a line-break and something which can't be 01713 // the start of a declarator. The comma was probably a typo for a 01714 // semicolon. 01715 Diag(CommaLoc, diag::err_expected_semi_declaration) 01716 << FixItHint::CreateReplacement(CommaLoc, ";"); 01717 ExpectSemi = false; 01718 break; 01719 } 01720 01721 // Parse the next declarator. 01722 D.clear(); 01723 D.setCommaLoc(CommaLoc); 01724 01725 // Accept attributes in an init-declarator. In the first declarator in a 01726 // declaration, these would be part of the declspec. In subsequent 01727 // declarators, they become part of the declarator itself, so that they 01728 // don't apply to declarators after *this* one. Examples: 01729 // short __attribute__((common)) var; -> declspec 01730 // short var __attribute__((common)); -> declarator 01731 // short x, __attribute__((common)) var; -> declarator 01732 MaybeParseGNUAttributes(D); 01733 01734 ParseDeclarator(D); 01735 if (!D.isInvalidType()) { 01736 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 01737 D.complete(ThisDecl); 01738 if (ThisDecl) 01739 DeclsInGroup.push_back(ThisDecl); 01740 } 01741 } 01742 01743 if (DeclEnd) 01744 *DeclEnd = Tok.getLocation(); 01745 01746 if (ExpectSemi && 01747 ExpectAndConsumeSemi(Context == Declarator::FileContext 01748 ? diag::err_invalid_token_after_toplevel_declarator 01749 : diag::err_expected_semi_declaration)) { 01750 // Okay, there was no semicolon and one was expected. If we see a 01751 // declaration specifier, just assume it was missing and continue parsing. 01752 // Otherwise things are very confused and we skip to recover. 01753 if (!isDeclarationSpecifier()) { 01754 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 01755 TryConsumeToken(tok::semi); 01756 } 01757 } 01758 01759 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); 01760 } 01761 01762 /// Parse an optional simple-asm-expr and attributes, and attach them to a 01763 /// declarator. Returns true on an error. 01764 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) { 01765 // If a simple-asm-expr is present, parse it. 01766 if (Tok.is(tok::kw_asm)) { 01767 SourceLocation Loc; 01768 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 01769 if (AsmLabel.isInvalid()) { 01770 SkipUntil(tok::semi, StopBeforeMatch); 01771 return true; 01772 } 01773 01774 D.setAsmLabel(AsmLabel.get()); 01775 D.SetRangeEnd(Loc); 01776 } 01777 01778 MaybeParseGNUAttributes(D); 01779 return false; 01780 } 01781 01782 /// \brief Parse 'declaration' after parsing 'declaration-specifiers 01783 /// declarator'. This method parses the remainder of the declaration 01784 /// (including any attributes or initializer, among other things) and 01785 /// finalizes the declaration. 01786 /// 01787 /// init-declarator: [C99 6.7] 01788 /// declarator 01789 /// declarator '=' initializer 01790 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] 01791 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 01792 /// [C++] declarator initializer[opt] 01793 /// 01794 /// [C++] initializer: 01795 /// [C++] '=' initializer-clause 01796 /// [C++] '(' expression-list ')' 01797 /// [C++0x] '=' 'default' [TODO] 01798 /// [C++0x] '=' 'delete' 01799 /// [C++0x] braced-init-list 01800 /// 01801 /// According to the standard grammar, =default and =delete are function 01802 /// definitions, but that definitely doesn't fit with the parser here. 01803 /// 01804 Decl *Parser::ParseDeclarationAfterDeclarator( 01805 Declarator &D, const ParsedTemplateInfo &TemplateInfo) { 01806 if (ParseAsmAttributesAfterDeclarator(D)) 01807 return nullptr; 01808 01809 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 01810 } 01811 01812 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes( 01813 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) { 01814 // Inform the current actions module that we just parsed this declarator. 01815 Decl *ThisDecl = nullptr; 01816 switch (TemplateInfo.Kind) { 01817 case ParsedTemplateInfo::NonTemplate: 01818 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 01819 break; 01820 01821 case ParsedTemplateInfo::Template: 01822 case ParsedTemplateInfo::ExplicitSpecialization: { 01823 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 01824 *TemplateInfo.TemplateParams, 01825 D); 01826 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) 01827 // Re-direct this decl to refer to the templated decl so that we can 01828 // initialize it. 01829 ThisDecl = VT->getTemplatedDecl(); 01830 break; 01831 } 01832 case ParsedTemplateInfo::ExplicitInstantiation: { 01833 if (Tok.is(tok::semi)) { 01834 DeclResult ThisRes = Actions.ActOnExplicitInstantiation( 01835 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D); 01836 if (ThisRes.isInvalid()) { 01837 SkipUntil(tok::semi, StopBeforeMatch); 01838 return nullptr; 01839 } 01840 ThisDecl = ThisRes.get(); 01841 } else { 01842 // FIXME: This check should be for a variable template instantiation only. 01843 01844 // Check that this is a valid instantiation 01845 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 01846 // If the declarator-id is not a template-id, issue a diagnostic and 01847 // recover by ignoring the 'template' keyword. 01848 Diag(Tok, diag::err_template_defn_explicit_instantiation) 01849 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc); 01850 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 01851 } else { 01852 SourceLocation LAngleLoc = 01853 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 01854 Diag(D.getIdentifierLoc(), 01855 diag::err_explicit_instantiation_with_definition) 01856 << SourceRange(TemplateInfo.TemplateLoc) 01857 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 01858 01859 // Recover as if it were an explicit specialization. 01860 TemplateParameterLists FakedParamLists; 01861 FakedParamLists.push_back(Actions.ActOnTemplateParameterList( 01862 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr, 01863 0, LAngleLoc)); 01864 01865 ThisDecl = 01866 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D); 01867 } 01868 } 01869 break; 01870 } 01871 } 01872 01873 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType(); 01874 01875 // Parse declarator '=' initializer. 01876 // If a '==' or '+=' is found, suggest a fixit to '='. 01877 if (isTokenEqualOrEqualTypo()) { 01878 SourceLocation EqualLoc = ConsumeToken(); 01879 01880 if (Tok.is(tok::kw_delete)) { 01881 if (D.isFunctionDeclarator()) 01882 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 01883 << 1 /* delete */; 01884 else 01885 Diag(ConsumeToken(), diag::err_deleted_non_function); 01886 } else if (Tok.is(tok::kw_default)) { 01887 if (D.isFunctionDeclarator()) 01888 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 01889 << 0 /* default */; 01890 else 01891 Diag(ConsumeToken(), diag::err_default_special_members); 01892 } else { 01893 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01894 EnterScope(0); 01895 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 01896 } 01897 01898 if (Tok.is(tok::code_completion)) { 01899 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 01900 Actions.FinalizeDeclaration(ThisDecl); 01901 cutOffParsing(); 01902 return nullptr; 01903 } 01904 01905 ExprResult Init(ParseInitializer()); 01906 01907 // If this is the only decl in (possibly) range based for statement, 01908 // our best guess is that the user meant ':' instead of '='. 01909 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) { 01910 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range) 01911 << FixItHint::CreateReplacement(EqualLoc, ":"); 01912 // We are trying to stop parser from looking for ';' in this for 01913 // statement, therefore preventing spurious errors to be issued. 01914 FRI->ColonLoc = EqualLoc; 01915 Init = ExprError(); 01916 FRI->RangeExpr = Init; 01917 } 01918 01919 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01920 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01921 ExitScope(); 01922 } 01923 01924 if (Init.isInvalid()) { 01925 SmallVector<tok::TokenKind, 2> StopTokens; 01926 StopTokens.push_back(tok::comma); 01927 if (D.getContext() == Declarator::ForContext) 01928 StopTokens.push_back(tok::r_paren); 01929 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch); 01930 Actions.ActOnInitializerError(ThisDecl); 01931 } else 01932 Actions.AddInitializerToDecl(ThisDecl, Init.get(), 01933 /*DirectInit=*/false, TypeContainsAuto); 01934 } 01935 } else if (Tok.is(tok::l_paren)) { 01936 // Parse C++ direct initializer: '(' expression-list ')' 01937 BalancedDelimiterTracker T(*this, tok::l_paren); 01938 T.consumeOpen(); 01939 01940 ExprVector Exprs; 01941 CommaLocsTy CommaLocs; 01942 01943 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01944 EnterScope(0); 01945 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 01946 } 01947 01948 if (ParseExpressionList(Exprs, CommaLocs)) { 01949 Actions.ActOnInitializerError(ThisDecl); 01950 SkipUntil(tok::r_paren, StopAtSemi); 01951 01952 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01953 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01954 ExitScope(); 01955 } 01956 } else { 01957 // Match the ')'. 01958 T.consumeClose(); 01959 01960 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 01961 "Unexpected number of commas!"); 01962 01963 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 01964 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01965 ExitScope(); 01966 } 01967 01968 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(), 01969 T.getCloseLocation(), 01970 Exprs); 01971 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(), 01972 /*DirectInit=*/true, TypeContainsAuto); 01973 } 01974 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) && 01975 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) { 01976 // Parse C++0x braced-init-list. 01977 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 01978 01979 if (D.getCXXScopeSpec().isSet()) { 01980 EnterScope(0); 01981 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 01982 } 01983 01984 ExprResult Init(ParseBraceInitializer()); 01985 01986 if (D.getCXXScopeSpec().isSet()) { 01987 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 01988 ExitScope(); 01989 } 01990 01991 if (Init.isInvalid()) { 01992 Actions.ActOnInitializerError(ThisDecl); 01993 } else 01994 Actions.AddInitializerToDecl(ThisDecl, Init.get(), 01995 /*DirectInit=*/true, TypeContainsAuto); 01996 01997 } else { 01998 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); 01999 } 02000 02001 Actions.FinalizeDeclaration(ThisDecl); 02002 02003 return ThisDecl; 02004 } 02005 02006 /// ParseSpecifierQualifierList 02007 /// specifier-qualifier-list: 02008 /// type-specifier specifier-qualifier-list[opt] 02009 /// type-qualifier specifier-qualifier-list[opt] 02010 /// [GNU] attributes specifier-qualifier-list[opt] 02011 /// 02012 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS, 02013 DeclSpecContext DSC) { 02014 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 02015 /// parse declaration-specifiers and complain about extra stuff. 02016 /// TODO: diagnose attribute-specifiers and alignment-specifiers. 02017 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC); 02018 02019 // Validate declspec for type-name. 02020 unsigned Specs = DS.getParsedSpecifiers(); 02021 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) { 02022 Diag(Tok, diag::err_expected_type); 02023 DS.SetTypeSpecError(); 02024 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 02025 !DS.hasAttributes()) { 02026 Diag(Tok, diag::err_typename_requires_specqual); 02027 if (!DS.hasTypeSpecifier()) 02028 DS.SetTypeSpecError(); 02029 } 02030 02031 // Issue diagnostic and remove storage class if present. 02032 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 02033 if (DS.getStorageClassSpecLoc().isValid()) 02034 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 02035 else 02036 Diag(DS.getThreadStorageClassSpecLoc(), 02037 diag::err_typename_invalid_storageclass); 02038 DS.ClearStorageClassSpecs(); 02039 } 02040 02041 // Issue diagnostic and remove function specfier if present. 02042 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 02043 if (DS.isInlineSpecified()) 02044 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 02045 if (DS.isVirtualSpecified()) 02046 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 02047 if (DS.isExplicitSpecified()) 02048 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 02049 DS.ClearFunctionSpecs(); 02050 } 02051 02052 // Issue diagnostic and remove constexpr specfier if present. 02053 if (DS.isConstexprSpecified()) { 02054 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr); 02055 DS.ClearConstexprSpec(); 02056 } 02057 } 02058 02059 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 02060 /// specified token is valid after the identifier in a declarator which 02061 /// immediately follows the declspec. For example, these things are valid: 02062 /// 02063 /// int x [ 4]; // direct-declarator 02064 /// int x ( int y); // direct-declarator 02065 /// int(int x ) // direct-declarator 02066 /// int x ; // simple-declaration 02067 /// int x = 17; // init-declarator-list 02068 /// int x , y; // init-declarator-list 02069 /// int x __asm__ ("foo"); // init-declarator-list 02070 /// int x : 4; // struct-declarator 02071 /// int x { 5}; // C++'0x unified initializers 02072 /// 02073 /// This is not, because 'x' does not immediately follow the declspec (though 02074 /// ')' happens to be valid anyway). 02075 /// int (x) 02076 /// 02077 static bool isValidAfterIdentifierInDeclarator(const Token &T) { 02078 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 02079 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 02080 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 02081 } 02082 02083 02084 /// ParseImplicitInt - This method is called when we have an non-typename 02085 /// identifier in a declspec (which normally terminates the decl spec) when 02086 /// the declspec has no type specifier. In this case, the declspec is either 02087 /// malformed or is "implicit int" (in K&R and C89). 02088 /// 02089 /// This method handles diagnosing this prettily and returns false if the 02090 /// declspec is done being processed. If it recovers and thinks there may be 02091 /// other pieces of declspec after it, it returns true. 02092 /// 02093 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 02094 const ParsedTemplateInfo &TemplateInfo, 02095 AccessSpecifier AS, DeclSpecContext DSC, 02096 ParsedAttributesWithRange &Attrs) { 02097 assert(Tok.is(tok::identifier) && "should have identifier"); 02098 02099 SourceLocation Loc = Tok.getLocation(); 02100 // If we see an identifier that is not a type name, we normally would 02101 // parse it as the identifer being declared. However, when a typename 02102 // is typo'd or the definition is not included, this will incorrectly 02103 // parse the typename as the identifier name and fall over misparsing 02104 // later parts of the diagnostic. 02105 // 02106 // As such, we try to do some look-ahead in cases where this would 02107 // otherwise be an "implicit-int" case to see if this is invalid. For 02108 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 02109 // an identifier with implicit int, we'd get a parse error because the 02110 // next token is obviously invalid for a type. Parse these as a case 02111 // with an invalid type specifier. 02112 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 02113 02114 // Since we know that this either implicit int (which is rare) or an 02115 // error, do lookahead to try to do better recovery. This never applies 02116 // within a type specifier. Outside of C++, we allow this even if the 02117 // language doesn't "officially" support implicit int -- we support 02118 // implicit int as an extension in C99 and C11. 02119 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus && 02120 isValidAfterIdentifierInDeclarator(NextToken())) { 02121 // If this token is valid for implicit int, e.g. "static x = 4", then 02122 // we just avoid eating the identifier, so it will be parsed as the 02123 // identifier in the declarator. 02124 return false; 02125 } 02126 02127 if (getLangOpts().CPlusPlus && 02128 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 02129 // Don't require a type specifier if we have the 'auto' storage class 02130 // specifier in C++98 -- we'll promote it to a type specifier. 02131 if (SS) 02132 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); 02133 return false; 02134 } 02135 02136 // Otherwise, if we don't consume this token, we are going to emit an 02137 // error anyway. Try to recover from various common problems. Check 02138 // to see if this was a reference to a tag name without a tag specified. 02139 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 02140 // 02141 // C++ doesn't need this, and isTagName doesn't take SS. 02142 if (SS == nullptr) { 02143 const char *TagName = nullptr, *FixitTagName = nullptr; 02144 tok::TokenKind TagKind = tok::unknown; 02145 02146 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 02147 default: break; 02148 case DeclSpec::TST_enum: 02149 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; 02150 case DeclSpec::TST_union: 02151 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; 02152 case DeclSpec::TST_struct: 02153 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; 02154 case DeclSpec::TST_interface: 02155 TagName="__interface"; FixitTagName = "__interface "; 02156 TagKind=tok::kw___interface;break; 02157 case DeclSpec::TST_class: 02158 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; 02159 } 02160 02161 if (TagName) { 02162 IdentifierInfo *TokenName = Tok.getIdentifierInfo(); 02163 LookupResult R(Actions, TokenName, SourceLocation(), 02164 Sema::LookupOrdinaryName); 02165 02166 Diag(Loc, diag::err_use_of_tag_name_without_tag) 02167 << TokenName << TagName << getLangOpts().CPlusPlus 02168 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); 02169 02170 if (Actions.LookupParsedName(R, getCurScope(), SS)) { 02171 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); 02172 I != IEnd; ++I) 02173 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 02174 << TokenName << TagName; 02175 } 02176 02177 // Parse this as a tag as if the missing tag were present. 02178 if (TagKind == tok::kw_enum) 02179 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal); 02180 else 02181 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS, 02182 /*EnteringContext*/ false, DSC_normal, Attrs); 02183 return true; 02184 } 02185 } 02186 02187 // Determine whether this identifier could plausibly be the name of something 02188 // being declared (with a missing type). 02189 if (!isTypeSpecifier(DSC) && 02190 (!SS || DSC == DSC_top_level || DSC == DSC_class)) { 02191 // Look ahead to the next token to try to figure out what this declaration 02192 // was supposed to be. 02193 switch (NextToken().getKind()) { 02194 case tok::l_paren: { 02195 // static x(4); // 'x' is not a type 02196 // x(int n); // 'x' is not a type 02197 // x (*p)[]; // 'x' is a type 02198 // 02199 // Since we're in an error case, we can afford to perform a tentative 02200 // parse to determine which case we're in. 02201 TentativeParsingAction PA(*this); 02202 ConsumeToken(); 02203 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false); 02204 PA.Revert(); 02205 02206 if (TPR != TPResult::False) { 02207 // The identifier is followed by a parenthesized declarator. 02208 // It's supposed to be a type. 02209 break; 02210 } 02211 02212 // If we're in a context where we could be declaring a constructor, 02213 // check whether this is a constructor declaration with a bogus name. 02214 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) { 02215 IdentifierInfo *II = Tok.getIdentifierInfo(); 02216 if (Actions.isCurrentClassNameTypo(II, SS)) { 02217 Diag(Loc, diag::err_constructor_bad_name) 02218 << Tok.getIdentifierInfo() << II 02219 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName()); 02220 Tok.setIdentifierInfo(II); 02221 } 02222 } 02223 // Fall through. 02224 } 02225 case tok::comma: 02226 case tok::equal: 02227 case tok::kw_asm: 02228 case tok::l_brace: 02229 case tok::l_square: 02230 case tok::semi: 02231 // This looks like a variable or function declaration. The type is 02232 // probably missing. We're done parsing decl-specifiers. 02233 if (SS) 02234 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); 02235 return false; 02236 02237 default: 02238 // This is probably supposed to be a type. This includes cases like: 02239 // int f(itn); 02240 // struct S { unsinged : 4; }; 02241 break; 02242 } 02243 } 02244 02245 // This is almost certainly an invalid type name. Let Sema emit a diagnostic 02246 // and attempt to recover. 02247 ParsedType T; 02248 IdentifierInfo *II = Tok.getIdentifierInfo(); 02249 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T, 02250 getLangOpts().CPlusPlus && 02251 NextToken().is(tok::less)); 02252 if (T) { 02253 // The action has suggested that the type T could be used. Set that as 02254 // the type in the declaration specifiers, consume the would-be type 02255 // name token, and we're done. 02256 const char *PrevSpec; 02257 unsigned DiagID; 02258 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T, 02259 Actions.getASTContext().getPrintingPolicy()); 02260 DS.SetRangeEnd(Tok.getLocation()); 02261 ConsumeToken(); 02262 // There may be other declaration specifiers after this. 02263 return true; 02264 } else if (II != Tok.getIdentifierInfo()) { 02265 // If no type was suggested, the correction is to a keyword 02266 Tok.setKind(II->getTokenID()); 02267 // There may be other declaration specifiers after this. 02268 return true; 02269 } 02270 02271 // Otherwise, the action had no suggestion for us. Mark this as an error. 02272 DS.SetTypeSpecError(); 02273 DS.SetRangeEnd(Tok.getLocation()); 02274 ConsumeToken(); 02275 02276 // TODO: Could inject an invalid typedef decl in an enclosing scope to 02277 // avoid rippling error messages on subsequent uses of the same type, 02278 // could be useful if #include was forgotten. 02279 return false; 02280 } 02281 02282 /// \brief Determine the declaration specifier context from the declarator 02283 /// context. 02284 /// 02285 /// \param Context the declarator context, which is one of the 02286 /// Declarator::TheContext enumerator values. 02287 Parser::DeclSpecContext 02288 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 02289 if (Context == Declarator::MemberContext) 02290 return DSC_class; 02291 if (Context == Declarator::FileContext) 02292 return DSC_top_level; 02293 if (Context == Declarator::TemplateTypeArgContext) 02294 return DSC_template_type_arg; 02295 if (Context == Declarator::TrailingReturnContext) 02296 return DSC_trailing; 02297 if (Context == Declarator::AliasDeclContext || 02298 Context == Declarator::AliasTemplateContext) 02299 return DSC_alias_declaration; 02300 return DSC_normal; 02301 } 02302 02303 /// ParseAlignArgument - Parse the argument to an alignment-specifier. 02304 /// 02305 /// FIXME: Simply returns an alignof() expression if the argument is a 02306 /// type. Ideally, the type should be propagated directly into Sema. 02307 /// 02308 /// [C11] type-id 02309 /// [C11] constant-expression 02310 /// [C++0x] type-id ...[opt] 02311 /// [C++0x] assignment-expression ...[opt] 02312 ExprResult Parser::ParseAlignArgument(SourceLocation Start, 02313 SourceLocation &EllipsisLoc) { 02314 ExprResult ER; 02315 if (isTypeIdInParens()) { 02316 SourceLocation TypeLoc = Tok.getLocation(); 02317 ParsedType Ty = ParseTypeName().get(); 02318 SourceRange TypeRange(Start, Tok.getLocation()); 02319 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, 02320 Ty.getAsOpaquePtr(), TypeRange); 02321 } else 02322 ER = ParseConstantExpression(); 02323 02324 if (getLangOpts().CPlusPlus11) 02325 TryConsumeToken(tok::ellipsis, EllipsisLoc); 02326 02327 return ER; 02328 } 02329 02330 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the 02331 /// attribute to Attrs. 02332 /// 02333 /// alignment-specifier: 02334 /// [C11] '_Alignas' '(' type-id ')' 02335 /// [C11] '_Alignas' '(' constant-expression ')' 02336 /// [C++11] 'alignas' '(' type-id ...[opt] ')' 02337 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')' 02338 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs, 02339 SourceLocation *EndLoc) { 02340 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) && 02341 "Not an alignment-specifier!"); 02342 02343 IdentifierInfo *KWName = Tok.getIdentifierInfo(); 02344 SourceLocation KWLoc = ConsumeToken(); 02345 02346 BalancedDelimiterTracker T(*this, tok::l_paren); 02347 if (T.expectAndConsume()) 02348 return; 02349 02350 SourceLocation EllipsisLoc; 02351 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc); 02352 if (ArgExpr.isInvalid()) { 02353 T.skipToEnd(); 02354 return; 02355 } 02356 02357 T.consumeClose(); 02358 if (EndLoc) 02359 *EndLoc = T.getCloseLocation(); 02360 02361 ArgsVector ArgExprs; 02362 ArgExprs.push_back(ArgExpr.get()); 02363 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, 02364 AttributeList::AS_Keyword, EllipsisLoc); 02365 } 02366 02367 /// Determine whether we're looking at something that might be a declarator 02368 /// in a simple-declaration. If it can't possibly be a declarator, maybe 02369 /// diagnose a missing semicolon after a prior tag definition in the decl 02370 /// specifier. 02371 /// 02372 /// \return \c true if an error occurred and this can't be any kind of 02373 /// declaration. 02374 bool 02375 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS, 02376 DeclSpecContext DSContext, 02377 LateParsedAttrList *LateAttrs) { 02378 assert(DS.hasTagDefinition() && "shouldn't call this"); 02379 02380 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); 02381 02382 if (getLangOpts().CPlusPlus && 02383 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 02384 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id)) && 02385 TryAnnotateCXXScopeToken(EnteringContext)) { 02386 SkipMalformedDecl(); 02387 return true; 02388 } 02389 02390 bool HasScope = Tok.is(tok::annot_cxxscope); 02391 // Make a copy in case GetLookAheadToken invalidates the result of NextToken. 02392 Token AfterScope = HasScope ? NextToken() : Tok; 02393 02394 // Determine whether the following tokens could possibly be a 02395 // declarator. 02396 bool MightBeDeclarator = true; 02397 if (Tok.is(tok::kw_typename) || Tok.is(tok::annot_typename)) { 02398 // A declarator-id can't start with 'typename'. 02399 MightBeDeclarator = false; 02400 } else if (AfterScope.is(tok::annot_template_id)) { 02401 // If we have a type expressed as a template-id, this cannot be a 02402 // declarator-id (such a type cannot be redeclared in a simple-declaration). 02403 TemplateIdAnnotation *Annot = 02404 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue()); 02405 if (Annot->Kind == TNK_Type_template) 02406 MightBeDeclarator = false; 02407 } else if (AfterScope.is(tok::identifier)) { 02408 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken(); 02409 02410 // These tokens cannot come after the declarator-id in a 02411 // simple-declaration, and are likely to come after a type-specifier. 02412 if (Next.is(tok::star) || Next.is(tok::amp) || Next.is(tok::ampamp) || 02413 Next.is(tok::identifier) || Next.is(tok::annot_cxxscope) || 02414 Next.is(tok::coloncolon)) { 02415 // Missing a semicolon. 02416 MightBeDeclarator = false; 02417 } else if (HasScope) { 02418 // If the declarator-id has a scope specifier, it must redeclare a 02419 // previously-declared entity. If that's a type (and this is not a 02420 // typedef), that's an error. 02421 CXXScopeSpec SS; 02422 Actions.RestoreNestedNameSpecifierAnnotation( 02423 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); 02424 IdentifierInfo *Name = AfterScope.getIdentifierInfo(); 02425 Sema::NameClassification Classification = Actions.ClassifyName( 02426 getCurScope(), SS, Name, AfterScope.getLocation(), Next, 02427 /*IsAddressOfOperand*/false); 02428 switch (Classification.getKind()) { 02429 case Sema::NC_Error: 02430 SkipMalformedDecl(); 02431 return true; 02432 02433 case Sema::NC_Keyword: 02434 case Sema::NC_NestedNameSpecifier: 02435 llvm_unreachable("typo correction and nested name specifiers not " 02436 "possible here"); 02437 02438 case Sema::NC_Type: 02439 case Sema::NC_TypeTemplate: 02440 // Not a previously-declared non-type entity. 02441 MightBeDeclarator = false; 02442 break; 02443 02444 case Sema::NC_Unknown: 02445 case Sema::NC_Expression: 02446 case Sema::NC_VarTemplate: 02447 case Sema::NC_FunctionTemplate: 02448 // Might be a redeclaration of a prior entity. 02449 break; 02450 } 02451 } 02452 } 02453 02454 if (MightBeDeclarator) 02455 return false; 02456 02457 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); 02458 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()), 02459 diag::err_expected_after) 02460 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi; 02461 02462 // Try to recover from the typo, by dropping the tag definition and parsing 02463 // the problematic tokens as a type. 02464 // 02465 // FIXME: Split the DeclSpec into pieces for the standalone 02466 // declaration and pieces for the following declaration, instead 02467 // of assuming that all the other pieces attach to new declaration, 02468 // and call ParsedFreeStandingDeclSpec as appropriate. 02469 DS.ClearTypeSpecType(); 02470 ParsedTemplateInfo NotATemplate; 02471 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs); 02472 return false; 02473 } 02474 02475 /// ParseDeclarationSpecifiers 02476 /// declaration-specifiers: [C99 6.7] 02477 /// storage-class-specifier declaration-specifiers[opt] 02478 /// type-specifier declaration-specifiers[opt] 02479 /// [C99] function-specifier declaration-specifiers[opt] 02480 /// [C11] alignment-specifier declaration-specifiers[opt] 02481 /// [GNU] attributes declaration-specifiers[opt] 02482 /// [Clang] '__module_private__' declaration-specifiers[opt] 02483 /// 02484 /// storage-class-specifier: [C99 6.7.1] 02485 /// 'typedef' 02486 /// 'extern' 02487 /// 'static' 02488 /// 'auto' 02489 /// 'register' 02490 /// [C++] 'mutable' 02491 /// [C++11] 'thread_local' 02492 /// [C11] '_Thread_local' 02493 /// [GNU] '__thread' 02494 /// function-specifier: [C99 6.7.4] 02495 /// [C99] 'inline' 02496 /// [C++] 'virtual' 02497 /// [C++] 'explicit' 02498 /// [OpenCL] '__kernel' 02499 /// 'friend': [C++ dcl.friend] 02500 /// 'constexpr': [C++0x dcl.constexpr] 02501 02502 /// 02503 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 02504 const ParsedTemplateInfo &TemplateInfo, 02505 AccessSpecifier AS, 02506 DeclSpecContext DSContext, 02507 LateParsedAttrList *LateAttrs) { 02508 if (DS.getSourceRange().isInvalid()) { 02509 // Start the range at the current token but make the end of the range 02510 // invalid. This will make the entire range invalid unless we successfully 02511 // consume a token. 02512 DS.SetRangeStart(Tok.getLocation()); 02513 DS.SetRangeEnd(SourceLocation()); 02514 } 02515 02516 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); 02517 bool AttrsLastTime = false; 02518 ParsedAttributesWithRange attrs(AttrFactory); 02519 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 02520 while (1) { 02521 bool isInvalid = false; 02522 const char *PrevSpec = nullptr; 02523 unsigned DiagID = 0; 02524 02525 SourceLocation Loc = Tok.getLocation(); 02526 02527 switch (Tok.getKind()) { 02528 default: 02529 DoneWithDeclSpec: 02530 if (!AttrsLastTime) 02531 ProhibitAttributes(attrs); 02532 else { 02533 // Reject C++11 attributes that appertain to decl specifiers as 02534 // we don't support any C++11 attributes that appertain to decl 02535 // specifiers. This also conforms to what g++ 4.8 is doing. 02536 ProhibitCXX11Attributes(attrs); 02537 02538 DS.takeAttributesFrom(attrs); 02539 } 02540 02541 // If this is not a declaration specifier token, we're done reading decl 02542 // specifiers. First verify that DeclSpec's are consistent. 02543 DS.Finish(Diags, PP, Policy); 02544 return; 02545 02546 case tok::l_square: 02547 case tok::kw_alignas: 02548 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier()) 02549 goto DoneWithDeclSpec; 02550 02551 ProhibitAttributes(attrs); 02552 // FIXME: It would be good to recover by accepting the attributes, 02553 // but attempting to do that now would cause serious 02554 // madness in terms of diagnostics. 02555 attrs.clear(); 02556 attrs.Range = SourceRange(); 02557 02558 ParseCXX11Attributes(attrs); 02559 AttrsLastTime = true; 02560 continue; 02561 02562 case tok::code_completion: { 02563 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 02564 if (DS.hasTypeSpecifier()) { 02565 bool AllowNonIdentifiers 02566 = (getCurScope()->getFlags() & (Scope::ControlScope | 02567 Scope::BlockScope | 02568 Scope::TemplateParamScope | 02569 Scope::FunctionPrototypeScope | 02570 Scope::AtCatchScope)) == 0; 02571 bool AllowNestedNameSpecifiers 02572 = DSContext == DSC_top_level || 02573 (DSContext == DSC_class && DS.isFriendSpecified()); 02574 02575 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 02576 AllowNonIdentifiers, 02577 AllowNestedNameSpecifiers); 02578 return cutOffParsing(); 02579 } 02580 02581 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 02582 CCC = Sema::PCC_LocalDeclarationSpecifiers; 02583 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 02584 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 02585 : Sema::PCC_Template; 02586 else if (DSContext == DSC_class) 02587 CCC = Sema::PCC_Class; 02588 else if (CurParsedObjCImpl) 02589 CCC = Sema::PCC_ObjCImplementation; 02590 02591 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 02592 return cutOffParsing(); 02593 } 02594 02595 case tok::coloncolon: // ::foo::bar 02596 // C++ scope specifier. Annotate and loop, or bail out on error. 02597 if (TryAnnotateCXXScopeToken(EnteringContext)) { 02598 if (!DS.hasTypeSpecifier()) 02599 DS.SetTypeSpecError(); 02600 goto DoneWithDeclSpec; 02601 } 02602 if (Tok.is(tok::coloncolon)) // ::new or ::delete 02603 goto DoneWithDeclSpec; 02604 continue; 02605 02606 case tok::annot_cxxscope: { 02607 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector()) 02608 goto DoneWithDeclSpec; 02609 02610 CXXScopeSpec SS; 02611 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 02612 Tok.getAnnotationRange(), 02613 SS); 02614 02615 // We are looking for a qualified typename. 02616 Token Next = NextToken(); 02617 if (Next.is(tok::annot_template_id) && 02618 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 02619 ->Kind == TNK_Type_template) { 02620 // We have a qualified template-id, e.g., N::A<int> 02621 02622 // C++ [class.qual]p2: 02623 // In a lookup in which the constructor is an acceptable lookup 02624 // result and the nested-name-specifier nominates a class C: 02625 // 02626 // - if the name specified after the 02627 // nested-name-specifier, when looked up in C, is the 02628 // injected-class-name of C (Clause 9), or 02629 // 02630 // - if the name specified after the nested-name-specifier 02631 // is the same as the identifier or the 02632 // simple-template-id's template-name in the last 02633 // component of the nested-name-specifier, 02634 // 02635 // the name is instead considered to name the constructor of 02636 // class C. 02637 // 02638 // Thus, if the template-name is actually the constructor 02639 // name, then the code is ill-formed; this interpretation is 02640 // reinforced by the NAD status of core issue 635. 02641 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 02642 if ((DSContext == DSC_top_level || DSContext == DSC_class) && 02643 TemplateId->Name && 02644 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 02645 if (isConstructorDeclarator(/*Unqualified*/false)) { 02646 // The user meant this to be an out-of-line constructor 02647 // definition, but template arguments are not allowed 02648 // there. Just allow this as a constructor; we'll 02649 // complain about it later. 02650 goto DoneWithDeclSpec; 02651 } 02652 02653 // The user meant this to name a type, but it actually names 02654 // a constructor with some extraneous template 02655 // arguments. Complain, then parse it as a type as the user 02656 // intended. 02657 Diag(TemplateId->TemplateNameLoc, 02658 diag::err_out_of_line_template_id_names_constructor) 02659 << TemplateId->Name; 02660 } 02661 02662 DS.getTypeSpecScope() = SS; 02663 ConsumeToken(); // The C++ scope. 02664 assert(Tok.is(tok::annot_template_id) && 02665 "ParseOptionalCXXScopeSpecifier not working"); 02666 AnnotateTemplateIdTokenAsType(); 02667 continue; 02668 } 02669 02670 if (Next.is(tok::annot_typename)) { 02671 DS.getTypeSpecScope() = SS; 02672 ConsumeToken(); // The C++ scope. 02673 if (Tok.getAnnotationValue()) { 02674 ParsedType T = getTypeAnnotation(Tok); 02675 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 02676 Tok.getAnnotationEndLoc(), 02677 PrevSpec, DiagID, T, Policy); 02678 if (isInvalid) 02679 break; 02680 } 02681 else 02682 DS.SetTypeSpecError(); 02683 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 02684 ConsumeToken(); // The typename 02685 } 02686 02687 if (Next.isNot(tok::identifier)) 02688 goto DoneWithDeclSpec; 02689 02690 // If we're in a context where the identifier could be a class name, 02691 // check whether this is a constructor declaration. 02692 if ((DSContext == DSC_top_level || DSContext == DSC_class) && 02693 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 02694 &SS)) { 02695 if (isConstructorDeclarator(/*Unqualified*/false)) 02696 goto DoneWithDeclSpec; 02697 02698 // As noted in C++ [class.qual]p2 (cited above), when the name 02699 // of the class is qualified in a context where it could name 02700 // a constructor, its a constructor name. However, we've 02701 // looked at the declarator, and the user probably meant this 02702 // to be a type. Complain that it isn't supposed to be treated 02703 // as a type, then proceed to parse it as a type. 02704 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 02705 << Next.getIdentifierInfo(); 02706 } 02707 02708 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 02709 Next.getLocation(), 02710 getCurScope(), &SS, 02711 false, false, ParsedType(), 02712 /*IsCtorOrDtorName=*/false, 02713 /*NonTrivialSourceInfo=*/true); 02714 02715 // If the referenced identifier is not a type, then this declspec is 02716 // erroneous: We already checked about that it has no type specifier, and 02717 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 02718 // typename. 02719 if (!TypeRep) { 02720 ConsumeToken(); // Eat the scope spec so the identifier is current. 02721 ParsedAttributesWithRange Attrs(AttrFactory); 02722 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) { 02723 if (!Attrs.empty()) { 02724 AttrsLastTime = true; 02725 attrs.takeAllFrom(Attrs); 02726 } 02727 continue; 02728 } 02729 goto DoneWithDeclSpec; 02730 } 02731 02732 DS.getTypeSpecScope() = SS; 02733 ConsumeToken(); // The C++ scope. 02734 02735 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 02736 DiagID, TypeRep, Policy); 02737 if (isInvalid) 02738 break; 02739 02740 DS.SetRangeEnd(Tok.getLocation()); 02741 ConsumeToken(); // The typename. 02742 02743 continue; 02744 } 02745 02746 case tok::annot_typename: { 02747 // If we've previously seen a tag definition, we were almost surely 02748 // missing a semicolon after it. 02749 if (DS.hasTypeSpecifier() && DS.hasTagDefinition()) 02750 goto DoneWithDeclSpec; 02751 02752 if (Tok.getAnnotationValue()) { 02753 ParsedType T = getTypeAnnotation(Tok); 02754 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 02755 DiagID, T, Policy); 02756 } else 02757 DS.SetTypeSpecError(); 02758 02759 if (isInvalid) 02760 break; 02761 02762 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 02763 ConsumeToken(); // The typename 02764 02765 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 02766 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 02767 // Objective-C interface. 02768 if (Tok.is(tok::less) && getLangOpts().ObjC1) 02769 ParseObjCProtocolQualifiers(DS); 02770 02771 continue; 02772 } 02773 02774 case tok::kw___is_signed: 02775 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang 02776 // typically treats it as a trait. If we see __is_signed as it appears 02777 // in libstdc++, e.g., 02778 // 02779 // static const bool __is_signed; 02780 // 02781 // then treat __is_signed as an identifier rather than as a keyword. 02782 if (DS.getTypeSpecType() == TST_bool && 02783 DS.getTypeQualifiers() == DeclSpec::TQ_const && 02784 DS.getStorageClassSpec() == DeclSpec::SCS_static) 02785 TryKeywordIdentFallback(true); 02786 02787 // We're done with the declaration-specifiers. 02788 goto DoneWithDeclSpec; 02789 02790 // typedef-name 02791 case tok::kw___super: 02792 case tok::kw_decltype: 02793 case tok::identifier: { 02794 // This identifier can only be a typedef name if we haven't already seen 02795 // a type-specifier. Without this check we misparse: 02796 // typedef int X; struct Y { short X; }; as 'short int'. 02797 if (DS.hasTypeSpecifier()) 02798 goto DoneWithDeclSpec; 02799 02800 // In C++, check to see if this is a scope specifier like foo::bar::, if 02801 // so handle it as such. This is important for ctor parsing. 02802 if (getLangOpts().CPlusPlus) { 02803 if (TryAnnotateCXXScopeToken(EnteringContext)) { 02804 DS.SetTypeSpecError(); 02805 goto DoneWithDeclSpec; 02806 } 02807 if (!Tok.is(tok::identifier)) 02808 continue; 02809 } 02810 02811 // Check for need to substitute AltiVec keyword tokens. 02812 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 02813 break; 02814 02815 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not 02816 // allow the use of a typedef name as a type specifier. 02817 if (DS.isTypeAltiVecVector()) 02818 goto DoneWithDeclSpec; 02819 02820 ParsedType TypeRep = 02821 Actions.getTypeName(*Tok.getIdentifierInfo(), 02822 Tok.getLocation(), getCurScope()); 02823 02824 // MSVC: If we weren't able to parse a default template argument, and it's 02825 // just a simple identifier, create a DependentNameType. This will allow us 02826 // to defer the name lookup to template instantiation time, as long we forge a 02827 // NestedNameSpecifier for the current context. 02828 if (!TypeRep && DSContext == DSC_template_type_arg && 02829 getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) { 02830 TypeRep = Actions.ActOnDelayedDefaultTemplateArg( 02831 *Tok.getIdentifierInfo(), Tok.getLocation()); 02832 } 02833 02834 // If this is not a typedef name, don't parse it as part of the declspec, 02835 // it must be an implicit int or an error. 02836 if (!TypeRep) { 02837 ParsedAttributesWithRange Attrs(AttrFactory); 02838 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) { 02839 if (!Attrs.empty()) { 02840 AttrsLastTime = true; 02841 attrs.takeAllFrom(Attrs); 02842 } 02843 continue; 02844 } 02845 goto DoneWithDeclSpec; 02846 } 02847 02848 // If we're in a context where the identifier could be a class name, 02849 // check whether this is a constructor declaration. 02850 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 02851 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 02852 isConstructorDeclarator(/*Unqualified*/true)) 02853 goto DoneWithDeclSpec; 02854 02855 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 02856 DiagID, TypeRep, Policy); 02857 if (isInvalid) 02858 break; 02859 02860 DS.SetRangeEnd(Tok.getLocation()); 02861 ConsumeToken(); // The identifier 02862 02863 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 02864 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 02865 // Objective-C interface. 02866 if (Tok.is(tok::less) && getLangOpts().ObjC1) 02867 ParseObjCProtocolQualifiers(DS); 02868 02869 // Need to support trailing type qualifiers (e.g. "id<p> const"). 02870 // If a type specifier follows, it will be diagnosed elsewhere. 02871 continue; 02872 } 02873 02874 // type-name 02875 case tok::annot_template_id: { 02876 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 02877 if (TemplateId->Kind != TNK_Type_template) { 02878 // This template-id does not refer to a type name, so we're 02879 // done with the type-specifiers. 02880 goto DoneWithDeclSpec; 02881 } 02882 02883 // If we're in a context where the template-id could be a 02884 // constructor name or specialization, check whether this is a 02885 // constructor declaration. 02886 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 02887 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 02888 isConstructorDeclarator(TemplateId->SS.isEmpty())) 02889 goto DoneWithDeclSpec; 02890 02891 // Turn the template-id annotation token into a type annotation 02892 // token, then try again to parse it as a type-specifier. 02893 AnnotateTemplateIdTokenAsType(); 02894 continue; 02895 } 02896 02897 // GNU attributes support. 02898 case tok::kw___attribute: 02899 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs); 02900 continue; 02901 02902 // Microsoft declspec support. 02903 case tok::kw___declspec: 02904 ParseMicrosoftDeclSpec(DS.getAttributes()); 02905 continue; 02906 02907 // Microsoft single token adornments. 02908 case tok::kw___forceinline: { 02909 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID); 02910 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 02911 SourceLocation AttrNameLoc = Tok.getLocation(); 02912 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, 02913 nullptr, 0, AttributeList::AS_Keyword); 02914 break; 02915 } 02916 02917 case tok::kw___sptr: 02918 case tok::kw___uptr: 02919 case tok::kw___ptr64: 02920 case tok::kw___ptr32: 02921 case tok::kw___w64: 02922 case tok::kw___cdecl: 02923 case tok::kw___stdcall: 02924 case tok::kw___fastcall: 02925 case tok::kw___thiscall: 02926 case tok::kw___vectorcall: 02927 case tok::kw___unaligned: 02928 ParseMicrosoftTypeAttributes(DS.getAttributes()); 02929 continue; 02930 02931 // Borland single token adornments. 02932 case tok::kw___pascal: 02933 ParseBorlandTypeAttributes(DS.getAttributes()); 02934 continue; 02935 02936 // OpenCL single token adornments. 02937 case tok::kw___kernel: 02938 ParseOpenCLAttributes(DS.getAttributes()); 02939 continue; 02940 02941 // storage-class-specifier 02942 case tok::kw_typedef: 02943 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, 02944 PrevSpec, DiagID, Policy); 02945 break; 02946 case tok::kw_extern: 02947 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 02948 Diag(Tok, diag::ext_thread_before) << "extern"; 02949 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, 02950 PrevSpec, DiagID, Policy); 02951 break; 02952 case tok::kw___private_extern__: 02953 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, 02954 Loc, PrevSpec, DiagID, Policy); 02955 break; 02956 case tok::kw_static: 02957 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 02958 Diag(Tok, diag::ext_thread_before) << "static"; 02959 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, 02960 PrevSpec, DiagID, Policy); 02961 break; 02962 case tok::kw_auto: 02963 if (getLangOpts().CPlusPlus11) { 02964 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 02965 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 02966 PrevSpec, DiagID, Policy); 02967 if (!isInvalid) 02968 Diag(Tok, diag::ext_auto_storage_class) 02969 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 02970 } else 02971 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 02972 DiagID, Policy); 02973 } else 02974 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 02975 PrevSpec, DiagID, Policy); 02976 break; 02977 case tok::kw_register: 02978 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, 02979 PrevSpec, DiagID, Policy); 02980 break; 02981 case tok::kw_mutable: 02982 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, 02983 PrevSpec, DiagID, Policy); 02984 break; 02985 case tok::kw___thread: 02986 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc, 02987 PrevSpec, DiagID); 02988 break; 02989 case tok::kw_thread_local: 02990 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc, 02991 PrevSpec, DiagID); 02992 break; 02993 case tok::kw__Thread_local: 02994 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local, 02995 Loc, PrevSpec, DiagID); 02996 break; 02997 02998 // function-specifier 02999 case tok::kw_inline: 03000 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID); 03001 break; 03002 case tok::kw_virtual: 03003 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID); 03004 break; 03005 case tok::kw_explicit: 03006 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID); 03007 break; 03008 case tok::kw__Noreturn: 03009 if (!getLangOpts().C11) 03010 Diag(Loc, diag::ext_c11_noreturn); 03011 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); 03012 break; 03013 03014 // alignment-specifier 03015 case tok::kw__Alignas: 03016 if (!getLangOpts().C11) 03017 Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); 03018 ParseAlignmentSpecifier(DS.getAttributes()); 03019 continue; 03020 03021 // friend 03022 case tok::kw_friend: 03023 if (DSContext == DSC_class) 03024 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 03025 else { 03026 PrevSpec = ""; // not actually used by the diagnostic 03027 DiagID = diag::err_friend_invalid_in_context; 03028 isInvalid = true; 03029 } 03030 break; 03031 03032 // Modules 03033 case tok::kw___module_private__: 03034 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); 03035 break; 03036 03037 // constexpr 03038 case tok::kw_constexpr: 03039 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 03040 break; 03041 03042 // type-specifier 03043 case tok::kw_short: 03044 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 03045 DiagID, Policy); 03046 break; 03047 case tok::kw_long: 03048 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 03049 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 03050 DiagID, Policy); 03051 else 03052 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 03053 DiagID, Policy); 03054 break; 03055 case tok::kw___int64: 03056 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 03057 DiagID, Policy); 03058 break; 03059 case tok::kw_signed: 03060 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 03061 DiagID); 03062 break; 03063 case tok::kw_unsigned: 03064 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 03065 DiagID); 03066 break; 03067 case tok::kw__Complex: 03068 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 03069 DiagID); 03070 break; 03071 case tok::kw__Imaginary: 03072 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 03073 DiagID); 03074 break; 03075 case tok::kw_void: 03076 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 03077 DiagID, Policy); 03078 break; 03079 case tok::kw_char: 03080 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 03081 DiagID, Policy); 03082 break; 03083 case tok::kw_int: 03084 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 03085 DiagID, Policy); 03086 break; 03087 case tok::kw___int128: 03088 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, 03089 DiagID, Policy); 03090 break; 03091 case tok::kw_half: 03092 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, 03093 DiagID, Policy); 03094 break; 03095 case tok::kw_float: 03096 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 03097 DiagID, Policy); 03098 break; 03099 case tok::kw_double: 03100 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 03101 DiagID, Policy); 03102 break; 03103 case tok::kw_wchar_t: 03104 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 03105 DiagID, Policy); 03106 break; 03107 case tok::kw_char16_t: 03108 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 03109 DiagID, Policy); 03110 break; 03111 case tok::kw_char32_t: 03112 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 03113 DiagID, Policy); 03114 break; 03115 case tok::kw_bool: 03116 case tok::kw__Bool: 03117 if (Tok.is(tok::kw_bool) && 03118 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 03119 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 03120 PrevSpec = ""; // Not used by the diagnostic. 03121 DiagID = diag::err_bool_redeclaration; 03122 // For better error recovery. 03123 Tok.setKind(tok::identifier); 03124 isInvalid = true; 03125 } else { 03126 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 03127 DiagID, Policy); 03128 } 03129 break; 03130 case tok::kw__Decimal32: 03131 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 03132 DiagID, Policy); 03133 break; 03134 case tok::kw__Decimal64: 03135 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 03136 DiagID, Policy); 03137 break; 03138 case tok::kw__Decimal128: 03139 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 03140 DiagID, Policy); 03141 break; 03142 case tok::kw___vector: 03143 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 03144 break; 03145 case tok::kw___pixel: 03146 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 03147 break; 03148 case tok::kw___unknown_anytype: 03149 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 03150 PrevSpec, DiagID, Policy); 03151 break; 03152 03153 // class-specifier: 03154 case tok::kw_class: 03155 case tok::kw_struct: 03156 case tok::kw___interface: 03157 case tok::kw_union: { 03158 tok::TokenKind Kind = Tok.getKind(); 03159 ConsumeToken(); 03160 03161 // These are attributes following class specifiers. 03162 // To produce better diagnostic, we parse them when 03163 // parsing class specifier. 03164 ParsedAttributesWithRange Attributes(AttrFactory); 03165 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, 03166 EnteringContext, DSContext, Attributes); 03167 03168 // If there are attributes following class specifier, 03169 // take them over and handle them here. 03170 if (!Attributes.empty()) { 03171 AttrsLastTime = true; 03172 attrs.takeAllFrom(Attributes); 03173 } 03174 continue; 03175 } 03176 03177 // enum-specifier: 03178 case tok::kw_enum: 03179 ConsumeToken(); 03180 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); 03181 continue; 03182 03183 // cv-qualifier: 03184 case tok::kw_const: 03185 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 03186 getLangOpts()); 03187 break; 03188 case tok::kw_volatile: 03189 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 03190 getLangOpts()); 03191 break; 03192 case tok::kw_restrict: 03193 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 03194 getLangOpts()); 03195 break; 03196 03197 // C++ typename-specifier: 03198 case tok::kw_typename: 03199 if (TryAnnotateTypeOrScopeToken()) { 03200 DS.SetTypeSpecError(); 03201 goto DoneWithDeclSpec; 03202 } 03203 if (!Tok.is(tok::kw_typename)) 03204 continue; 03205 break; 03206 03207 // GNU typeof support. 03208 case tok::kw_typeof: 03209 ParseTypeofSpecifier(DS); 03210 continue; 03211 03212 case tok::annot_decltype: 03213 ParseDecltypeSpecifier(DS); 03214 continue; 03215 03216 case tok::kw___underlying_type: 03217 ParseUnderlyingTypeSpecifier(DS); 03218 continue; 03219 03220 case tok::kw__Atomic: 03221 // C11 6.7.2.4/4: 03222 // If the _Atomic keyword is immediately followed by a left parenthesis, 03223 // it is interpreted as a type specifier (with a type name), not as a 03224 // type qualifier. 03225 if (NextToken().is(tok::l_paren)) { 03226 ParseAtomicSpecifier(DS); 03227 continue; 03228 } 03229 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 03230 getLangOpts()); 03231 break; 03232 03233 // OpenCL qualifiers: 03234 case tok::kw___private: 03235 case tok::kw___global: 03236 case tok::kw___local: 03237 case tok::kw___constant: 03238 case tok::kw___read_only: 03239 case tok::kw___write_only: 03240 case tok::kw___read_write: 03241 ParseOpenCLQualifiers(DS.getAttributes()); 03242 break; 03243 03244 case tok::less: 03245 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 03246 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 03247 // but we support it. 03248 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) 03249 goto DoneWithDeclSpec; 03250 03251 if (!ParseObjCProtocolQualifiers(DS)) 03252 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 03253 << FixItHint::CreateInsertion(Loc, "id") 03254 << SourceRange(Loc, DS.getSourceRange().getEnd()); 03255 03256 // Need to support trailing type qualifiers (e.g. "id<p> const"). 03257 // If a type specifier follows, it will be diagnosed elsewhere. 03258 continue; 03259 } 03260 // If the specifier wasn't legal, issue a diagnostic. 03261 if (isInvalid) { 03262 assert(PrevSpec && "Method did not return previous specifier!"); 03263 assert(DiagID); 03264 03265 if (DiagID == diag::ext_duplicate_declspec) 03266 Diag(Tok, DiagID) 03267 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 03268 else 03269 Diag(Tok, DiagID) << PrevSpec; 03270 } 03271 03272 DS.SetRangeEnd(Tok.getLocation()); 03273 if (DiagID != diag::err_bool_redeclaration) 03274 ConsumeToken(); 03275 03276 AttrsLastTime = false; 03277 } 03278 } 03279 03280 /// ParseStructDeclaration - Parse a struct declaration without the terminating 03281 /// semicolon. 03282 /// 03283 /// struct-declaration: 03284 /// specifier-qualifier-list struct-declarator-list 03285 /// [GNU] __extension__ struct-declaration 03286 /// [GNU] specifier-qualifier-list 03287 /// struct-declarator-list: 03288 /// struct-declarator 03289 /// struct-declarator-list ',' struct-declarator 03290 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 03291 /// struct-declarator: 03292 /// declarator 03293 /// [GNU] declarator attributes[opt] 03294 /// declarator[opt] ':' constant-expression 03295 /// [GNU] declarator[opt] ':' constant-expression attributes[opt] 03296 /// 03297 void Parser::ParseStructDeclaration( 03298 ParsingDeclSpec &DS, 03299 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) { 03300 03301 if (Tok.is(tok::kw___extension__)) { 03302 // __extension__ silences extension warnings in the subexpression. 03303 ExtensionRAIIObject O(Diags); // Use RAII to do this. 03304 ConsumeToken(); 03305 return ParseStructDeclaration(DS, FieldsCallback); 03306 } 03307 03308 // Parse the common specifier-qualifiers-list piece. 03309 ParseSpecifierQualifierList(DS); 03310 03311 // If there are no declarators, this is a free-standing declaration 03312 // specifier. Let the actions module cope with it. 03313 if (Tok.is(tok::semi)) { 03314 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 03315 DS); 03316 DS.complete(TheDecl); 03317 return; 03318 } 03319 03320 // Read struct-declarators until we find the semicolon. 03321 bool FirstDeclarator = true; 03322 SourceLocation CommaLoc; 03323 while (1) { 03324 ParsingFieldDeclarator DeclaratorInfo(*this, DS); 03325 DeclaratorInfo.D.setCommaLoc(CommaLoc); 03326 03327 // Attributes are only allowed here on successive declarators. 03328 if (!FirstDeclarator) 03329 MaybeParseGNUAttributes(DeclaratorInfo.D); 03330 03331 /// struct-declarator: declarator 03332 /// struct-declarator: declarator[opt] ':' constant-expression 03333 if (Tok.isNot(tok::colon)) { 03334 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 03335 ColonProtectionRAIIObject X(*this); 03336 ParseDeclarator(DeclaratorInfo.D); 03337 } else 03338 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation()); 03339 03340 if (TryConsumeToken(tok::colon)) { 03341 ExprResult Res(ParseConstantExpression()); 03342 if (Res.isInvalid()) 03343 SkipUntil(tok::semi, StopBeforeMatch); 03344 else 03345 DeclaratorInfo.BitfieldSize = Res.get(); 03346 } 03347 03348 // If attributes exist after the declarator, parse them. 03349 MaybeParseGNUAttributes(DeclaratorInfo.D); 03350 03351 // We're done with this declarator; invoke the callback. 03352 FieldsCallback(DeclaratorInfo); 03353 03354 // If we don't have a comma, it is either the end of the list (a ';') 03355 // or an error, bail out. 03356 if (!TryConsumeToken(tok::comma, CommaLoc)) 03357 return; 03358 03359 FirstDeclarator = false; 03360 } 03361 } 03362 03363 /// ParseStructUnionBody 03364 /// struct-contents: 03365 /// struct-declaration-list 03366 /// [EXT] empty 03367 /// [GNU] "struct-declaration-list" without terminatoring ';' 03368 /// struct-declaration-list: 03369 /// struct-declaration 03370 /// struct-declaration-list struct-declaration 03371 /// [OBC] '@' 'defs' '(' class-name ')' 03372 /// 03373 void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 03374 unsigned TagType, Decl *TagDecl) { 03375 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 03376 "parsing struct/union body"); 03377 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported"); 03378 03379 BalancedDelimiterTracker T(*this, tok::l_brace); 03380 if (T.consumeOpen()) 03381 return; 03382 03383 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 03384 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 03385 03386 SmallVector<Decl *, 32> FieldDecls; 03387 03388 // While we still have something to read, read the declarations in the struct. 03389 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 03390 // Each iteration of this loop reads one struct-declaration. 03391 03392 // Check for extraneous top-level semicolon. 03393 if (Tok.is(tok::semi)) { 03394 ConsumeExtraSemi(InsideStruct, TagType); 03395 continue; 03396 } 03397 03398 // Parse _Static_assert declaration. 03399 if (Tok.is(tok::kw__Static_assert)) { 03400 SourceLocation DeclEnd; 03401 ParseStaticAssertDeclaration(DeclEnd); 03402 continue; 03403 } 03404 03405 if (Tok.is(tok::annot_pragma_pack)) { 03406 HandlePragmaPack(); 03407 continue; 03408 } 03409 03410 if (Tok.is(tok::annot_pragma_align)) { 03411 HandlePragmaAlign(); 03412 continue; 03413 } 03414 03415 if (!Tok.is(tok::at)) { 03416 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) { 03417 // Install the declarator into the current TagDecl. 03418 Decl *Field = 03419 Actions.ActOnField(getCurScope(), TagDecl, 03420 FD.D.getDeclSpec().getSourceRange().getBegin(), 03421 FD.D, FD.BitfieldSize); 03422 FieldDecls.push_back(Field); 03423 FD.complete(Field); 03424 }; 03425 03426 // Parse all the comma separated declarators. 03427 ParsingDeclSpec DS(*this); 03428 ParseStructDeclaration(DS, CFieldCallback); 03429 } else { // Handle @defs 03430 ConsumeToken(); 03431 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 03432 Diag(Tok, diag::err_unexpected_at); 03433 SkipUntil(tok::semi); 03434 continue; 03435 } 03436 ConsumeToken(); 03437 ExpectAndConsume(tok::l_paren); 03438 if (!Tok.is(tok::identifier)) { 03439 Diag(Tok, diag::err_expected) << tok::identifier; 03440 SkipUntil(tok::semi); 03441 continue; 03442 } 03443 SmallVector<Decl *, 16> Fields; 03444 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 03445 Tok.getIdentifierInfo(), Fields); 03446 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 03447 ConsumeToken(); 03448 ExpectAndConsume(tok::r_paren); 03449 } 03450 03451 if (TryConsumeToken(tok::semi)) 03452 continue; 03453 03454 if (Tok.is(tok::r_brace)) { 03455 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 03456 break; 03457 } 03458 03459 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 03460 // Skip to end of block or statement to avoid ext-warning on extra ';'. 03461 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 03462 // If we stopped at a ';', eat it. 03463 TryConsumeToken(tok::semi); 03464 } 03465 03466 T.consumeClose(); 03467 03468 ParsedAttributes attrs(AttrFactory); 03469 // If attributes exist after struct contents, parse them. 03470 MaybeParseGNUAttributes(attrs); 03471 03472 Actions.ActOnFields(getCurScope(), 03473 RecordLoc, TagDecl, FieldDecls, 03474 T.getOpenLocation(), T.getCloseLocation(), 03475 attrs.getList()); 03476 StructScope.Exit(); 03477 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 03478 T.getCloseLocation()); 03479 } 03480 03481 /// ParseEnumSpecifier 03482 /// enum-specifier: [C99 6.7.2.2] 03483 /// 'enum' identifier[opt] '{' enumerator-list '}' 03484 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 03485 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 03486 /// '}' attributes[opt] 03487 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] 03488 /// '}' 03489 /// 'enum' identifier 03490 /// [GNU] 'enum' attributes[opt] identifier 03491 /// 03492 /// [C++11] enum-head '{' enumerator-list[opt] '}' 03493 /// [C++11] enum-head '{' enumerator-list ',' '}' 03494 /// 03495 /// enum-head: [C++11] 03496 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] 03497 /// enum-key attribute-specifier-seq[opt] nested-name-specifier 03498 /// identifier enum-base[opt] 03499 /// 03500 /// enum-key: [C++11] 03501 /// 'enum' 03502 /// 'enum' 'class' 03503 /// 'enum' 'struct' 03504 /// 03505 /// enum-base: [C++11] 03506 /// ':' type-specifier-seq 03507 /// 03508 /// [C++] elaborated-type-specifier: 03509 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 03510 /// 03511 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 03512 const ParsedTemplateInfo &TemplateInfo, 03513 AccessSpecifier AS, DeclSpecContext DSC) { 03514 // Parse the tag portion of this. 03515 if (Tok.is(tok::code_completion)) { 03516 // Code completion for an enum name. 03517 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 03518 return cutOffParsing(); 03519 } 03520 03521 // If attributes exist after tag, parse them. 03522 ParsedAttributesWithRange attrs(AttrFactory); 03523 MaybeParseGNUAttributes(attrs); 03524 MaybeParseCXX11Attributes(attrs); 03525 03526 // If declspecs exist after tag, parse them. 03527 while (Tok.is(tok::kw___declspec)) 03528 ParseMicrosoftDeclSpec(attrs); 03529 03530 SourceLocation ScopedEnumKWLoc; 03531 bool IsScopedUsingClassTag = false; 03532 03533 // In C++11, recognize 'enum class' and 'enum struct'. 03534 if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) { 03535 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum 03536 : diag::ext_scoped_enum); 03537 IsScopedUsingClassTag = Tok.is(tok::kw_class); 03538 ScopedEnumKWLoc = ConsumeToken(); 03539 03540 // Attributes are not allowed between these keywords. Diagnose, 03541 // but then just treat them like they appeared in the right place. 03542 ProhibitAttributes(attrs); 03543 03544 // They are allowed afterwards, though. 03545 MaybeParseGNUAttributes(attrs); 03546 MaybeParseCXX11Attributes(attrs); 03547 while (Tok.is(tok::kw___declspec)) 03548 ParseMicrosoftDeclSpec(attrs); 03549 } 03550 03551 // C++11 [temp.explicit]p12: 03552 // The usual access controls do not apply to names used to specify 03553 // explicit instantiations. 03554 // We extend this to also cover explicit specializations. Note that 03555 // we don't suppress if this turns out to be an elaborated type 03556 // specifier. 03557 bool shouldDelayDiagsInTag = 03558 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 03559 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 03560 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 03561 03562 // Enum definitions should not be parsed in a trailing-return-type. 03563 bool AllowDeclaration = DSC != DSC_trailing; 03564 03565 bool AllowFixedUnderlyingType = AllowDeclaration && 03566 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt || 03567 getLangOpts().ObjC2); 03568 03569 CXXScopeSpec &SS = DS.getTypeSpecScope(); 03570 if (getLangOpts().CPlusPlus) { 03571 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 03572 // if a fixed underlying type is allowed. 03573 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 03574 03575 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 03576 /*EnteringContext=*/true)) 03577 return; 03578 03579 if (SS.isSet() && Tok.isNot(tok::identifier)) { 03580 Diag(Tok, diag::err_expected) << tok::identifier; 03581 if (Tok.isNot(tok::l_brace)) { 03582 // Has no name and is not a definition. 03583 // Skip the rest of this declarator, up until the comma or semicolon. 03584 SkipUntil(tok::comma, StopAtSemi); 03585 return; 03586 } 03587 } 03588 } 03589 03590 // Must have either 'enum name' or 'enum {...}'. 03591 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 03592 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { 03593 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace; 03594 03595 // Skip the rest of this declarator, up until the comma or semicolon. 03596 SkipUntil(tok::comma, StopAtSemi); 03597 return; 03598 } 03599 03600 // If an identifier is present, consume and remember it. 03601 IdentifierInfo *Name = nullptr; 03602 SourceLocation NameLoc; 03603 if (Tok.is(tok::identifier)) { 03604 Name = Tok.getIdentifierInfo(); 03605 NameLoc = ConsumeToken(); 03606 } 03607 03608 if (!Name && ScopedEnumKWLoc.isValid()) { 03609 // C++0x 7.2p2: The optional identifier shall not be omitted in the 03610 // declaration of a scoped enumeration. 03611 Diag(Tok, diag::err_scoped_enum_missing_identifier); 03612 ScopedEnumKWLoc = SourceLocation(); 03613 IsScopedUsingClassTag = false; 03614 } 03615 03616 // Okay, end the suppression area. We'll decide whether to emit the 03617 // diagnostics in a second. 03618 if (shouldDelayDiagsInTag) 03619 diagsFromTag.done(); 03620 03621 TypeResult BaseType; 03622 03623 // Parse the fixed underlying type. 03624 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 03625 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 03626 bool PossibleBitfield = false; 03627 if (CanBeBitfield) { 03628 // If we're in class scope, this can either be an enum declaration with 03629 // an underlying type, or a declaration of a bitfield member. We try to 03630 // use a simple disambiguation scheme first to catch the common cases 03631 // (integer literal, sizeof); if it's still ambiguous, we then consider 03632 // anything that's a simple-type-specifier followed by '(' as an 03633 // expression. This suffices because function types are not valid 03634 // underlying types anyway. 03635 EnterExpressionEvaluationContext Unevaluated(Actions, 03636 Sema::ConstantEvaluated); 03637 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 03638 // If the next token starts an expression, we know we're parsing a 03639 // bit-field. This is the common case. 03640 if (TPR == TPResult::True) 03641 PossibleBitfield = true; 03642 // If the next token starts a type-specifier-seq, it may be either a 03643 // a fixed underlying type or the start of a function-style cast in C++; 03644 // lookahead one more token to see if it's obvious that we have a 03645 // fixed underlying type. 03646 else if (TPR == TPResult::False && 03647 GetLookAheadToken(2).getKind() == tok::semi) { 03648 // Consume the ':'. 03649 ConsumeToken(); 03650 } else { 03651 // We have the start of a type-specifier-seq, so we have to perform 03652 // tentative parsing to determine whether we have an expression or a 03653 // type. 03654 TentativeParsingAction TPA(*this); 03655 03656 // Consume the ':'. 03657 ConsumeToken(); 03658 03659 // If we see a type specifier followed by an open-brace, we have an 03660 // ambiguity between an underlying type and a C++11 braced 03661 // function-style cast. Resolve this by always treating it as an 03662 // underlying type. 03663 // FIXME: The standard is not entirely clear on how to disambiguate in 03664 // this case. 03665 if ((getLangOpts().CPlusPlus && 03666 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) || 03667 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { 03668 // We'll parse this as a bitfield later. 03669 PossibleBitfield = true; 03670 TPA.Revert(); 03671 } else { 03672 // We have a type-specifier-seq. 03673 TPA.Commit(); 03674 } 03675 } 03676 } else { 03677 // Consume the ':'. 03678 ConsumeToken(); 03679 } 03680 03681 if (!PossibleBitfield) { 03682 SourceRange Range; 03683 BaseType = ParseTypeName(&Range); 03684 03685 if (getLangOpts().CPlusPlus11) { 03686 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 03687 } else if (!getLangOpts().ObjC2) { 03688 if (getLangOpts().CPlusPlus) 03689 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range; 03690 else 03691 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range; 03692 } 03693 } 03694 } 03695 03696 // There are four options here. If we have 'friend enum foo;' then this is a 03697 // friend declaration, and cannot have an accompanying definition. If we have 03698 // 'enum foo;', then this is a forward declaration. If we have 03699 // 'enum foo {...' then this is a definition. Otherwise we have something 03700 // like 'enum foo xyz', a reference. 03701 // 03702 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 03703 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 03704 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 03705 // 03706 Sema::TagUseKind TUK; 03707 if (!AllowDeclaration) { 03708 TUK = Sema::TUK_Reference; 03709 } else if (Tok.is(tok::l_brace)) { 03710 if (DS.isFriendSpecified()) { 03711 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 03712 << SourceRange(DS.getFriendSpecLoc()); 03713 ConsumeBrace(); 03714 SkipUntil(tok::r_brace, StopAtSemi); 03715 TUK = Sema::TUK_Friend; 03716 } else { 03717 TUK = Sema::TUK_Definition; 03718 } 03719 } else if (!isTypeSpecifier(DSC) && 03720 (Tok.is(tok::semi) || 03721 (Tok.isAtStartOfLine() && 03722 !isValidAfterTypeSpecifier(CanBeBitfield)))) { 03723 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 03724 if (Tok.isNot(tok::semi)) { 03725 // A semicolon was missing after this declaration. Diagnose and recover. 03726 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 03727 PP.EnterToken(Tok); 03728 Tok.setKind(tok::semi); 03729 } 03730 } else { 03731 TUK = Sema::TUK_Reference; 03732 } 03733 03734 // If this is an elaborated type specifier, and we delayed 03735 // diagnostics before, just merge them into the current pool. 03736 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { 03737 diagsFromTag.redelay(); 03738 } 03739 03740 MultiTemplateParamsArg TParams; 03741 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 03742 TUK != Sema::TUK_Reference) { 03743 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) { 03744 // Skip the rest of this declarator, up until the comma or semicolon. 03745 Diag(Tok, diag::err_enum_template); 03746 SkipUntil(tok::comma, StopAtSemi); 03747 return; 03748 } 03749 03750 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 03751 // Enumerations can't be explicitly instantiated. 03752 DS.SetTypeSpecError(); 03753 Diag(StartLoc, diag::err_explicit_instantiation_enum); 03754 return; 03755 } 03756 03757 assert(TemplateInfo.TemplateParams && "no template parameters"); 03758 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), 03759 TemplateInfo.TemplateParams->size()); 03760 } 03761 03762 if (TUK == Sema::TUK_Reference) 03763 ProhibitAttributes(attrs); 03764 03765 if (!Name && TUK != Sema::TUK_Definition) { 03766 Diag(Tok, diag::err_enumerator_unnamed_no_def); 03767 03768 // Skip the rest of this declarator, up until the comma or semicolon. 03769 SkipUntil(tok::comma, StopAtSemi); 03770 return; 03771 } 03772 03773 bool Owned = false; 03774 bool IsDependent = false; 03775 const char *PrevSpec = nullptr; 03776 unsigned DiagID; 03777 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 03778 StartLoc, SS, Name, NameLoc, attrs.getList(), 03779 AS, DS.getModulePrivateSpecLoc(), TParams, 03780 Owned, IsDependent, ScopedEnumKWLoc, 03781 IsScopedUsingClassTag, BaseType, 03782 DSC == DSC_type_specifier); 03783 03784 if (IsDependent) { 03785 // This enum has a dependent nested-name-specifier. Handle it as a 03786 // dependent tag. 03787 if (!Name) { 03788 DS.SetTypeSpecError(); 03789 Diag(Tok, diag::err_expected_type_name_after_typename); 03790 return; 03791 } 03792 03793 TypeResult Type = Actions.ActOnDependentTag( 03794 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc); 03795 if (Type.isInvalid()) { 03796 DS.SetTypeSpecError(); 03797 return; 03798 } 03799 03800 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 03801 NameLoc.isValid() ? NameLoc : StartLoc, 03802 PrevSpec, DiagID, Type.get(), 03803 Actions.getASTContext().getPrintingPolicy())) 03804 Diag(StartLoc, DiagID) << PrevSpec; 03805 03806 return; 03807 } 03808 03809 if (!TagDecl) { 03810 // The action failed to produce an enumeration tag. If this is a 03811 // definition, consume the entire definition. 03812 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 03813 ConsumeBrace(); 03814 SkipUntil(tok::r_brace, StopAtSemi); 03815 } 03816 03817 DS.SetTypeSpecError(); 03818 return; 03819 } 03820 03821 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) 03822 ParseEnumBody(StartLoc, TagDecl); 03823 03824 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 03825 NameLoc.isValid() ? NameLoc : StartLoc, 03826 PrevSpec, DiagID, TagDecl, Owned, 03827 Actions.getASTContext().getPrintingPolicy())) 03828 Diag(StartLoc, DiagID) << PrevSpec; 03829 } 03830 03831 /// ParseEnumBody - Parse a {} enclosed enumerator-list. 03832 /// enumerator-list: 03833 /// enumerator 03834 /// enumerator-list ',' enumerator 03835 /// enumerator: 03836 /// enumeration-constant attributes[opt] 03837 /// enumeration-constant attributes[opt] '=' constant-expression 03838 /// enumeration-constant: 03839 /// identifier 03840 /// 03841 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 03842 // Enter the scope of the enum body and start the definition. 03843 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope); 03844 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 03845 03846 BalancedDelimiterTracker T(*this, tok::l_brace); 03847 T.consumeOpen(); 03848 03849 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 03850 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) 03851 Diag(Tok, diag::error_empty_enum); 03852 03853 SmallVector<Decl *, 32> EnumConstantDecls; 03854 03855 Decl *LastEnumConstDecl = nullptr; 03856 03857 // Parse the enumerator-list. 03858 while (Tok.isNot(tok::r_brace)) { 03859 // Parse enumerator. If failed, try skipping till the start of the next 03860 // enumerator definition. 03861 if (Tok.isNot(tok::identifier)) { 03862 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 03863 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) && 03864 TryConsumeToken(tok::comma)) 03865 continue; 03866 break; 03867 } 03868 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 03869 SourceLocation IdentLoc = ConsumeToken(); 03870 03871 // If attributes exist after the enumerator, parse them. 03872 ParsedAttributesWithRange attrs(AttrFactory); 03873 MaybeParseGNUAttributes(attrs); 03874 ProhibitAttributes(attrs); // GNU-style attributes are prohibited. 03875 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { 03876 if (!getLangOpts().CPlusPlus1z) 03877 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute) 03878 << 1 /*enumerator*/; 03879 ParseCXX11Attributes(attrs); 03880 } 03881 03882 SourceLocation EqualLoc; 03883 ExprResult AssignedVal; 03884 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 03885 03886 if (TryConsumeToken(tok::equal, EqualLoc)) { 03887 AssignedVal = ParseConstantExpression(); 03888 if (AssignedVal.isInvalid()) 03889 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch); 03890 } 03891 03892 // Install the enumerator constant into EnumDecl. 03893 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 03894 LastEnumConstDecl, 03895 IdentLoc, Ident, 03896 attrs.getList(), EqualLoc, 03897 AssignedVal.get()); 03898 PD.complete(EnumConstDecl); 03899 03900 EnumConstantDecls.push_back(EnumConstDecl); 03901 LastEnumConstDecl = EnumConstDecl; 03902 03903 if (Tok.is(tok::identifier)) { 03904 // We're missing a comma between enumerators. 03905 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 03906 Diag(Loc, diag::err_enumerator_list_missing_comma) 03907 << FixItHint::CreateInsertion(Loc, ", "); 03908 continue; 03909 } 03910 03911 // Emumerator definition must be finished, only comma or r_brace are 03912 // allowed here. 03913 SourceLocation CommaLoc; 03914 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) { 03915 if (EqualLoc.isValid()) 03916 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace 03917 << tok::comma; 03918 else 03919 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator); 03920 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) { 03921 if (TryConsumeToken(tok::comma, CommaLoc)) 03922 continue; 03923 } else { 03924 break; 03925 } 03926 } 03927 03928 // If comma is followed by r_brace, emit appropriate warning. 03929 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) { 03930 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) 03931 Diag(CommaLoc, getLangOpts().CPlusPlus ? 03932 diag::ext_enumerator_list_comma_cxx : 03933 diag::ext_enumerator_list_comma_c) 03934 << FixItHint::CreateRemoval(CommaLoc); 03935 else if (getLangOpts().CPlusPlus11) 03936 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 03937 << FixItHint::CreateRemoval(CommaLoc); 03938 break; 03939 } 03940 } 03941 03942 // Eat the }. 03943 T.consumeClose(); 03944 03945 // If attributes exist after the identifier list, parse them. 03946 ParsedAttributes attrs(AttrFactory); 03947 MaybeParseGNUAttributes(attrs); 03948 03949 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), 03950 EnumDecl, EnumConstantDecls, 03951 getCurScope(), 03952 attrs.getList()); 03953 03954 EnumScope.Exit(); 03955 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, 03956 T.getCloseLocation()); 03957 03958 // The next token must be valid after an enum definition. If not, a ';' 03959 // was probably forgotten. 03960 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 03961 if (!isValidAfterTypeSpecifier(CanBeBitfield)) { 03962 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); 03963 // Push this token back into the preprocessor and change our current token 03964 // to ';' so that the rest of the code recovers as though there were an 03965 // ';' after the definition. 03966 PP.EnterToken(Tok); 03967 Tok.setKind(tok::semi); 03968 } 03969 } 03970 03971 /// isTypeSpecifierQualifier - Return true if the current token could be the 03972 /// start of a type-qualifier-list. 03973 bool Parser::isTypeQualifier() const { 03974 switch (Tok.getKind()) { 03975 default: return false; 03976 // type-qualifier 03977 case tok::kw_const: 03978 case tok::kw_volatile: 03979 case tok::kw_restrict: 03980 case tok::kw___private: 03981 case tok::kw___local: 03982 case tok::kw___global: 03983 case tok::kw___constant: 03984 case tok::kw___read_only: 03985 case tok::kw___read_write: 03986 case tok::kw___write_only: 03987 return true; 03988 } 03989 } 03990 03991 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token 03992 /// is definitely a type-specifier. Return false if it isn't part of a type 03993 /// specifier or if we're not sure. 03994 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 03995 switch (Tok.getKind()) { 03996 default: return false; 03997 // type-specifiers 03998 case tok::kw_short: 03999 case tok::kw_long: 04000 case tok::kw___int64: 04001 case tok::kw___int128: 04002 case tok::kw_signed: 04003 case tok::kw_unsigned: 04004 case tok::kw__Complex: 04005 case tok::kw__Imaginary: 04006 case tok::kw_void: 04007 case tok::kw_char: 04008 case tok::kw_wchar_t: 04009 case tok::kw_char16_t: 04010 case tok::kw_char32_t: 04011 case tok::kw_int: 04012 case tok::kw_half: 04013 case tok::kw_float: 04014 case tok::kw_double: 04015 case tok::kw_bool: 04016 case tok::kw__Bool: 04017 case tok::kw__Decimal32: 04018 case tok::kw__Decimal64: 04019 case tok::kw__Decimal128: 04020 case tok::kw___vector: 04021 04022 // struct-or-union-specifier (C99) or class-specifier (C++) 04023 case tok::kw_class: 04024 case tok::kw_struct: 04025 case tok::kw___interface: 04026 case tok::kw_union: 04027 // enum-specifier 04028 case tok::kw_enum: 04029 04030 // typedef-name 04031 case tok::annot_typename: 04032 return true; 04033 } 04034 } 04035 04036 /// isTypeSpecifierQualifier - Return true if the current token could be the 04037 /// start of a specifier-qualifier-list. 04038 bool Parser::isTypeSpecifierQualifier() { 04039 switch (Tok.getKind()) { 04040 default: return false; 04041 04042 case tok::identifier: // foo::bar 04043 if (TryAltiVecVectorToken()) 04044 return true; 04045 // Fall through. 04046 case tok::kw_typename: // typename T::type 04047 // Annotate typenames and C++ scope specifiers. If we get one, just 04048 // recurse to handle whatever we get. 04049 if (TryAnnotateTypeOrScopeToken()) 04050 return true; 04051 if (Tok.is(tok::identifier)) 04052 return false; 04053 return isTypeSpecifierQualifier(); 04054 04055 case tok::coloncolon: // ::foo::bar 04056 if (NextToken().is(tok::kw_new) || // ::new 04057 NextToken().is(tok::kw_delete)) // ::delete 04058 return false; 04059 04060 if (TryAnnotateTypeOrScopeToken()) 04061 return true; 04062 return isTypeSpecifierQualifier(); 04063 04064 // GNU attributes support. 04065 case tok::kw___attribute: 04066 // GNU typeof support. 04067 case tok::kw_typeof: 04068 04069 // type-specifiers 04070 case tok::kw_short: 04071 case tok::kw_long: 04072 case tok::kw___int64: 04073 case tok::kw___int128: 04074 case tok::kw_signed: 04075 case tok::kw_unsigned: 04076 case tok::kw__Complex: 04077 case tok::kw__Imaginary: 04078 case tok::kw_void: 04079 case tok::kw_char: 04080 case tok::kw_wchar_t: 04081 case tok::kw_char16_t: 04082 case tok::kw_char32_t: 04083 case tok::kw_int: 04084 case tok::kw_half: 04085 case tok::kw_float: 04086 case tok::kw_double: 04087 case tok::kw_bool: 04088 case tok::kw__Bool: 04089 case tok::kw__Decimal32: 04090 case tok::kw__Decimal64: 04091 case tok::kw__Decimal128: 04092 case tok::kw___vector: 04093 04094 // struct-or-union-specifier (C99) or class-specifier (C++) 04095 case tok::kw_class: 04096 case tok::kw_struct: 04097 case tok::kw___interface: 04098 case tok::kw_union: 04099 // enum-specifier 04100 case tok::kw_enum: 04101 04102 // type-qualifier 04103 case tok::kw_const: 04104 case tok::kw_volatile: 04105 case tok::kw_restrict: 04106 04107 // Debugger support. 04108 case tok::kw___unknown_anytype: 04109 04110 // typedef-name 04111 case tok::annot_typename: 04112 return true; 04113 04114 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 04115 case tok::less: 04116 return getLangOpts().ObjC1; 04117 04118 case tok::kw___cdecl: 04119 case tok::kw___stdcall: 04120 case tok::kw___fastcall: 04121 case tok::kw___thiscall: 04122 case tok::kw___vectorcall: 04123 case tok::kw___w64: 04124 case tok::kw___ptr64: 04125 case tok::kw___ptr32: 04126 case tok::kw___pascal: 04127 case tok::kw___unaligned: 04128 04129 case tok::kw___private: 04130 case tok::kw___local: 04131 case tok::kw___global: 04132 case tok::kw___constant: 04133 case tok::kw___read_only: 04134 case tok::kw___read_write: 04135 case tok::kw___write_only: 04136 04137 return true; 04138 04139 // C11 _Atomic 04140 case tok::kw__Atomic: 04141 return true; 04142 } 04143 } 04144 04145 /// isDeclarationSpecifier() - Return true if the current token is part of a 04146 /// declaration specifier. 04147 /// 04148 /// \param DisambiguatingWithExpression True to indicate that the purpose of 04149 /// this check is to disambiguate between an expression and a declaration. 04150 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 04151 switch (Tok.getKind()) { 04152 default: return false; 04153 04154 case tok::identifier: // foo::bar 04155 // Unfortunate hack to support "Class.factoryMethod" notation. 04156 if (getLangOpts().ObjC1 && NextToken().is(tok::period)) 04157 return false; 04158 if (TryAltiVecVectorToken()) 04159 return true; 04160 // Fall through. 04161 case tok::kw_decltype: // decltype(T())::type 04162 case tok::kw_typename: // typename T::type 04163 // Annotate typenames and C++ scope specifiers. If we get one, just 04164 // recurse to handle whatever we get. 04165 if (TryAnnotateTypeOrScopeToken()) 04166 return true; 04167 if (Tok.is(tok::identifier)) 04168 return false; 04169 04170 // If we're in Objective-C and we have an Objective-C class type followed 04171 // by an identifier and then either ':' or ']', in a place where an 04172 // expression is permitted, then this is probably a class message send 04173 // missing the initial '['. In this case, we won't consider this to be 04174 // the start of a declaration. 04175 if (DisambiguatingWithExpression && 04176 isStartOfObjCClassMessageMissingOpenBracket()) 04177 return false; 04178 04179 return isDeclarationSpecifier(); 04180 04181 case tok::coloncolon: // ::foo::bar 04182 if (NextToken().is(tok::kw_new) || // ::new 04183 NextToken().is(tok::kw_delete)) // ::delete 04184 return false; 04185 04186 // Annotate typenames and C++ scope specifiers. If we get one, just 04187 // recurse to handle whatever we get. 04188 if (TryAnnotateTypeOrScopeToken()) 04189 return true; 04190 return isDeclarationSpecifier(); 04191 04192 // storage-class-specifier 04193 case tok::kw_typedef: 04194 case tok::kw_extern: 04195 case tok::kw___private_extern__: 04196 case tok::kw_static: 04197 case tok::kw_auto: 04198 case tok::kw_register: 04199 case tok::kw___thread: 04200 case tok::kw_thread_local: 04201 case tok::kw__Thread_local: 04202 04203 // Modules 04204 case tok::kw___module_private__: 04205 04206 // Debugger support 04207 case tok::kw___unknown_anytype: 04208 04209 // type-specifiers 04210 case tok::kw_short: 04211 case tok::kw_long: 04212 case tok::kw___int64: 04213 case tok::kw___int128: 04214 case tok::kw_signed: 04215 case tok::kw_unsigned: 04216 case tok::kw__Complex: 04217 case tok::kw__Imaginary: 04218 case tok::kw_void: 04219 case tok::kw_char: 04220 case tok::kw_wchar_t: 04221 case tok::kw_char16_t: 04222 case tok::kw_char32_t: 04223 04224 case tok::kw_int: 04225 case tok::kw_half: 04226 case tok::kw_float: 04227 case tok::kw_double: 04228 case tok::kw_bool: 04229 case tok::kw__Bool: 04230 case tok::kw__Decimal32: 04231 case tok::kw__Decimal64: 04232 case tok::kw__Decimal128: 04233 case tok::kw___vector: 04234 04235 // struct-or-union-specifier (C99) or class-specifier (C++) 04236 case tok::kw_class: 04237 case tok::kw_struct: 04238 case tok::kw_union: 04239 case tok::kw___interface: 04240 // enum-specifier 04241 case tok::kw_enum: 04242 04243 // type-qualifier 04244 case tok::kw_const: 04245 case tok::kw_volatile: 04246 case tok::kw_restrict: 04247 04248 // function-specifier 04249 case tok::kw_inline: 04250 case tok::kw_virtual: 04251 case tok::kw_explicit: 04252 case tok::kw__Noreturn: 04253 04254 // alignment-specifier 04255 case tok::kw__Alignas: 04256 04257 // friend keyword. 04258 case tok::kw_friend: 04259 04260 // static_assert-declaration 04261 case tok::kw__Static_assert: 04262 04263 // GNU typeof support. 04264 case tok::kw_typeof: 04265 04266 // GNU attributes. 04267 case tok::kw___attribute: 04268 04269 // C++11 decltype and constexpr. 04270 case tok::annot_decltype: 04271 case tok::kw_constexpr: 04272 04273 // C11 _Atomic 04274 case tok::kw__Atomic: 04275 return true; 04276 04277 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 04278 case tok::less: 04279 return getLangOpts().ObjC1; 04280 04281 // typedef-name 04282 case tok::annot_typename: 04283 return !DisambiguatingWithExpression || 04284 !isStartOfObjCClassMessageMissingOpenBracket(); 04285 04286 case tok::kw___declspec: 04287 case tok::kw___cdecl: 04288 case tok::kw___stdcall: 04289 case tok::kw___fastcall: 04290 case tok::kw___thiscall: 04291 case tok::kw___vectorcall: 04292 case tok::kw___w64: 04293 case tok::kw___sptr: 04294 case tok::kw___uptr: 04295 case tok::kw___ptr64: 04296 case tok::kw___ptr32: 04297 case tok::kw___forceinline: 04298 case tok::kw___pascal: 04299 case tok::kw___unaligned: 04300 04301 case tok::kw___private: 04302 case tok::kw___local: 04303 case tok::kw___global: 04304 case tok::kw___constant: 04305 case tok::kw___read_only: 04306 case tok::kw___read_write: 04307 case tok::kw___write_only: 04308 04309 return true; 04310 } 04311 } 04312 04313 bool Parser::isConstructorDeclarator(bool IsUnqualified) { 04314 TentativeParsingAction TPA(*this); 04315 04316 // Parse the C++ scope specifier. 04317 CXXScopeSpec SS; 04318 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 04319 /*EnteringContext=*/true)) { 04320 TPA.Revert(); 04321 return false; 04322 } 04323 04324 // Parse the constructor name. 04325 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 04326 // We already know that we have a constructor name; just consume 04327 // the token. 04328 ConsumeToken(); 04329 } else { 04330 TPA.Revert(); 04331 return false; 04332 } 04333 04334 // Current class name must be followed by a left parenthesis. 04335 if (Tok.isNot(tok::l_paren)) { 04336 TPA.Revert(); 04337 return false; 04338 } 04339 ConsumeParen(); 04340 04341 // A right parenthesis, or ellipsis followed by a right parenthesis signals 04342 // that we have a constructor. 04343 if (Tok.is(tok::r_paren) || 04344 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 04345 TPA.Revert(); 04346 return true; 04347 } 04348 04349 // A C++11 attribute here signals that we have a constructor, and is an 04350 // attribute on the first constructor parameter. 04351 if (getLangOpts().CPlusPlus11 && 04352 isCXX11AttributeSpecifier(/*Disambiguate*/ false, 04353 /*OuterMightBeMessageSend*/ true)) { 04354 TPA.Revert(); 04355 return true; 04356 } 04357 04358 // If we need to, enter the specified scope. 04359 DeclaratorScopeObj DeclScopeObj(*this, SS); 04360 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 04361 DeclScopeObj.EnterDeclaratorScope(); 04362 04363 // Optionally skip Microsoft attributes. 04364 ParsedAttributes Attrs(AttrFactory); 04365 MaybeParseMicrosoftAttributes(Attrs); 04366 04367 // Check whether the next token(s) are part of a declaration 04368 // specifier, in which case we have the start of a parameter and, 04369 // therefore, we know that this is a constructor. 04370 bool IsConstructor = false; 04371 if (isDeclarationSpecifier()) 04372 IsConstructor = true; 04373 else if (Tok.is(tok::identifier) || 04374 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 04375 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 04376 // This might be a parenthesized member name, but is more likely to 04377 // be a constructor declaration with an invalid argument type. Keep 04378 // looking. 04379 if (Tok.is(tok::annot_cxxscope)) 04380 ConsumeToken(); 04381 ConsumeToken(); 04382 04383 // If this is not a constructor, we must be parsing a declarator, 04384 // which must have one of the following syntactic forms (see the 04385 // grammar extract at the start of ParseDirectDeclarator): 04386 switch (Tok.getKind()) { 04387 case tok::l_paren: 04388 // C(X ( int)); 04389 case tok::l_square: 04390 // C(X [ 5]); 04391 // C(X [ [attribute]]); 04392 case tok::coloncolon: 04393 // C(X :: Y); 04394 // C(X :: *p); 04395 // Assume this isn't a constructor, rather than assuming it's a 04396 // constructor with an unnamed parameter of an ill-formed type. 04397 break; 04398 04399 case tok::r_paren: 04400 // C(X ) 04401 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) { 04402 // Assume these were meant to be constructors: 04403 // C(X) : (the name of a bit-field cannot be parenthesized). 04404 // C(X) try (this is otherwise ill-formed). 04405 IsConstructor = true; 04406 } 04407 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) { 04408 // If we have a constructor name within the class definition, 04409 // assume these were meant to be constructors: 04410 // C(X) { 04411 // C(X) ; 04412 // ... because otherwise we would be declaring a non-static data 04413 // member that is ill-formed because it's of the same type as its 04414 // surrounding class. 04415 // 04416 // FIXME: We can actually do this whether or not the name is qualified, 04417 // because if it is qualified in this context it must be being used as 04418 // a constructor name. However, we do not implement that rule correctly 04419 // currently, so we're somewhat conservative here. 04420 IsConstructor = IsUnqualified; 04421 } 04422 break; 04423 04424 default: 04425 IsConstructor = true; 04426 break; 04427 } 04428 } 04429 04430 TPA.Revert(); 04431 return IsConstructor; 04432 } 04433 04434 /// ParseTypeQualifierListOpt 04435 /// type-qualifier-list: [C99 6.7.5] 04436 /// type-qualifier 04437 /// [vendor] attributes 04438 /// [ only if AttrReqs & AR_VendorAttributesParsed ] 04439 /// type-qualifier-list type-qualifier 04440 /// [vendor] type-qualifier-list attributes 04441 /// [ only if AttrReqs & AR_VendorAttributesParsed ] 04442 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 04443 /// [ only if AttReqs & AR_CXX11AttributesParsed ] 04444 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via 04445 /// AttrRequirements bitmask values. 04446 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs, 04447 bool AtomicAllowed, 04448 bool IdentifierRequired) { 04449 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) && 04450 isCXX11AttributeSpecifier()) { 04451 ParsedAttributesWithRange attrs(AttrFactory); 04452 ParseCXX11Attributes(attrs); 04453 DS.takeAttributesFrom(attrs); 04454 } 04455 04456 SourceLocation EndLoc; 04457 04458 while (1) { 04459 bool isInvalid = false; 04460 const char *PrevSpec = nullptr; 04461 unsigned DiagID = 0; 04462 SourceLocation Loc = Tok.getLocation(); 04463 04464 switch (Tok.getKind()) { 04465 case tok::code_completion: 04466 Actions.CodeCompleteTypeQualifiers(DS); 04467 return cutOffParsing(); 04468 04469 case tok::kw_const: 04470 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 04471 getLangOpts()); 04472 break; 04473 case tok::kw_volatile: 04474 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 04475 getLangOpts()); 04476 break; 04477 case tok::kw_restrict: 04478 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 04479 getLangOpts()); 04480 break; 04481 case tok::kw__Atomic: 04482 if (!AtomicAllowed) 04483 goto DoneWithTypeQuals; 04484 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 04485 getLangOpts()); 04486 break; 04487 04488 // OpenCL qualifiers: 04489 case tok::kw___private: 04490 case tok::kw___global: 04491 case tok::kw___local: 04492 case tok::kw___constant: 04493 case tok::kw___read_only: 04494 case tok::kw___write_only: 04495 case tok::kw___read_write: 04496 ParseOpenCLQualifiers(DS.getAttributes()); 04497 break; 04498 04499 case tok::kw___uptr: 04500 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts 04501 // with the MS modifier keyword. 04502 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus && 04503 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) { 04504 if (TryKeywordIdentFallback(false)) 04505 continue; 04506 } 04507 case tok::kw___sptr: 04508 case tok::kw___w64: 04509 case tok::kw___ptr64: 04510 case tok::kw___ptr32: 04511 case tok::kw___cdecl: 04512 case tok::kw___stdcall: 04513 case tok::kw___fastcall: 04514 case tok::kw___thiscall: 04515 case tok::kw___vectorcall: 04516 case tok::kw___unaligned: 04517 if (AttrReqs & AR_DeclspecAttributesParsed) { 04518 ParseMicrosoftTypeAttributes(DS.getAttributes()); 04519 continue; 04520 } 04521 goto DoneWithTypeQuals; 04522 case tok::kw___pascal: 04523 if (AttrReqs & AR_VendorAttributesParsed) { 04524 ParseBorlandTypeAttributes(DS.getAttributes()); 04525 continue; 04526 } 04527 goto DoneWithTypeQuals; 04528 case tok::kw___attribute: 04529 if (AttrReqs & AR_GNUAttributesParsedAndRejected) 04530 // When GNU attributes are expressly forbidden, diagnose their usage. 04531 Diag(Tok, diag::err_attributes_not_allowed); 04532 04533 // Parse the attributes even if they are rejected to ensure that error 04534 // recovery is graceful. 04535 if (AttrReqs & AR_GNUAttributesParsed || 04536 AttrReqs & AR_GNUAttributesParsedAndRejected) { 04537 ParseGNUAttributes(DS.getAttributes()); 04538 continue; // do *not* consume the next token! 04539 } 04540 // otherwise, FALL THROUGH! 04541 default: 04542 DoneWithTypeQuals: 04543 // If this is not a type-qualifier token, we're done reading type 04544 // qualifiers. First verify that DeclSpec's are consistent. 04545 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy()); 04546 if (EndLoc.isValid()) 04547 DS.SetRangeEnd(EndLoc); 04548 return; 04549 } 04550 04551 // If the specifier combination wasn't legal, issue a diagnostic. 04552 if (isInvalid) { 04553 assert(PrevSpec && "Method did not return previous specifier!"); 04554 Diag(Tok, DiagID) << PrevSpec; 04555 } 04556 EndLoc = ConsumeToken(); 04557 } 04558 } 04559 04560 04561 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 04562 /// 04563 void Parser::ParseDeclarator(Declarator &D) { 04564 /// This implements the 'declarator' production in the C grammar, then checks 04565 /// for well-formedness and issues diagnostics. 04566 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 04567 } 04568 04569 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, 04570 unsigned TheContext) { 04571 if (Kind == tok::star || Kind == tok::caret) 04572 return true; 04573 04574 if (!Lang.CPlusPlus) 04575 return false; 04576 04577 if (Kind == tok::amp) 04578 return true; 04579 04580 // We parse rvalue refs in C++03, because otherwise the errors are scary. 04581 // But we must not parse them in conversion-type-ids and new-type-ids, since 04582 // those can be legitimately followed by a && operator. 04583 // (The same thing can in theory happen after a trailing-return-type, but 04584 // since those are a C++11 feature, there is no rejects-valid issue there.) 04585 if (Kind == tok::ampamp) 04586 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext && 04587 TheContext != Declarator::CXXNewContext); 04588 04589 return false; 04590 } 04591 04592 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 04593 /// is parsed by the function passed to it. Pass null, and the direct-declarator 04594 /// isn't parsed at all, making this function effectively parse the C++ 04595 /// ptr-operator production. 04596 /// 04597 /// If the grammar of this construct is extended, matching changes must also be 04598 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to 04599 /// isConstructorDeclarator. 04600 /// 04601 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 04602 /// [C] pointer[opt] direct-declarator 04603 /// [C++] direct-declarator 04604 /// [C++] ptr-operator declarator 04605 /// 04606 /// pointer: [C99 6.7.5] 04607 /// '*' type-qualifier-list[opt] 04608 /// '*' type-qualifier-list[opt] pointer 04609 /// 04610 /// ptr-operator: 04611 /// '*' cv-qualifier-seq[opt] 04612 /// '&' 04613 /// [C++0x] '&&' 04614 /// [GNU] '&' restrict[opt] attributes[opt] 04615 /// [GNU?] '&&' restrict[opt] attributes[opt] 04616 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 04617 void Parser::ParseDeclaratorInternal(Declarator &D, 04618 DirectDeclParseFunction DirectDeclParser) { 04619 if (Diags.hasAllExtensionsSilenced()) 04620 D.setExtension(); 04621 04622 // C++ member pointers start with a '::' or a nested-name. 04623 // Member pointers get special handling, since there's no place for the 04624 // scope spec in the generic path below. 04625 if (getLangOpts().CPlusPlus && 04626 (Tok.is(tok::coloncolon) || 04627 (Tok.is(tok::identifier) && 04628 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) || 04629 Tok.is(tok::annot_cxxscope))) { 04630 bool EnteringContext = D.getContext() == Declarator::FileContext || 04631 D.getContext() == Declarator::MemberContext; 04632 CXXScopeSpec SS; 04633 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext); 04634 04635 if (SS.isNotEmpty()) { 04636 if (Tok.isNot(tok::star)) { 04637 // The scope spec really belongs to the direct-declarator. 04638 if (D.mayHaveIdentifier()) 04639 D.getCXXScopeSpec() = SS; 04640 else 04641 AnnotateScopeToken(SS, true); 04642 04643 if (DirectDeclParser) 04644 (this->*DirectDeclParser)(D); 04645 return; 04646 } 04647 04648 SourceLocation Loc = ConsumeToken(); 04649 D.SetRangeEnd(Loc); 04650 DeclSpec DS(AttrFactory); 04651 ParseTypeQualifierListOpt(DS); 04652 D.ExtendWithDeclSpec(DS); 04653 04654 // Recurse to parse whatever is left. 04655 ParseDeclaratorInternal(D, DirectDeclParser); 04656 04657 // Sema will have to catch (syntactically invalid) pointers into global 04658 // scope. It has to catch pointers into namespace scope anyway. 04659 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 04660 Loc), 04661 DS.getAttributes(), 04662 /* Don't replace range end. */SourceLocation()); 04663 return; 04664 } 04665 } 04666 04667 tok::TokenKind Kind = Tok.getKind(); 04668 // Not a pointer, C++ reference, or block. 04669 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) { 04670 if (DirectDeclParser) 04671 (this->*DirectDeclParser)(D); 04672 return; 04673 } 04674 04675 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 04676 // '&&' -> rvalue reference 04677 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 04678 D.SetRangeEnd(Loc); 04679 04680 if (Kind == tok::star || Kind == tok::caret) { 04681 // Is a pointer. 04682 DeclSpec DS(AttrFactory); 04683 04684 // GNU attributes are not allowed here in a new-type-id, but Declspec and 04685 // C++11 attributes are allowed. 04686 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed | 04687 ((D.getContext() != Declarator::CXXNewContext) 04688 ? AR_GNUAttributesParsed 04689 : AR_GNUAttributesParsedAndRejected); 04690 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier()); 04691 D.ExtendWithDeclSpec(DS); 04692 04693 // Recursively parse the declarator. 04694 ParseDeclaratorInternal(D, DirectDeclParser); 04695 if (Kind == tok::star) 04696 // Remember that we parsed a pointer type, and remember the type-quals. 04697 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 04698 DS.getConstSpecLoc(), 04699 DS.getVolatileSpecLoc(), 04700 DS.getRestrictSpecLoc()), 04701 DS.getAttributes(), 04702 SourceLocation()); 04703 else 04704 // Remember that we parsed a Block type, and remember the type-quals. 04705 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 04706 Loc), 04707 DS.getAttributes(), 04708 SourceLocation()); 04709 } else { 04710 // Is a reference 04711 DeclSpec DS(AttrFactory); 04712 04713 // Complain about rvalue references in C++03, but then go on and build 04714 // the declarator. 04715 if (Kind == tok::ampamp) 04716 Diag(Loc, getLangOpts().CPlusPlus11 ? 04717 diag::warn_cxx98_compat_rvalue_reference : 04718 diag::ext_rvalue_reference); 04719 04720 // GNU-style and C++11 attributes are allowed here, as is restrict. 04721 ParseTypeQualifierListOpt(DS); 04722 D.ExtendWithDeclSpec(DS); 04723 04724 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 04725 // cv-qualifiers are introduced through the use of a typedef or of a 04726 // template type argument, in which case the cv-qualifiers are ignored. 04727 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 04728 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 04729 Diag(DS.getConstSpecLoc(), 04730 diag::err_invalid_reference_qualifier_application) << "const"; 04731 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 04732 Diag(DS.getVolatileSpecLoc(), 04733 diag::err_invalid_reference_qualifier_application) << "volatile"; 04734 // 'restrict' is permitted as an extension. 04735 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 04736 Diag(DS.getAtomicSpecLoc(), 04737 diag::err_invalid_reference_qualifier_application) << "_Atomic"; 04738 } 04739 04740 // Recursively parse the declarator. 04741 ParseDeclaratorInternal(D, DirectDeclParser); 04742 04743 if (D.getNumTypeObjects() > 0) { 04744 // C++ [dcl.ref]p4: There shall be no references to references. 04745 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 04746 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 04747 if (const IdentifierInfo *II = D.getIdentifier()) 04748 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 04749 << II; 04750 else 04751 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 04752 << "type name"; 04753 04754 // Once we've complained about the reference-to-reference, we 04755 // can go ahead and build the (technically ill-formed) 04756 // declarator: reference collapsing will take care of it. 04757 } 04758 } 04759 04760 // Remember that we parsed a reference type. 04761 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 04762 Kind == tok::amp), 04763 DS.getAttributes(), 04764 SourceLocation()); 04765 } 04766 } 04767 04768 // When correcting from misplaced brackets before the identifier, the location 04769 // is saved inside the declarator so that other diagnostic messages can use 04770 // them. This extracts and returns that location, or returns the provided 04771 // location if a stored location does not exist. 04772 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, 04773 SourceLocation Loc) { 04774 if (D.getName().StartLocation.isInvalid() && 04775 D.getName().EndLocation.isValid()) 04776 return D.getName().EndLocation; 04777 04778 return Loc; 04779 } 04780 04781 /// ParseDirectDeclarator 04782 /// direct-declarator: [C99 6.7.5] 04783 /// [C99] identifier 04784 /// '(' declarator ')' 04785 /// [GNU] '(' attributes declarator ')' 04786 /// [C90] direct-declarator '[' constant-expression[opt] ']' 04787 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 04788 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 04789 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 04790 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 04791 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 04792 /// attribute-specifier-seq[opt] 04793 /// direct-declarator '(' parameter-type-list ')' 04794 /// direct-declarator '(' identifier-list[opt] ')' 04795 /// [GNU] direct-declarator '(' parameter-forward-declarations 04796 /// parameter-type-list[opt] ')' 04797 /// [C++] direct-declarator '(' parameter-declaration-clause ')' 04798 /// cv-qualifier-seq[opt] exception-specification[opt] 04799 /// [C++11] direct-declarator '(' parameter-declaration-clause ')' 04800 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt] 04801 /// ref-qualifier[opt] exception-specification[opt] 04802 /// [C++] declarator-id 04803 /// [C++11] declarator-id attribute-specifier-seq[opt] 04804 /// 04805 /// declarator-id: [C++ 8] 04806 /// '...'[opt] id-expression 04807 /// '::'[opt] nested-name-specifier[opt] type-name 04808 /// 04809 /// id-expression: [C++ 5.1] 04810 /// unqualified-id 04811 /// qualified-id 04812 /// 04813 /// unqualified-id: [C++ 5.1] 04814 /// identifier 04815 /// operator-function-id 04816 /// conversion-function-id 04817 /// '~' class-name 04818 /// template-id 04819 /// 04820 /// Note, any additional constructs added here may need corresponding changes 04821 /// in isConstructorDeclarator. 04822 void Parser::ParseDirectDeclarator(Declarator &D) { 04823 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 04824 04825 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { 04826 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in 04827 // this context it is a bitfield. Also in range-based for statement colon 04828 // may delimit for-range-declaration. 04829 ColonProtectionRAIIObject X(*this, 04830 D.getContext() == Declarator::MemberContext || 04831 (D.getContext() == Declarator::ForContext && 04832 getLangOpts().CPlusPlus11)); 04833 04834 // ParseDeclaratorInternal might already have parsed the scope. 04835 if (D.getCXXScopeSpec().isEmpty()) { 04836 bool EnteringContext = D.getContext() == Declarator::FileContext || 04837 D.getContext() == Declarator::MemberContext; 04838 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), 04839 EnteringContext); 04840 } 04841 04842 if (D.getCXXScopeSpec().isValid()) { 04843 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 04844 // Change the declaration context for name lookup, until this function 04845 // is exited (and the declarator has been parsed). 04846 DeclScopeObj.EnterDeclaratorScope(); 04847 } 04848 04849 // C++0x [dcl.fct]p14: 04850 // There is a syntactic ambiguity when an ellipsis occurs at the end 04851 // of a parameter-declaration-clause without a preceding comma. In 04852 // this case, the ellipsis is parsed as part of the 04853 // abstract-declarator if the type of the parameter names a template 04854 // parameter pack that has not been expanded; otherwise, it is parsed 04855 // as part of the parameter-declaration-clause. 04856 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && 04857 !((D.getContext() == Declarator::PrototypeContext || 04858 D.getContext() == Declarator::LambdaExprParameterContext || 04859 D.getContext() == Declarator::BlockLiteralContext) && 04860 NextToken().is(tok::r_paren) && 04861 !D.hasGroupingParens() && 04862 !Actions.containsUnexpandedParameterPacks(D))) { 04863 SourceLocation EllipsisLoc = ConsumeToken(); 04864 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) { 04865 // The ellipsis was put in the wrong place. Recover, and explain to 04866 // the user what they should have done. 04867 ParseDeclarator(D); 04868 if (EllipsisLoc.isValid()) 04869 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 04870 return; 04871 } else 04872 D.setEllipsisLoc(EllipsisLoc); 04873 04874 // The ellipsis can't be followed by a parenthesized declarator. We 04875 // check for that in ParseParenDeclarator, after we have disambiguated 04876 // the l_paren token. 04877 } 04878 04879 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 04880 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 04881 // We found something that indicates the start of an unqualified-id. 04882 // Parse that unqualified-id. 04883 bool AllowConstructorName; 04884 if (D.getDeclSpec().hasTypeSpecifier()) 04885 AllowConstructorName = false; 04886 else if (D.getCXXScopeSpec().isSet()) 04887 AllowConstructorName = 04888 (D.getContext() == Declarator::FileContext || 04889 D.getContext() == Declarator::MemberContext); 04890 else 04891 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 04892 04893 SourceLocation TemplateKWLoc; 04894 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 04895 /*EnteringContext=*/true, 04896 /*AllowDestructorName=*/true, 04897 AllowConstructorName, 04898 ParsedType(), 04899 TemplateKWLoc, 04900 D.getName()) || 04901 // Once we're past the identifier, if the scope was bad, mark the 04902 // whole declarator bad. 04903 D.getCXXScopeSpec().isInvalid()) { 04904 D.SetIdentifier(nullptr, Tok.getLocation()); 04905 D.setInvalidType(true); 04906 } else { 04907 // Parsed the unqualified-id; update range information and move along. 04908 if (D.getSourceRange().getBegin().isInvalid()) 04909 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 04910 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 04911 } 04912 goto PastIdentifier; 04913 } 04914 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 04915 assert(!getLangOpts().CPlusPlus && 04916 "There's a C++-specific check for tok::identifier above"); 04917 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 04918 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 04919 D.SetRangeEnd(Tok.getLocation()); 04920 ConsumeToken(); 04921 goto PastIdentifier; 04922 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) { 04923 // A virt-specifier isn't treated as an identifier if it appears after a 04924 // trailing-return-type. 04925 if (D.getContext() != Declarator::TrailingReturnContext || 04926 !isCXX11VirtSpecifier(Tok)) { 04927 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id) 04928 << FixItHint::CreateRemoval(Tok.getLocation()); 04929 D.SetIdentifier(nullptr, Tok.getLocation()); 04930 ConsumeToken(); 04931 goto PastIdentifier; 04932 } 04933 } 04934 04935 if (Tok.is(tok::l_paren)) { 04936 // direct-declarator: '(' declarator ')' 04937 // direct-declarator: '(' attributes declarator ')' 04938 // Example: 'char (*X)' or 'int (*XX)(void)' 04939 ParseParenDeclarator(D); 04940 04941 // If the declarator was parenthesized, we entered the declarator 04942 // scope when parsing the parenthesized declarator, then exited 04943 // the scope already. Re-enter the scope, if we need to. 04944 if (D.getCXXScopeSpec().isSet()) { 04945 // If there was an error parsing parenthesized declarator, declarator 04946 // scope may have been entered before. Don't do it again. 04947 if (!D.isInvalidType() && 04948 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 04949 // Change the declaration context for name lookup, until this function 04950 // is exited (and the declarator has been parsed). 04951 DeclScopeObj.EnterDeclaratorScope(); 04952 } 04953 } else if (D.mayOmitIdentifier()) { 04954 // This could be something simple like "int" (in which case the declarator 04955 // portion is empty), if an abstract-declarator is allowed. 04956 D.SetIdentifier(nullptr, Tok.getLocation()); 04957 04958 // The grammar for abstract-pack-declarator does not allow grouping parens. 04959 // FIXME: Revisit this once core issue 1488 is resolved. 04960 if (D.hasEllipsis() && D.hasGroupingParens()) 04961 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()), 04962 diag::ext_abstract_pack_declarator_parens); 04963 } else { 04964 if (Tok.getKind() == tok::annot_pragma_parser_crash) 04965 LLVM_BUILTIN_TRAP; 04966 if (Tok.is(tok::l_square)) 04967 return ParseMisplacedBracketDeclarator(D); 04968 if (D.getContext() == Declarator::MemberContext) { 04969 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 04970 diag::err_expected_member_name_or_semi) 04971 << (D.getDeclSpec().isEmpty() ? SourceRange() 04972 : D.getDeclSpec().getSourceRange()); 04973 } else if (getLangOpts().CPlusPlus) { 04974 if (Tok.is(tok::period) || Tok.is(tok::arrow)) 04975 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow); 04976 else { 04977 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc(); 04978 if (Tok.isAtStartOfLine() && Loc.isValid()) 04979 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id) 04980 << getLangOpts().CPlusPlus; 04981 else 04982 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 04983 diag::err_expected_unqualified_id) 04984 << getLangOpts().CPlusPlus; 04985 } 04986 } else { 04987 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), 04988 diag::err_expected_either) 04989 << tok::identifier << tok::l_paren; 04990 } 04991 D.SetIdentifier(nullptr, Tok.getLocation()); 04992 D.setInvalidType(true); 04993 } 04994 04995 PastIdentifier: 04996 assert(D.isPastIdentifier() && 04997 "Haven't past the location of the identifier yet?"); 04998 04999 // Don't parse attributes unless we have parsed an unparenthesized name. 05000 if (D.hasName() && !D.getNumTypeObjects()) 05001 MaybeParseCXX11Attributes(D); 05002 05003 while (1) { 05004 if (Tok.is(tok::l_paren)) { 05005 // Enter function-declaration scope, limiting any declarators to the 05006 // function prototype scope, including parameter declarators. 05007 ParseScope PrototypeScope(this, 05008 Scope::FunctionPrototypeScope|Scope::DeclScope| 05009 (D.isFunctionDeclaratorAFunctionDeclaration() 05010 ? Scope::FunctionDeclarationScope : 0)); 05011 05012 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 05013 // In such a case, check if we actually have a function declarator; if it 05014 // is not, the declarator has been fully parsed. 05015 bool IsAmbiguous = false; 05016 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 05017 // The name of the declarator, if any, is tentatively declared within 05018 // a possible direct initializer. 05019 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier()); 05020 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous); 05021 TentativelyDeclaredIdentifiers.pop_back(); 05022 if (!IsFunctionDecl) 05023 break; 05024 } 05025 ParsedAttributes attrs(AttrFactory); 05026 BalancedDelimiterTracker T(*this, tok::l_paren); 05027 T.consumeOpen(); 05028 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous); 05029 PrototypeScope.Exit(); 05030 } else if (Tok.is(tok::l_square)) { 05031 ParseBracketDeclarator(D); 05032 } else { 05033 break; 05034 } 05035 } 05036 } 05037 05038 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 05039 /// only called before the identifier, so these are most likely just grouping 05040 /// parens for precedence. If we find that these are actually function 05041 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 05042 /// 05043 /// direct-declarator: 05044 /// '(' declarator ')' 05045 /// [GNU] '(' attributes declarator ')' 05046 /// direct-declarator '(' parameter-type-list ')' 05047 /// direct-declarator '(' identifier-list[opt] ')' 05048 /// [GNU] direct-declarator '(' parameter-forward-declarations 05049 /// parameter-type-list[opt] ')' 05050 /// 05051 void Parser::ParseParenDeclarator(Declarator &D) { 05052 BalancedDelimiterTracker T(*this, tok::l_paren); 05053 T.consumeOpen(); 05054 05055 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 05056 05057 // Eat any attributes before we look at whether this is a grouping or function 05058 // declarator paren. If this is a grouping paren, the attribute applies to 05059 // the type being built up, for example: 05060 // int (__attribute__(()) *x)(long y) 05061 // If this ends up not being a grouping paren, the attribute applies to the 05062 // first argument, for example: 05063 // int (__attribute__(()) int x) 05064 // In either case, we need to eat any attributes to be able to determine what 05065 // sort of paren this is. 05066 // 05067 ParsedAttributes attrs(AttrFactory); 05068 bool RequiresArg = false; 05069 if (Tok.is(tok::kw___attribute)) { 05070 ParseGNUAttributes(attrs); 05071 05072 // We require that the argument list (if this is a non-grouping paren) be 05073 // present even if the attribute list was empty. 05074 RequiresArg = true; 05075 } 05076 05077 // Eat any Microsoft extensions. 05078 ParseMicrosoftTypeAttributes(attrs); 05079 05080 // Eat any Borland extensions. 05081 if (Tok.is(tok::kw___pascal)) 05082 ParseBorlandTypeAttributes(attrs); 05083 05084 // If we haven't past the identifier yet (or where the identifier would be 05085 // stored, if this is an abstract declarator), then this is probably just 05086 // grouping parens. However, if this could be an abstract-declarator, then 05087 // this could also be the start of function arguments (consider 'void()'). 05088 bool isGrouping; 05089 05090 if (!D.mayOmitIdentifier()) { 05091 // If this can't be an abstract-declarator, this *must* be a grouping 05092 // paren, because we haven't seen the identifier yet. 05093 isGrouping = true; 05094 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 05095 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && 05096 NextToken().is(tok::r_paren)) || // C++ int(...) 05097 isDeclarationSpecifier() || // 'int(int)' is a function. 05098 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. 05099 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 05100 // considered to be a type, not a K&R identifier-list. 05101 isGrouping = false; 05102 } else { 05103 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 05104 isGrouping = true; 05105 } 05106 05107 // If this is a grouping paren, handle: 05108 // direct-declarator: '(' declarator ')' 05109 // direct-declarator: '(' attributes declarator ')' 05110 if (isGrouping) { 05111 SourceLocation EllipsisLoc = D.getEllipsisLoc(); 05112 D.setEllipsisLoc(SourceLocation()); 05113 05114 bool hadGroupingParens = D.hasGroupingParens(); 05115 D.setGroupingParens(true); 05116 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 05117 // Match the ')'. 05118 T.consumeClose(); 05119 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), 05120 T.getCloseLocation()), 05121 attrs, T.getCloseLocation()); 05122 05123 D.setGroupingParens(hadGroupingParens); 05124 05125 // An ellipsis cannot be placed outside parentheses. 05126 if (EllipsisLoc.isValid()) 05127 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); 05128 05129 return; 05130 } 05131 05132 // Okay, if this wasn't a grouping paren, it must be the start of a function 05133 // argument list. Recognize that this declarator will never have an 05134 // identifier (and remember where it would have been), then call into 05135 // ParseFunctionDeclarator to handle of argument list. 05136 D.SetIdentifier(nullptr, Tok.getLocation()); 05137 05138 // Enter function-declaration scope, limiting any declarators to the 05139 // function prototype scope, including parameter declarators. 05140 ParseScope PrototypeScope(this, 05141 Scope::FunctionPrototypeScope | Scope::DeclScope | 05142 (D.isFunctionDeclaratorAFunctionDeclaration() 05143 ? Scope::FunctionDeclarationScope : 0)); 05144 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg); 05145 PrototypeScope.Exit(); 05146 } 05147 05148 /// ParseFunctionDeclarator - We are after the identifier and have parsed the 05149 /// declarator D up to a paren, which indicates that we are parsing function 05150 /// arguments. 05151 /// 05152 /// If FirstArgAttrs is non-null, then the caller parsed those arguments 05153 /// immediately after the open paren - they should be considered to be the 05154 /// first argument of a parameter. 05155 /// 05156 /// If RequiresArg is true, then the first argument of the function is required 05157 /// to be present and required to not be an identifier list. 05158 /// 05159 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], 05160 /// (C++11) ref-qualifier[opt], exception-specification[opt], 05161 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt]. 05162 /// 05163 /// [C++11] exception-specification: 05164 /// dynamic-exception-specification 05165 /// noexcept-specification 05166 /// 05167 void Parser::ParseFunctionDeclarator(Declarator &D, 05168 ParsedAttributes &FirstArgAttrs, 05169 BalancedDelimiterTracker &Tracker, 05170 bool IsAmbiguous, 05171 bool RequiresArg) { 05172 assert(getCurScope()->isFunctionPrototypeScope() && 05173 "Should call from a Function scope"); 05174 // lparen is already consumed! 05175 assert(D.isPastIdentifier() && "Should not call before identifier!"); 05176 05177 // This should be true when the function has typed arguments. 05178 // Otherwise, it is treated as a K&R-style function. 05179 bool HasProto = false; 05180 // Build up an array of information about the parsed arguments. 05181 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 05182 // Remember where we see an ellipsis, if any. 05183 SourceLocation EllipsisLoc; 05184 05185 DeclSpec DS(AttrFactory); 05186 bool RefQualifierIsLValueRef = true; 05187 SourceLocation RefQualifierLoc; 05188 SourceLocation ConstQualifierLoc; 05189 SourceLocation VolatileQualifierLoc; 05190 SourceLocation RestrictQualifierLoc; 05191 ExceptionSpecificationType ESpecType = EST_None; 05192 SourceRange ESpecRange; 05193 SmallVector<ParsedType, 2> DynamicExceptions; 05194 SmallVector<SourceRange, 2> DynamicExceptionRanges; 05195 ExprResult NoexceptExpr; 05196 CachedTokens *ExceptionSpecTokens = 0; 05197 ParsedAttributes FnAttrs(AttrFactory); 05198 TypeResult TrailingReturnType; 05199 05200 /* LocalEndLoc is the end location for the local FunctionTypeLoc. 05201 EndLoc is the end location for the function declarator. 05202 They differ for trailing return types. */ 05203 SourceLocation StartLoc, LocalEndLoc, EndLoc; 05204 SourceLocation LParenLoc, RParenLoc; 05205 LParenLoc = Tracker.getOpenLocation(); 05206 StartLoc = LParenLoc; 05207 05208 if (isFunctionDeclaratorIdentifierList()) { 05209 if (RequiresArg) 05210 Diag(Tok, diag::err_argument_required_after_attribute); 05211 05212 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 05213 05214 Tracker.consumeClose(); 05215 RParenLoc = Tracker.getCloseLocation(); 05216 LocalEndLoc = RParenLoc; 05217 EndLoc = RParenLoc; 05218 } else { 05219 if (Tok.isNot(tok::r_paren)) 05220 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, 05221 EllipsisLoc); 05222 else if (RequiresArg) 05223 Diag(Tok, diag::err_argument_required_after_attribute); 05224 05225 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus; 05226 05227 // If we have the closing ')', eat it. 05228 Tracker.consumeClose(); 05229 RParenLoc = Tracker.getCloseLocation(); 05230 LocalEndLoc = RParenLoc; 05231 EndLoc = RParenLoc; 05232 05233 if (getLangOpts().CPlusPlus) { 05234 // FIXME: Accept these components in any order, and produce fixits to 05235 // correct the order if the user gets it wrong. Ideally we should deal 05236 // with the virt-specifier-seq and pure-specifier in the same way. 05237 05238 // Parse cv-qualifier-seq[opt]. 05239 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, 05240 /*AtomicAllowed*/ false); 05241 if (!DS.getSourceRange().getEnd().isInvalid()) { 05242 EndLoc = DS.getSourceRange().getEnd(); 05243 ConstQualifierLoc = DS.getConstSpecLoc(); 05244 VolatileQualifierLoc = DS.getVolatileSpecLoc(); 05245 RestrictQualifierLoc = DS.getRestrictSpecLoc(); 05246 } 05247 05248 // Parse ref-qualifier[opt]. 05249 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 05250 Diag(Tok, getLangOpts().CPlusPlus11 ? 05251 diag::warn_cxx98_compat_ref_qualifier : 05252 diag::ext_ref_qualifier); 05253 05254 RefQualifierIsLValueRef = Tok.is(tok::amp); 05255 RefQualifierLoc = ConsumeToken(); 05256 EndLoc = RefQualifierLoc; 05257 } 05258 05259 // C++11 [expr.prim.general]p3: 05260 // If a declaration declares a member function or member function 05261 // template of a class X, the expression this is a prvalue of type 05262 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 05263 // and the end of the function-definition, member-declarator, or 05264 // declarator. 05265 // FIXME: currently, "static" case isn't handled correctly. 05266 bool IsCXX11MemberFunction = 05267 getLangOpts().CPlusPlus11 && 05268 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 05269 (D.getContext() == Declarator::MemberContext 05270 ? !D.getDeclSpec().isFriendSpecified() 05271 : D.getContext() == Declarator::FileContext && 05272 D.getCXXScopeSpec().isValid() && 05273 Actions.CurContext->isRecord()); 05274 Sema::CXXThisScopeRAII ThisScope(Actions, 05275 dyn_cast<CXXRecordDecl>(Actions.CurContext), 05276 DS.getTypeQualifiers() | 05277 (D.getDeclSpec().isConstexprSpecified() && 05278 !getLangOpts().CPlusPlus14 05279 ? Qualifiers::Const : 0), 05280 IsCXX11MemberFunction); 05281 05282 // Parse exception-specification[opt]. 05283 bool Delayed = D.isFirstDeclarationOfMember() && 05284 D.isFunctionDeclaratorAFunctionDeclaration() && 05285 !Actions.isLibstdcxxEagerExceptionSpecHack(D); 05286 ESpecType = tryParseExceptionSpecification(Delayed, 05287 ESpecRange, 05288 DynamicExceptions, 05289 DynamicExceptionRanges, 05290 NoexceptExpr, 05291 ExceptionSpecTokens); 05292 if (ESpecType != EST_None) 05293 EndLoc = ESpecRange.getEnd(); 05294 05295 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes 05296 // after the exception-specification. 05297 MaybeParseCXX11Attributes(FnAttrs); 05298 05299 // Parse trailing-return-type[opt]. 05300 LocalEndLoc = EndLoc; 05301 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) { 05302 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 05303 if (D.getDeclSpec().getTypeSpecType() == TST_auto) 05304 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 05305 LocalEndLoc = Tok.getLocation(); 05306 SourceRange Range; 05307 TrailingReturnType = ParseTrailingReturnType(Range); 05308 EndLoc = Range.getEnd(); 05309 } 05310 } 05311 } 05312 05313 // Remember that we parsed a function type, and remember the attributes. 05314 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, 05315 IsAmbiguous, 05316 LParenLoc, 05317 ParamInfo.data(), ParamInfo.size(), 05318 EllipsisLoc, RParenLoc, 05319 DS.getTypeQualifiers(), 05320 RefQualifierIsLValueRef, 05321 RefQualifierLoc, ConstQualifierLoc, 05322 VolatileQualifierLoc, 05323 RestrictQualifierLoc, 05324 /*MutableLoc=*/SourceLocation(), 05325 ESpecType, ESpecRange.getBegin(), 05326 DynamicExceptions.data(), 05327 DynamicExceptionRanges.data(), 05328 DynamicExceptions.size(), 05329 NoexceptExpr.isUsable() ? 05330 NoexceptExpr.get() : nullptr, 05331 ExceptionSpecTokens, 05332 StartLoc, LocalEndLoc, D, 05333 TrailingReturnType), 05334 FnAttrs, EndLoc); 05335 } 05336 05337 /// isFunctionDeclaratorIdentifierList - This parameter list may have an 05338 /// identifier list form for a K&R-style function: void foo(a,b,c) 05339 /// 05340 /// Note that identifier-lists are only allowed for normal declarators, not for 05341 /// abstract-declarators. 05342 bool Parser::isFunctionDeclaratorIdentifierList() { 05343 return !getLangOpts().CPlusPlus 05344 && Tok.is(tok::identifier) 05345 && !TryAltiVecVectorToken() 05346 // K&R identifier lists can't have typedefs as identifiers, per C99 05347 // 6.7.5.3p11. 05348 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 05349 // Identifier lists follow a really simple grammar: the identifiers can 05350 // be followed *only* by a ", identifier" or ")". However, K&R 05351 // identifier lists are really rare in the brave new modern world, and 05352 // it is very common for someone to typo a type in a non-K&R style 05353 // list. If we are presented with something like: "void foo(intptr x, 05354 // float y)", we don't want to start parsing the function declarator as 05355 // though it is a K&R style declarator just because intptr is an 05356 // invalid type. 05357 // 05358 // To handle this, we check to see if the token after the first 05359 // identifier is a "," or ")". Only then do we parse it as an 05360 // identifier list. 05361 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)); 05362 } 05363 05364 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 05365 /// we found a K&R-style identifier list instead of a typed parameter list. 05366 /// 05367 /// After returning, ParamInfo will hold the parsed parameters. 05368 /// 05369 /// identifier-list: [C99 6.7.5] 05370 /// identifier 05371 /// identifier-list ',' identifier 05372 /// 05373 void Parser::ParseFunctionDeclaratorIdentifierList( 05374 Declarator &D, 05375 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) { 05376 // If there was no identifier specified for the declarator, either we are in 05377 // an abstract-declarator, or we are in a parameter declarator which was found 05378 // to be abstract. In abstract-declarators, identifier lists are not valid: 05379 // diagnose this. 05380 if (!D.getIdentifier()) 05381 Diag(Tok, diag::ext_ident_list_in_param); 05382 05383 // Maintain an efficient lookup of params we have seen so far. 05384 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 05385 05386 do { 05387 // If this isn't an identifier, report the error and skip until ')'. 05388 if (Tok.isNot(tok::identifier)) { 05389 Diag(Tok, diag::err_expected) << tok::identifier; 05390 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 05391 // Forget we parsed anything. 05392 ParamInfo.clear(); 05393 return; 05394 } 05395 05396 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 05397 05398 // Reject 'typedef int y; int test(x, y)', but continue parsing. 05399 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 05400 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 05401 05402 // Verify that the argument identifier has not already been mentioned. 05403 if (!ParamsSoFar.insert(ParmII)) { 05404 Diag(Tok, diag::err_param_redefinition) << ParmII; 05405 } else { 05406 // Remember this identifier in ParamInfo. 05407 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 05408 Tok.getLocation(), 05409 nullptr)); 05410 } 05411 05412 // Eat the identifier. 05413 ConsumeToken(); 05414 // The list continues if we see a comma. 05415 } while (TryConsumeToken(tok::comma)); 05416 } 05417 05418 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 05419 /// after the opening parenthesis. This function will not parse a K&R-style 05420 /// identifier list. 05421 /// 05422 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the 05423 /// caller parsed those arguments immediately after the open paren - they should 05424 /// be considered to be part of the first parameter. 05425 /// 05426 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 05427 /// be the location of the ellipsis, if any was parsed. 05428 /// 05429 /// parameter-type-list: [C99 6.7.5] 05430 /// parameter-list 05431 /// parameter-list ',' '...' 05432 /// [C++] parameter-list '...' 05433 /// 05434 /// parameter-list: [C99 6.7.5] 05435 /// parameter-declaration 05436 /// parameter-list ',' parameter-declaration 05437 /// 05438 /// parameter-declaration: [C99 6.7.5] 05439 /// declaration-specifiers declarator 05440 /// [C++] declaration-specifiers declarator '=' assignment-expression 05441 /// [C++11] initializer-clause 05442 /// [GNU] declaration-specifiers declarator attributes 05443 /// declaration-specifiers abstract-declarator[opt] 05444 /// [C++] declaration-specifiers abstract-declarator[opt] 05445 /// '=' assignment-expression 05446 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes 05447 /// [C++11] attribute-specifier-seq parameter-declaration 05448 /// 05449 void Parser::ParseParameterDeclarationClause( 05450 Declarator &D, 05451 ParsedAttributes &FirstArgAttrs, 05452 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, 05453 SourceLocation &EllipsisLoc) { 05454 do { 05455 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq 05456 // before deciding this was a parameter-declaration-clause. 05457 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) 05458 break; 05459 05460 // Parse the declaration-specifiers. 05461 // Just use the ParsingDeclaration "scope" of the declarator. 05462 DeclSpec DS(AttrFactory); 05463 05464 // Parse any C++11 attributes. 05465 MaybeParseCXX11Attributes(DS.getAttributes()); 05466 05467 // Skip any Microsoft attributes before a param. 05468 MaybeParseMicrosoftAttributes(DS.getAttributes()); 05469 05470 SourceLocation DSStart = Tok.getLocation(); 05471 05472 // If the caller parsed attributes for the first argument, add them now. 05473 // Take them so that we only apply the attributes to the first parameter. 05474 // FIXME: If we can leave the attributes in the token stream somehow, we can 05475 // get rid of a parameter (FirstArgAttrs) and this statement. It might be 05476 // too much hassle. 05477 DS.takeAttributesFrom(FirstArgAttrs); 05478 05479 ParseDeclarationSpecifiers(DS); 05480 05481 05482 // Parse the declarator. This is "PrototypeContext" or 05483 // "LambdaExprParameterContext", because we must accept either 05484 // 'declarator' or 'abstract-declarator' here. 05485 Declarator ParmDeclarator(DS, 05486 D.getContext() == Declarator::LambdaExprContext ? 05487 Declarator::LambdaExprParameterContext : 05488 Declarator::PrototypeContext); 05489 ParseDeclarator(ParmDeclarator); 05490 05491 // Parse GNU attributes, if present. 05492 MaybeParseGNUAttributes(ParmDeclarator); 05493 05494 // Remember this parsed parameter in ParamInfo. 05495 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier(); 05496 05497 // DefArgToks is used when the parsing of default arguments needs 05498 // to be delayed. 05499 CachedTokens *DefArgToks = nullptr; 05500 05501 // If no parameter was specified, verify that *something* was specified, 05502 // otherwise we have a missing type and identifier. 05503 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr && 05504 ParmDeclarator.getNumTypeObjects() == 0) { 05505 // Completely missing, emit error. 05506 Diag(DSStart, diag::err_missing_param); 05507 } else { 05508 // Otherwise, we have something. Add it and let semantic analysis try 05509 // to grok it and add the result to the ParamInfo we are building. 05510 05511 // Last chance to recover from a misplaced ellipsis in an attempted 05512 // parameter pack declaration. 05513 if (Tok.is(tok::ellipsis) && 05514 (NextToken().isNot(tok::r_paren) || 05515 (!ParmDeclarator.getEllipsisLoc().isValid() && 05516 !Actions.isUnexpandedParameterPackPermitted())) && 05517 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) 05518 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator); 05519 05520 // Inform the actions module about the parameter declarator, so it gets 05521 // added to the current scope. 05522 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 05523 // Parse the default argument, if any. We parse the default 05524 // arguments in all dialects; the semantic analysis in 05525 // ActOnParamDefaultArgument will reject the default argument in 05526 // C. 05527 if (Tok.is(tok::equal)) { 05528 SourceLocation EqualLoc = Tok.getLocation(); 05529 05530 // Parse the default argument 05531 if (D.getContext() == Declarator::MemberContext) { 05532 // If we're inside a class definition, cache the tokens 05533 // corresponding to the default argument. We'll actually parse 05534 // them when we see the end of the class definition. 05535 // FIXME: Can we use a smart pointer for Toks? 05536 DefArgToks = new CachedTokens; 05537 05538 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) { 05539 delete DefArgToks; 05540 DefArgToks = nullptr; 05541 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 05542 } else { 05543 // Mark the end of the default argument so that we know when to 05544 // stop when we parse it later on. 05545 Token DefArgEnd; 05546 DefArgEnd.startToken(); 05547 DefArgEnd.setKind(tok::cxx_defaultarg_end); 05548 DefArgEnd.setLocation(Tok.getLocation()); 05549 DefArgToks->push_back(DefArgEnd); 05550 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 05551 (*DefArgToks)[1].getLocation()); 05552 } 05553 } else { 05554 // Consume the '='. 05555 ConsumeToken(); 05556 05557 // The argument isn't actually potentially evaluated unless it is 05558 // used. 05559 EnterExpressionEvaluationContext Eval(Actions, 05560 Sema::PotentiallyEvaluatedIfUsed, 05561 Param); 05562 05563 ExprResult DefArgResult; 05564 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 05565 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 05566 DefArgResult = ParseBraceInitializer(); 05567 } else 05568 DefArgResult = ParseAssignmentExpression(); 05569 if (DefArgResult.isInvalid()) { 05570 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 05571 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch); 05572 } else { 05573 // Inform the actions module about the default argument 05574 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 05575 DefArgResult.get()); 05576 } 05577 } 05578 } 05579 05580 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 05581 ParmDeclarator.getIdentifierLoc(), 05582 Param, DefArgToks)); 05583 } 05584 05585 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { 05586 if (!getLangOpts().CPlusPlus) { 05587 // We have ellipsis without a preceding ',', which is ill-formed 05588 // in C. Complain and provide the fix. 05589 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 05590 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 05591 } else if (ParmDeclarator.getEllipsisLoc().isValid() || 05592 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) { 05593 // It looks like this was supposed to be a parameter pack. Warn and 05594 // point out where the ellipsis should have gone. 05595 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc(); 05596 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg) 05597 << ParmEllipsis.isValid() << ParmEllipsis; 05598 if (ParmEllipsis.isValid()) { 05599 Diag(ParmEllipsis, 05600 diag::note_misplaced_ellipsis_vararg_existing_ellipsis); 05601 } else { 05602 Diag(ParmDeclarator.getIdentifierLoc(), 05603 diag::note_misplaced_ellipsis_vararg_add_ellipsis) 05604 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(), 05605 "...") 05606 << !ParmDeclarator.hasName(); 05607 } 05608 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma) 05609 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 05610 } 05611 05612 // We can't have any more parameters after an ellipsis. 05613 break; 05614 } 05615 05616 // If the next token is a comma, consume it and keep reading arguments. 05617 } while (TryConsumeToken(tok::comma)); 05618 } 05619 05620 /// [C90] direct-declarator '[' constant-expression[opt] ']' 05621 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 05622 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 05623 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 05624 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 05625 /// [C++11] direct-declarator '[' constant-expression[opt] ']' 05626 /// attribute-specifier-seq[opt] 05627 void Parser::ParseBracketDeclarator(Declarator &D) { 05628 if (CheckProhibitedCXX11Attribute()) 05629 return; 05630 05631 BalancedDelimiterTracker T(*this, tok::l_square); 05632 T.consumeOpen(); 05633 05634 // C array syntax has many features, but by-far the most common is [] and [4]. 05635 // This code does a fast path to handle some of the most obvious cases. 05636 if (Tok.getKind() == tok::r_square) { 05637 T.consumeClose(); 05638 ParsedAttributes attrs(AttrFactory); 05639 MaybeParseCXX11Attributes(attrs); 05640 05641 // Remember that we parsed the empty array type. 05642 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr, 05643 T.getOpenLocation(), 05644 T.getCloseLocation()), 05645 attrs, T.getCloseLocation()); 05646 return; 05647 } else if (Tok.getKind() == tok::numeric_constant && 05648 GetLookAheadToken(1).is(tok::r_square)) { 05649 // [4] is very common. Parse the numeric constant expression. 05650 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); 05651 ConsumeToken(); 05652 05653 T.consumeClose(); 05654 ParsedAttributes attrs(AttrFactory); 05655 MaybeParseCXX11Attributes(attrs); 05656 05657 // Remember that we parsed a array type, and remember its features. 05658 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 05659 ExprRes.get(), 05660 T.getOpenLocation(), 05661 T.getCloseLocation()), 05662 attrs, T.getCloseLocation()); 05663 return; 05664 } 05665 05666 // If valid, this location is the position where we read the 'static' keyword. 05667 SourceLocation StaticLoc; 05668 TryConsumeToken(tok::kw_static, StaticLoc); 05669 05670 // If there is a type-qualifier-list, read it now. 05671 // Type qualifiers in an array subscript are a C99 feature. 05672 DeclSpec DS(AttrFactory); 05673 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed); 05674 05675 // If we haven't already read 'static', check to see if there is one after the 05676 // type-qualifier-list. 05677 if (!StaticLoc.isValid()) 05678 TryConsumeToken(tok::kw_static, StaticLoc); 05679 05680 // Handle "direct-declarator [ type-qual-list[opt] * ]". 05681 bool isStar = false; 05682 ExprResult NumElements; 05683 05684 // Handle the case where we have '[*]' as the array size. However, a leading 05685 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 05686 // the token after the star is a ']'. Since stars in arrays are 05687 // infrequent, use of lookahead is not costly here. 05688 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 05689 ConsumeToken(); // Eat the '*'. 05690 05691 if (StaticLoc.isValid()) { 05692 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 05693 StaticLoc = SourceLocation(); // Drop the static. 05694 } 05695 isStar = true; 05696 } else if (Tok.isNot(tok::r_square)) { 05697 // Note, in C89, this production uses the constant-expr production instead 05698 // of assignment-expr. The only difference is that assignment-expr allows 05699 // things like '=' and '*='. Sema rejects these in C89 mode because they 05700 // are not i-c-e's, so we don't need to distinguish between the two here. 05701 05702 // Parse the constant-expression or assignment-expression now (depending 05703 // on dialect). 05704 if (getLangOpts().CPlusPlus) { 05705 NumElements = ParseConstantExpression(); 05706 } else { 05707 EnterExpressionEvaluationContext Unevaluated(Actions, 05708 Sema::ConstantEvaluated); 05709 NumElements = ParseAssignmentExpression(); 05710 } 05711 } else { 05712 if (StaticLoc.isValid()) { 05713 Diag(StaticLoc, diag::err_unspecified_size_with_static); 05714 StaticLoc = SourceLocation(); // Drop the static. 05715 } 05716 } 05717 05718 // If there was an error parsing the assignment-expression, recover. 05719 if (NumElements.isInvalid()) { 05720 D.setInvalidType(true); 05721 // If the expression was invalid, skip it. 05722 SkipUntil(tok::r_square, StopAtSemi); 05723 return; 05724 } 05725 05726 T.consumeClose(); 05727 05728 ParsedAttributes attrs(AttrFactory); 05729 MaybeParseCXX11Attributes(attrs); 05730 05731 // Remember that we parsed a array type, and remember its features. 05732 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 05733 StaticLoc.isValid(), isStar, 05734 NumElements.get(), 05735 T.getOpenLocation(), 05736 T.getCloseLocation()), 05737 attrs, T.getCloseLocation()); 05738 } 05739 05740 /// Diagnose brackets before an identifier. 05741 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) { 05742 assert(Tok.is(tok::l_square) && "Missing opening bracket"); 05743 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier"); 05744 05745 SourceLocation StartBracketLoc = Tok.getLocation(); 05746 Declarator TempDeclarator(D.getDeclSpec(), D.getContext()); 05747 05748 while (Tok.is(tok::l_square)) { 05749 ParseBracketDeclarator(TempDeclarator); 05750 } 05751 05752 // Stuff the location of the start of the brackets into the Declarator. 05753 // The diagnostics from ParseDirectDeclarator will make more sense if 05754 // they use this location instead. 05755 if (Tok.is(tok::semi)) 05756 D.getName().EndLocation = StartBracketLoc; 05757 05758 SourceLocation SuggestParenLoc = Tok.getLocation(); 05759 05760 // Now that the brackets are removed, try parsing the declarator again. 05761 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 05762 05763 // Something went wrong parsing the brackets, in which case, 05764 // ParseBracketDeclarator has emitted an error, and we don't need to emit 05765 // one here. 05766 if (TempDeclarator.getNumTypeObjects() == 0) 05767 return; 05768 05769 // Determine if parens will need to be suggested in the diagnostic. 05770 bool NeedParens = false; 05771 if (D.getNumTypeObjects() != 0) { 05772 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) { 05773 case DeclaratorChunk::Pointer: 05774 case DeclaratorChunk::Reference: 05775 case DeclaratorChunk::BlockPointer: 05776 case DeclaratorChunk::MemberPointer: 05777 NeedParens = true; 05778 break; 05779 case DeclaratorChunk::Array: 05780 case DeclaratorChunk::Function: 05781 case DeclaratorChunk::Paren: 05782 break; 05783 } 05784 } 05785 05786 if (NeedParens) { 05787 // Create a DeclaratorChunk for the inserted parens. 05788 ParsedAttributes attrs(AttrFactory); 05789 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 05790 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs, 05791 SourceLocation()); 05792 } 05793 05794 // Adding back the bracket info to the end of the Declarator. 05795 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) { 05796 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i); 05797 ParsedAttributes attrs(AttrFactory); 05798 attrs.set(Chunk.Common.AttrList); 05799 D.AddTypeInfo(Chunk, attrs, SourceLocation()); 05800 } 05801 05802 // The missing identifier would have been diagnosed in ParseDirectDeclarator. 05803 // If parentheses are required, always suggest them. 05804 if (!D.getIdentifier() && !NeedParens) 05805 return; 05806 05807 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd(); 05808 05809 // Generate the move bracket error message. 05810 SourceRange BracketRange(StartBracketLoc, EndBracketLoc); 05811 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); 05812 05813 if (NeedParens) { 05814 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 05815 << getLangOpts().CPlusPlus 05816 << FixItHint::CreateInsertion(SuggestParenLoc, "(") 05817 << FixItHint::CreateInsertion(EndLoc, ")") 05818 << FixItHint::CreateInsertionFromRange( 05819 EndLoc, CharSourceRange(BracketRange, true)) 05820 << FixItHint::CreateRemoval(BracketRange); 05821 } else { 05822 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) 05823 << getLangOpts().CPlusPlus 05824 << FixItHint::CreateInsertionFromRange( 05825 EndLoc, CharSourceRange(BracketRange, true)) 05826 << FixItHint::CreateRemoval(BracketRange); 05827 } 05828 } 05829 05830 /// [GNU] typeof-specifier: 05831 /// typeof ( expressions ) 05832 /// typeof ( type-name ) 05833 /// [GNU/C++] typeof unary-expression 05834 /// 05835 void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 05836 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 05837 Token OpTok = Tok; 05838 SourceLocation StartLoc = ConsumeToken(); 05839 05840 const bool hasParens = Tok.is(tok::l_paren); 05841 05842 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 05843 Sema::ReuseLambdaContextDecl); 05844 05845 bool isCastExpr; 05846 ParsedType CastTy; 05847 SourceRange CastRange; 05848 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, 05849 CastTy, CastRange); 05850 if (hasParens) 05851 DS.setTypeofParensRange(CastRange); 05852 05853 if (CastRange.getEnd().isInvalid()) 05854 // FIXME: Not accurate, the range gets one token more than it should. 05855 DS.SetRangeEnd(Tok.getLocation()); 05856 else 05857 DS.SetRangeEnd(CastRange.getEnd()); 05858 05859 if (isCastExpr) { 05860 if (!CastTy) { 05861 DS.SetTypeSpecError(); 05862 return; 05863 } 05864 05865 const char *PrevSpec = nullptr; 05866 unsigned DiagID; 05867 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 05868 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 05869 DiagID, CastTy, 05870 Actions.getASTContext().getPrintingPolicy())) 05871 Diag(StartLoc, DiagID) << PrevSpec; 05872 return; 05873 } 05874 05875 // If we get here, the operand to the typeof was an expresion. 05876 if (Operand.isInvalid()) { 05877 DS.SetTypeSpecError(); 05878 return; 05879 } 05880 05881 // We might need to transform the operand if it is potentially evaluated. 05882 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 05883 if (Operand.isInvalid()) { 05884 DS.SetTypeSpecError(); 05885 return; 05886 } 05887 05888 const char *PrevSpec = nullptr; 05889 unsigned DiagID; 05890 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 05891 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 05892 DiagID, Operand.get(), 05893 Actions.getASTContext().getPrintingPolicy())) 05894 Diag(StartLoc, DiagID) << PrevSpec; 05895 } 05896 05897 /// [C11] atomic-specifier: 05898 /// _Atomic ( type-name ) 05899 /// 05900 void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 05901 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) && 05902 "Not an atomic specifier"); 05903 05904 SourceLocation StartLoc = ConsumeToken(); 05905 BalancedDelimiterTracker T(*this, tok::l_paren); 05906 if (T.consumeOpen()) 05907 return; 05908 05909 TypeResult Result = ParseTypeName(); 05910 if (Result.isInvalid()) { 05911 SkipUntil(tok::r_paren, StopAtSemi); 05912 return; 05913 } 05914 05915 // Match the ')' 05916 T.consumeClose(); 05917 05918 if (T.getCloseLocation().isInvalid()) 05919 return; 05920 05921 DS.setTypeofParensRange(T.getRange()); 05922 DS.SetRangeEnd(T.getCloseLocation()); 05923 05924 const char *PrevSpec = nullptr; 05925 unsigned DiagID; 05926 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 05927 DiagID, Result.get(), 05928 Actions.getASTContext().getPrintingPolicy())) 05929 Diag(StartLoc, DiagID) << PrevSpec; 05930 } 05931 05932 05933 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 05934 /// from TryAltiVecVectorToken. 05935 bool Parser::TryAltiVecVectorTokenOutOfLine() { 05936 Token Next = NextToken(); 05937 switch (Next.getKind()) { 05938 default: return false; 05939 case tok::kw_short: 05940 case tok::kw_long: 05941 case tok::kw_signed: 05942 case tok::kw_unsigned: 05943 case tok::kw_void: 05944 case tok::kw_char: 05945 case tok::kw_int: 05946 case tok::kw_float: 05947 case tok::kw_double: 05948 case tok::kw_bool: 05949 case tok::kw___pixel: 05950 Tok.setKind(tok::kw___vector); 05951 return true; 05952 case tok::identifier: 05953 if (Next.getIdentifierInfo() == Ident_pixel) { 05954 Tok.setKind(tok::kw___vector); 05955 return true; 05956 } 05957 if (Next.getIdentifierInfo() == Ident_bool) { 05958 Tok.setKind(tok::kw___vector); 05959 return true; 05960 } 05961 return false; 05962 } 05963 } 05964 05965 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 05966 const char *&PrevSpec, unsigned &DiagID, 05967 bool &isInvalid) { 05968 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 05969 if (Tok.getIdentifierInfo() == Ident_vector) { 05970 Token Next = NextToken(); 05971 switch (Next.getKind()) { 05972 case tok::kw_short: 05973 case tok::kw_long: 05974 case tok::kw_signed: 05975 case tok::kw_unsigned: 05976 case tok::kw_void: 05977 case tok::kw_char: 05978 case tok::kw_int: 05979 case tok::kw_float: 05980 case tok::kw_double: 05981 case tok::kw_bool: 05982 case tok::kw___pixel: 05983 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); 05984 return true; 05985 case tok::identifier: 05986 if (Next.getIdentifierInfo() == Ident_pixel) { 05987 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 05988 return true; 05989 } 05990 if (Next.getIdentifierInfo() == Ident_bool) { 05991 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); 05992 return true; 05993 } 05994 break; 05995 default: 05996 break; 05997 } 05998 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 05999 DS.isTypeAltiVecVector()) { 06000 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); 06001 return true; 06002 } else if ((Tok.getIdentifierInfo() == Ident_bool) && 06003 DS.isTypeAltiVecVector()) { 06004 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); 06005 return true; 06006 } 06007 return false; 06008 }