1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Objective-C portions of the Parser interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Parse/Parser.h" 15 #include "RAIIObjectsForParser.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/Basic/CharInfo.h" 18 #include "clang/Parse/ParseDiagnostic.h" 19 #include "clang/Sema/DeclSpec.h" 20 #include "clang/Sema/PrettyDeclStackTrace.h" 21 #include "clang/Sema/Scope.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringExtras.h" 24 25 using namespace clang; 26 27 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic. 28 void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) { 29 ParsedAttributes attrs(AttrFactory); 30 if (Tok.is(tok::kw___attribute)) { 31 if (Kind == tok::objc_interface || Kind == tok::objc_protocol) 32 Diag(Tok, diag::err_objc_postfix_attribute_hint) 33 << (Kind == tok::objc_protocol); 34 else 35 Diag(Tok, diag::err_objc_postfix_attribute); 36 ParseGNUAttributes(attrs); 37 } 38 } 39 40 /// ParseObjCAtDirectives - Handle parts of the external-declaration production: 41 /// external-declaration: [C99 6.9] 42 /// [OBJC] objc-class-definition 43 /// [OBJC] objc-class-declaration 44 /// [OBJC] objc-alias-declaration 45 /// [OBJC] objc-protocol-definition 46 /// [OBJC] objc-method-definition 47 /// [OBJC] '@' 'end' 48 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() { 49 SourceLocation AtLoc = ConsumeToken(); // the "@" 50 51 if (Tok.is(tok::code_completion)) { 52 Actions.CodeCompleteObjCAtDirective(getCurScope()); 53 cutOffParsing(); 54 return nullptr; 55 } 56 57 Decl *SingleDecl = nullptr; 58 switch (Tok.getObjCKeywordID()) { 59 case tok::objc_class: 60 return ParseObjCAtClassDeclaration(AtLoc); 61 case tok::objc_interface: { 62 ParsedAttributes attrs(AttrFactory); 63 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs); 64 break; 65 } 66 case tok::objc_protocol: { 67 ParsedAttributes attrs(AttrFactory); 68 return ParseObjCAtProtocolDeclaration(AtLoc, attrs); 69 } 70 case tok::objc_implementation: 71 return ParseObjCAtImplementationDeclaration(AtLoc); 72 case tok::objc_end: 73 return ParseObjCAtEndDeclaration(AtLoc); 74 case tok::objc_compatibility_alias: 75 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc); 76 break; 77 case tok::objc_synthesize: 78 SingleDecl = ParseObjCPropertySynthesize(AtLoc); 79 break; 80 case tok::objc_dynamic: 81 SingleDecl = ParseObjCPropertyDynamic(AtLoc); 82 break; 83 case tok::objc_import: 84 if (getLangOpts().Modules || getLangOpts().DebuggerSupport) 85 return ParseModuleImport(AtLoc); 86 Diag(AtLoc, diag::err_atimport); 87 SkipUntil(tok::semi); 88 return Actions.ConvertDeclToDeclGroup(nullptr); 89 default: 90 Diag(AtLoc, diag::err_unexpected_at); 91 SkipUntil(tok::semi); 92 SingleDecl = nullptr; 93 break; 94 } 95 return Actions.ConvertDeclToDeclGroup(SingleDecl); 96 } 97 98 /// Class to handle popping type parameters when leaving the scope. 99 class Parser::ObjCTypeParamListScope { 100 Sema &Actions; 101 Scope *S; 102 ObjCTypeParamList *Params; 103 104 public: 105 ObjCTypeParamListScope(Sema &Actions, Scope *S) 106 : Actions(Actions), S(S), Params(nullptr) {} 107 108 ~ObjCTypeParamListScope() { 109 leave(); 110 } 111 112 void enter(ObjCTypeParamList *P) { 113 assert(!Params); 114 Params = P; 115 } 116 117 void leave() { 118 if (Params) 119 Actions.popObjCTypeParamList(S, Params); 120 Params = nullptr; 121 } 122 }; 123 124 /// 125 /// objc-class-declaration: 126 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';' 127 /// 128 /// objc-class-forward-decl: 129 /// identifier objc-type-parameter-list[opt] 130 /// 131 Parser::DeclGroupPtrTy 132 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { 133 ConsumeToken(); // the identifier "class" 134 SmallVector<IdentifierInfo *, 8> ClassNames; 135 SmallVector<SourceLocation, 8> ClassLocs; 136 SmallVector<ObjCTypeParamList *, 8> ClassTypeParams; 137 138 while (1) { 139 MaybeSkipAttributes(tok::objc_class); 140 if (Tok.isNot(tok::identifier)) { 141 Diag(Tok, diag::err_expected) << tok::identifier; 142 SkipUntil(tok::semi); 143 return Actions.ConvertDeclToDeclGroup(nullptr); 144 } 145 ClassNames.push_back(Tok.getIdentifierInfo()); 146 ClassLocs.push_back(Tok.getLocation()); 147 ConsumeToken(); 148 149 // Parse the optional objc-type-parameter-list. 150 ObjCTypeParamList *TypeParams = nullptr; 151 if (Tok.is(tok::less)) 152 TypeParams = parseObjCTypeParamList(); 153 ClassTypeParams.push_back(TypeParams); 154 if (!TryConsumeToken(tok::comma)) 155 break; 156 } 157 158 // Consume the ';'. 159 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class")) 160 return Actions.ConvertDeclToDeclGroup(nullptr); 161 162 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(), 163 ClassLocs.data(), 164 ClassTypeParams, 165 ClassNames.size()); 166 } 167 168 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc) 169 { 170 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind(); 171 if (ock == Sema::OCK_None) 172 return; 173 174 Decl *Decl = Actions.getObjCDeclContext(); 175 if (CurParsedObjCImpl) { 176 CurParsedObjCImpl->finish(AtLoc); 177 } else { 178 Actions.ActOnAtEnd(getCurScope(), AtLoc); 179 } 180 Diag(AtLoc, diag::err_objc_missing_end) 181 << FixItHint::CreateInsertion(AtLoc, "@end\n"); 182 if (Decl) 183 Diag(Decl->getLocStart(), diag::note_objc_container_start) 184 << (int) ock; 185 } 186 187 /// 188 /// objc-interface: 189 /// objc-class-interface-attributes[opt] objc-class-interface 190 /// objc-category-interface 191 /// 192 /// objc-class-interface: 193 /// '@' 'interface' identifier objc-type-parameter-list[opt] 194 /// objc-superclass[opt] objc-protocol-refs[opt] 195 /// objc-class-instance-variables[opt] 196 /// objc-interface-decl-list 197 /// @end 198 /// 199 /// objc-category-interface: 200 /// '@' 'interface' identifier objc-type-parameter-list[opt] 201 /// '(' identifier[opt] ')' objc-protocol-refs[opt] 202 /// objc-interface-decl-list 203 /// @end 204 /// 205 /// objc-superclass: 206 /// ':' identifier objc-type-arguments[opt] 207 /// 208 /// objc-class-interface-attributes: 209 /// __attribute__((visibility("default"))) 210 /// __attribute__((visibility("hidden"))) 211 /// __attribute__((deprecated)) 212 /// __attribute__((unavailable)) 213 /// __attribute__((objc_exception)) - used by NSException on 64-bit 214 /// __attribute__((objc_root_class)) 215 /// 216 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, 217 ParsedAttributes &attrs) { 218 assert(Tok.isObjCAtKeyword(tok::objc_interface) && 219 "ParseObjCAtInterfaceDeclaration(): Expected @interface"); 220 CheckNestedObjCContexts(AtLoc); 221 ConsumeToken(); // the "interface" identifier 222 223 // Code completion after '@interface'. 224 if (Tok.is(tok::code_completion)) { 225 Actions.CodeCompleteObjCInterfaceDecl(getCurScope()); 226 cutOffParsing(); 227 return nullptr; 228 } 229 230 MaybeSkipAttributes(tok::objc_interface); 231 232 if (Tok.isNot(tok::identifier)) { 233 Diag(Tok, diag::err_expected) 234 << tok::identifier; // missing class or category name. 235 return nullptr; 236 } 237 238 // We have a class or category name - consume it. 239 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 240 SourceLocation nameLoc = ConsumeToken(); 241 242 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter 243 // case, LAngleLoc will be valid and ProtocolIdents will capture the 244 // protocol references (that have not yet been resolved). 245 SourceLocation LAngleLoc, EndProtoLoc; 246 SmallVector<IdentifierLocPair, 8> ProtocolIdents; 247 ObjCTypeParamList *typeParameterList = nullptr; 248 ObjCTypeParamListScope typeParamScope(Actions, getCurScope()); 249 if (Tok.is(tok::less)) 250 typeParameterList = parseObjCTypeParamListOrProtocolRefs( 251 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc); 252 253 if (Tok.is(tok::l_paren) && 254 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. 255 256 BalancedDelimiterTracker T(*this, tok::l_paren); 257 T.consumeOpen(); 258 259 SourceLocation categoryLoc; 260 IdentifierInfo *categoryId = nullptr; 261 if (Tok.is(tok::code_completion)) { 262 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc); 263 cutOffParsing(); 264 return nullptr; 265 } 266 267 // For ObjC2, the category name is optional (not an error). 268 if (Tok.is(tok::identifier)) { 269 categoryId = Tok.getIdentifierInfo(); 270 categoryLoc = ConsumeToken(); 271 } 272 else if (!getLangOpts().ObjC2) { 273 Diag(Tok, diag::err_expected) 274 << tok::identifier; // missing category name. 275 return nullptr; 276 } 277 278 T.consumeClose(); 279 if (T.getCloseLocation().isInvalid()) 280 return nullptr; 281 282 if (!attrs.empty()) { // categories don't support attributes. 283 Diag(nameLoc, diag::err_objc_no_attributes_on_category); 284 attrs.clear(); 285 } 286 287 // Next, we need to check for any protocol references. 288 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols"); 289 SmallVector<Decl *, 8> ProtocolRefs; 290 SmallVector<SourceLocation, 8> ProtocolLocs; 291 if (Tok.is(tok::less) && 292 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true, 293 LAngleLoc, EndProtoLoc, 294 /*consumeLastToken=*/true)) 295 return nullptr; 296 297 Decl *CategoryType = 298 Actions.ActOnStartCategoryInterface(AtLoc, 299 nameId, nameLoc, 300 typeParameterList, 301 categoryId, categoryLoc, 302 ProtocolRefs.data(), 303 ProtocolRefs.size(), 304 ProtocolLocs.data(), 305 EndProtoLoc); 306 307 if (Tok.is(tok::l_brace)) 308 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc); 309 310 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType); 311 312 return CategoryType; 313 } 314 // Parse a class interface. 315 IdentifierInfo *superClassId = nullptr; 316 SourceLocation superClassLoc; 317 SourceLocation typeArgsLAngleLoc; 318 SmallVector<ParsedType, 4> typeArgs; 319 SourceLocation typeArgsRAngleLoc; 320 SmallVector<Decl *, 4> protocols; 321 SmallVector<SourceLocation, 4> protocolLocs; 322 if (Tok.is(tok::colon)) { // a super class is specified. 323 ConsumeToken(); 324 325 // Code completion of superclass names. 326 if (Tok.is(tok::code_completion)) { 327 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc); 328 cutOffParsing(); 329 return nullptr; 330 } 331 332 if (Tok.isNot(tok::identifier)) { 333 Diag(Tok, diag::err_expected) 334 << tok::identifier; // missing super class name. 335 return nullptr; 336 } 337 superClassId = Tok.getIdentifierInfo(); 338 superClassLoc = ConsumeToken(); 339 340 // Type arguments for the superclass or protocol conformances. 341 if (Tok.is(tok::less)) { 342 parseObjCTypeArgsOrProtocolQualifiers( 343 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc, 344 protocols, protocolLocs, EndProtoLoc, 345 /*consumeLastToken=*/true, 346 /*warnOnIncompleteProtocols=*/true); 347 if (Tok.is(tok::eof)) 348 return nullptr; 349 } 350 } 351 352 // Next, we need to check for any protocol references. 353 if (LAngleLoc.isValid()) { 354 if (!ProtocolIdents.empty()) { 355 // We already parsed the protocols named when we thought we had a 356 // type parameter list. Translate them into actual protocol references. 357 for (const auto &pair : ProtocolIdents) { 358 protocolLocs.push_back(pair.second); 359 } 360 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true, 361 /*ForObjCContainer=*/true, 362 ProtocolIdents, protocols); 363 } 364 } else if (protocols.empty() && Tok.is(tok::less) && 365 ParseObjCProtocolReferences(protocols, protocolLocs, true, true, 366 LAngleLoc, EndProtoLoc, 367 /*consumeLastToken=*/true)) { 368 return nullptr; 369 } 370 371 if (Tok.isNot(tok::less)) 372 Actions.ActOnTypedefedProtocols(protocols, protocolLocs, 373 superClassId, superClassLoc); 374 375 Decl *ClsType = 376 Actions.ActOnStartClassInterface(getCurScope(), AtLoc, nameId, nameLoc, 377 typeParameterList, superClassId, 378 superClassLoc, 379 typeArgs, 380 SourceRange(typeArgsLAngleLoc, 381 typeArgsRAngleLoc), 382 protocols.data(), protocols.size(), 383 protocolLocs.data(), 384 EndProtoLoc, attrs.getList()); 385 386 if (Tok.is(tok::l_brace)) 387 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc); 388 389 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType); 390 391 return ClsType; 392 } 393 394 /// Add an attribute for a context-sensitive type nullability to the given 395 /// declarator. 396 static void addContextSensitiveTypeNullability(Parser &P, 397 Declarator &D, 398 NullabilityKind nullability, 399 SourceLocation nullabilityLoc, 400 bool &addedToDeclSpec) { 401 // Create the attribute. 402 auto getNullabilityAttr = [&]() -> AttributeList * { 403 return D.getAttributePool().create( 404 P.getNullabilityKeyword(nullability), 405 SourceRange(nullabilityLoc), 406 nullptr, SourceLocation(), 407 nullptr, 0, 408 AttributeList::AS_ContextSensitiveKeyword); 409 }; 410 411 if (D.getNumTypeObjects() > 0) { 412 // Add the attribute to the declarator chunk nearest the declarator. 413 auto nullabilityAttr = getNullabilityAttr(); 414 DeclaratorChunk &chunk = D.getTypeObject(0); 415 nullabilityAttr->setNext(chunk.getAttrListRef()); 416 chunk.getAttrListRef() = nullabilityAttr; 417 } else if (!addedToDeclSpec) { 418 // Otherwise, just put it on the declaration specifiers (if one 419 // isn't there already). 420 D.getMutableDeclSpec().addAttributes(getNullabilityAttr()); 421 addedToDeclSpec = true; 422 } 423 } 424 425 /// Parse an Objective-C type parameter list, if present, or capture 426 /// the locations of the protocol identifiers for a list of protocol 427 /// references. 428 /// 429 /// objc-type-parameter-list: 430 /// '<' objc-type-parameter (',' objc-type-parameter)* '>' 431 /// 432 /// objc-type-parameter: 433 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt] 434 /// 435 /// objc-type-parameter-bound: 436 /// ':' type-name 437 /// 438 /// objc-type-parameter-variance: 439 /// '__covariant' 440 /// '__contravariant' 441 /// 442 /// \param lAngleLoc The location of the starting '<'. 443 /// 444 /// \param protocolIdents Will capture the list of identifiers, if the 445 /// angle brackets contain a list of protocol references rather than a 446 /// type parameter list. 447 /// 448 /// \param rAngleLoc The location of the ending '>'. 449 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs( 450 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, 451 SmallVectorImpl<IdentifierLocPair> &protocolIdents, 452 SourceLocation &rAngleLoc, bool mayBeProtocolList) { 453 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list"); 454 455 // Within the type parameter list, don't treat '>' as an operator. 456 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); 457 458 // Local function to "flush" the protocol identifiers, turning them into 459 // type parameters. 460 SmallVector<Decl *, 4> typeParams; 461 auto makeProtocolIdentsIntoTypeParameters = [&]() { 462 unsigned index = 0; 463 for (const auto &pair : protocolIdents) { 464 DeclResult typeParam = Actions.actOnObjCTypeParam( 465 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(), 466 index++, pair.first, pair.second, SourceLocation(), nullptr); 467 if (typeParam.isUsable()) 468 typeParams.push_back(typeParam.get()); 469 } 470 471 protocolIdents.clear(); 472 mayBeProtocolList = false; 473 }; 474 475 bool invalid = false; 476 lAngleLoc = ConsumeToken(); 477 478 do { 479 // Parse the variance, if any. 480 SourceLocation varianceLoc; 481 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant; 482 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) { 483 variance = Tok.is(tok::kw___covariant) 484 ? ObjCTypeParamVariance::Covariant 485 : ObjCTypeParamVariance::Contravariant; 486 varianceLoc = ConsumeToken(); 487 488 // Once we've seen a variance specific , we know this is not a 489 // list of protocol references. 490 if (mayBeProtocolList) { 491 // Up until now, we have been queuing up parameters because they 492 // might be protocol references. Turn them into parameters now. 493 makeProtocolIdentsIntoTypeParameters(); 494 } 495 } 496 497 // Parse the identifier. 498 if (!Tok.is(tok::identifier)) { 499 // Code completion. 500 if (Tok.is(tok::code_completion)) { 501 // FIXME: If these aren't protocol references, we'll need different 502 // completions. 503 Actions.CodeCompleteObjCProtocolReferences(protocolIdents); 504 cutOffParsing(); 505 506 // FIXME: Better recovery here?. 507 return nullptr; 508 } 509 510 Diag(Tok, diag::err_objc_expected_type_parameter); 511 invalid = true; 512 break; 513 } 514 515 IdentifierInfo *paramName = Tok.getIdentifierInfo(); 516 SourceLocation paramLoc = ConsumeToken(); 517 518 // If there is a bound, parse it. 519 SourceLocation colonLoc; 520 TypeResult boundType; 521 if (TryConsumeToken(tok::colon, colonLoc)) { 522 // Once we've seen a bound, we know this is not a list of protocol 523 // references. 524 if (mayBeProtocolList) { 525 // Up until now, we have been queuing up parameters because they 526 // might be protocol references. Turn them into parameters now. 527 makeProtocolIdentsIntoTypeParameters(); 528 } 529 530 // type-name 531 boundType = ParseTypeName(); 532 if (boundType.isInvalid()) 533 invalid = true; 534 } else if (mayBeProtocolList) { 535 // If this could still be a protocol list, just capture the identifier. 536 // We don't want to turn it into a parameter. 537 protocolIdents.push_back(std::make_pair(paramName, paramLoc)); 538 continue; 539 } 540 541 // Create the type parameter. 542 DeclResult typeParam = Actions.actOnObjCTypeParam( 543 getCurScope(), variance, varianceLoc, typeParams.size(), paramName, 544 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr); 545 if (typeParam.isUsable()) 546 typeParams.push_back(typeParam.get()); 547 } while (TryConsumeToken(tok::comma)); 548 549 // Parse the '>'. 550 if (invalid) { 551 SkipUntil(tok::greater, tok::at, StopBeforeMatch); 552 if (Tok.is(tok::greater)) 553 ConsumeToken(); 554 } else if (ParseGreaterThanInTemplateList(rAngleLoc, 555 /*ConsumeLastToken=*/true, 556 /*ObjCGenericList=*/true)) { 557 Diag(lAngleLoc, diag::note_matching) << "'<'"; 558 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus, 559 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace, 560 tok::comma, tok::semi }, 561 StopBeforeMatch); 562 if (Tok.is(tok::greater)) 563 ConsumeToken(); 564 } 565 566 if (mayBeProtocolList) { 567 // A type parameter list must be followed by either a ':' (indicating the 568 // presence of a superclass) or a '(' (indicating that this is a category 569 // or extension). This disambiguates between an objc-type-parameter-list 570 // and a objc-protocol-refs. 571 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) { 572 // Returning null indicates that we don't have a type parameter list. 573 // The results the caller needs to handle the protocol references are 574 // captured in the reference parameters already. 575 return nullptr; 576 } 577 578 // We have a type parameter list that looks like a list of protocol 579 // references. Turn that parameter list into type parameters. 580 makeProtocolIdentsIntoTypeParameters(); 581 } 582 583 // Form the type parameter list and enter its scope. 584 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList( 585 getCurScope(), 586 lAngleLoc, 587 typeParams, 588 rAngleLoc); 589 Scope.enter(list); 590 591 // Clear out the angle locations; they're used by the caller to indicate 592 // whether there are any protocol references. 593 lAngleLoc = SourceLocation(); 594 rAngleLoc = SourceLocation(); 595 return invalid ? nullptr : list; 596 } 597 598 /// Parse an objc-type-parameter-list. 599 ObjCTypeParamList *Parser::parseObjCTypeParamList() { 600 SourceLocation lAngleLoc; 601 SmallVector<IdentifierLocPair, 1> protocolIdents; 602 SourceLocation rAngleLoc; 603 604 ObjCTypeParamListScope Scope(Actions, getCurScope()); 605 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents, 606 rAngleLoc, 607 /*mayBeProtocolList=*/false); 608 } 609 610 /// objc-interface-decl-list: 611 /// empty 612 /// objc-interface-decl-list objc-property-decl [OBJC2] 613 /// objc-interface-decl-list objc-method-requirement [OBJC2] 614 /// objc-interface-decl-list objc-method-proto ';' 615 /// objc-interface-decl-list declaration 616 /// objc-interface-decl-list ';' 617 /// 618 /// objc-method-requirement: [OBJC2] 619 /// @required 620 /// @optional 621 /// 622 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, 623 Decl *CDecl) { 624 SmallVector<Decl *, 32> allMethods; 625 SmallVector<DeclGroupPtrTy, 8> allTUVariables; 626 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; 627 628 SourceRange AtEnd; 629 630 while (1) { 631 // If this is a method prototype, parse it. 632 if (Tok.isOneOf(tok::minus, tok::plus)) { 633 if (Decl *methodPrototype = 634 ParseObjCMethodPrototype(MethodImplKind, false)) 635 allMethods.push_back(methodPrototype); 636 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for 637 // method definitions. 638 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) { 639 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'. 640 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch); 641 if (Tok.is(tok::semi)) 642 ConsumeToken(); 643 } 644 continue; 645 } 646 if (Tok.is(tok::l_paren)) { 647 Diag(Tok, diag::err_expected_minus_or_plus); 648 ParseObjCMethodDecl(Tok.getLocation(), 649 tok::minus, 650 MethodImplKind, false); 651 continue; 652 } 653 // Ignore excess semicolons. 654 if (Tok.is(tok::semi)) { 655 ConsumeToken(); 656 continue; 657 } 658 659 // If we got to the end of the file, exit the loop. 660 if (isEofOrEom()) 661 break; 662 663 // Code completion within an Objective-C interface. 664 if (Tok.is(tok::code_completion)) { 665 Actions.CodeCompleteOrdinaryName(getCurScope(), 666 CurParsedObjCImpl? Sema::PCC_ObjCImplementation 667 : Sema::PCC_ObjCInterface); 668 return cutOffParsing(); 669 } 670 671 // If we don't have an @ directive, parse it as a function definition. 672 if (Tok.isNot(tok::at)) { 673 // The code below does not consume '}'s because it is afraid of eating the 674 // end of a namespace. Because of the way this code is structured, an 675 // erroneous r_brace would cause an infinite loop if not handled here. 676 if (Tok.is(tok::r_brace)) 677 break; 678 ParsedAttributesWithRange attrs(AttrFactory); 679 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs)); 680 continue; 681 } 682 683 // Otherwise, we have an @ directive, eat the @. 684 SourceLocation AtLoc = ConsumeToken(); // the "@" 685 if (Tok.is(tok::code_completion)) { 686 Actions.CodeCompleteObjCAtDirective(getCurScope()); 687 return cutOffParsing(); 688 } 689 690 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID(); 691 692 if (DirectiveKind == tok::objc_end) { // @end -> terminate list 693 AtEnd.setBegin(AtLoc); 694 AtEnd.setEnd(Tok.getLocation()); 695 break; 696 } else if (DirectiveKind == tok::objc_not_keyword) { 697 Diag(Tok, diag::err_objc_unknown_at); 698 SkipUntil(tok::semi); 699 continue; 700 } 701 702 // Eat the identifier. 703 ConsumeToken(); 704 705 switch (DirectiveKind) { 706 default: 707 // FIXME: If someone forgets an @end on a protocol, this loop will 708 // continue to eat up tons of stuff and spew lots of nonsense errors. It 709 // would probably be better to bail out if we saw an @class or @interface 710 // or something like that. 711 Diag(AtLoc, diag::err_objc_illegal_interface_qual); 712 // Skip until we see an '@' or '}' or ';'. 713 SkipUntil(tok::r_brace, tok::at, StopAtSemi); 714 break; 715 716 case tok::objc_implementation: 717 case tok::objc_interface: 718 Diag(AtLoc, diag::err_objc_missing_end) 719 << FixItHint::CreateInsertion(AtLoc, "@end\n"); 720 Diag(CDecl->getLocStart(), diag::note_objc_container_start) 721 << (int) Actions.getObjCContainerKind(); 722 ConsumeToken(); 723 break; 724 725 case tok::objc_required: 726 case tok::objc_optional: 727 // This is only valid on protocols. 728 // FIXME: Should this check for ObjC2 being enabled? 729 if (contextKey != tok::objc_protocol) 730 Diag(AtLoc, diag::err_objc_directive_only_in_protocol); 731 else 732 MethodImplKind = DirectiveKind; 733 break; 734 735 case tok::objc_property: 736 if (!getLangOpts().ObjC2) 737 Diag(AtLoc, diag::err_objc_properties_require_objc2); 738 739 ObjCDeclSpec OCDS; 740 SourceLocation LParenLoc; 741 // Parse property attribute list, if any. 742 if (Tok.is(tok::l_paren)) { 743 LParenLoc = Tok.getLocation(); 744 ParseObjCPropertyAttribute(OCDS); 745 } 746 747 bool addedToDeclSpec = false; 748 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) { 749 if (FD.D.getIdentifier() == nullptr) { 750 Diag(AtLoc, diag::err_objc_property_requires_field_name) 751 << FD.D.getSourceRange(); 752 return; 753 } 754 if (FD.BitfieldSize) { 755 Diag(AtLoc, diag::err_objc_property_bitfield) 756 << FD.D.getSourceRange(); 757 return; 758 } 759 760 // Map a nullability property attribute to a context-sensitive keyword 761 // attribute. 762 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 763 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(), 764 OCDS.getNullabilityLoc(), 765 addedToDeclSpec); 766 767 // Install the property declarator into interfaceDecl. 768 IdentifierInfo *SelName = 769 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier(); 770 771 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName); 772 IdentifierInfo *SetterName = OCDS.getSetterName(); 773 Selector SetterSel; 774 if (SetterName) 775 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName); 776 else 777 SetterSel = SelectorTable::constructSetterSelector( 778 PP.getIdentifierTable(), PP.getSelectorTable(), 779 FD.D.getIdentifier()); 780 Decl *Property = Actions.ActOnProperty( 781 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel, 782 MethodImplKind); 783 784 FD.complete(Property); 785 }; 786 787 // Parse all the comma separated declarators. 788 ParsingDeclSpec DS(*this); 789 ParseStructDeclaration(DS, ObjCPropertyCallback); 790 791 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 792 break; 793 } 794 } 795 796 // We break out of the big loop in two cases: when we see @end or when we see 797 // EOF. In the former case, eat the @end. In the later case, emit an error. 798 if (Tok.is(tok::code_completion)) { 799 Actions.CodeCompleteObjCAtDirective(getCurScope()); 800 return cutOffParsing(); 801 } else if (Tok.isObjCAtKeyword(tok::objc_end)) { 802 ConsumeToken(); // the "end" identifier 803 } else { 804 Diag(Tok, diag::err_objc_missing_end) 805 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n"); 806 Diag(CDecl->getLocStart(), diag::note_objc_container_start) 807 << (int) Actions.getObjCContainerKind(); 808 AtEnd.setBegin(Tok.getLocation()); 809 AtEnd.setEnd(Tok.getLocation()); 810 } 811 812 // Insert collected methods declarations into the @interface object. 813 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit. 814 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables); 815 } 816 817 /// Diagnose redundant or conflicting nullability information. 818 static void diagnoseRedundantPropertyNullability(Parser &P, 819 ObjCDeclSpec &DS, 820 NullabilityKind nullability, 821 SourceLocation nullabilityLoc){ 822 if (DS.getNullability() == nullability) { 823 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate) 824 << DiagNullabilityKind(nullability, true) 825 << SourceRange(DS.getNullabilityLoc()); 826 return; 827 } 828 829 P.Diag(nullabilityLoc, diag::err_nullability_conflicting) 830 << DiagNullabilityKind(nullability, true) 831 << DiagNullabilityKind(DS.getNullability(), true) 832 << SourceRange(DS.getNullabilityLoc()); 833 } 834 835 /// Parse property attribute declarations. 836 /// 837 /// property-attr-decl: '(' property-attrlist ')' 838 /// property-attrlist: 839 /// property-attribute 840 /// property-attrlist ',' property-attribute 841 /// property-attribute: 842 /// getter '=' identifier 843 /// setter '=' identifier ':' 844 /// readonly 845 /// readwrite 846 /// assign 847 /// retain 848 /// copy 849 /// nonatomic 850 /// atomic 851 /// strong 852 /// weak 853 /// unsafe_unretained 854 /// nonnull 855 /// nullable 856 /// null_unspecified 857 /// null_resettable 858 /// class 859 /// 860 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { 861 assert(Tok.getKind() == tok::l_paren); 862 BalancedDelimiterTracker T(*this, tok::l_paren); 863 T.consumeOpen(); 864 865 while (1) { 866 if (Tok.is(tok::code_completion)) { 867 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS); 868 return cutOffParsing(); 869 } 870 const IdentifierInfo *II = Tok.getIdentifierInfo(); 871 872 // If this is not an identifier at all, bail out early. 873 if (!II) { 874 T.consumeClose(); 875 return; 876 } 877 878 SourceLocation AttrName = ConsumeToken(); // consume last attribute name 879 880 if (II->isStr("readonly")) 881 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly); 882 else if (II->isStr("assign")) 883 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign); 884 else if (II->isStr("unsafe_unretained")) 885 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained); 886 else if (II->isStr("readwrite")) 887 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite); 888 else if (II->isStr("retain")) 889 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain); 890 else if (II->isStr("strong")) 891 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong); 892 else if (II->isStr("copy")) 893 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy); 894 else if (II->isStr("nonatomic")) 895 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic); 896 else if (II->isStr("atomic")) 897 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic); 898 else if (II->isStr("weak")) 899 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak); 900 else if (II->isStr("getter") || II->isStr("setter")) { 901 bool IsSetter = II->getNameStart()[0] == 's'; 902 903 // getter/setter require extra treatment. 904 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter : 905 diag::err_objc_expected_equal_for_getter; 906 907 if (ExpectAndConsume(tok::equal, DiagID)) { 908 SkipUntil(tok::r_paren, StopAtSemi); 909 return; 910 } 911 912 if (Tok.is(tok::code_completion)) { 913 if (IsSetter) 914 Actions.CodeCompleteObjCPropertySetter(getCurScope()); 915 else 916 Actions.CodeCompleteObjCPropertyGetter(getCurScope()); 917 return cutOffParsing(); 918 } 919 920 SourceLocation SelLoc; 921 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc); 922 923 if (!SelIdent) { 924 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter) 925 << IsSetter; 926 SkipUntil(tok::r_paren, StopAtSemi); 927 return; 928 } 929 930 if (IsSetter) { 931 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter); 932 DS.setSetterName(SelIdent); 933 934 if (ExpectAndConsume(tok::colon, 935 diag::err_expected_colon_after_setter_name)) { 936 SkipUntil(tok::r_paren, StopAtSemi); 937 return; 938 } 939 } else { 940 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter); 941 DS.setGetterName(SelIdent); 942 } 943 } else if (II->isStr("nonnull")) { 944 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 945 diagnoseRedundantPropertyNullability(*this, DS, 946 NullabilityKind::NonNull, 947 Tok.getLocation()); 948 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 949 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull); 950 } else if (II->isStr("nullable")) { 951 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 952 diagnoseRedundantPropertyNullability(*this, DS, 953 NullabilityKind::Nullable, 954 Tok.getLocation()); 955 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 956 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable); 957 } else if (II->isStr("null_unspecified")) { 958 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 959 diagnoseRedundantPropertyNullability(*this, DS, 960 NullabilityKind::Unspecified, 961 Tok.getLocation()); 962 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 963 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified); 964 } else if (II->isStr("null_resettable")) { 965 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 966 diagnoseRedundantPropertyNullability(*this, DS, 967 NullabilityKind::Unspecified, 968 Tok.getLocation()); 969 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 970 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified); 971 972 // Also set the null_resettable bit. 973 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable); 974 } else if (II->isStr("class")) { 975 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class); 976 } else { 977 Diag(AttrName, diag::err_objc_expected_property_attr) << II; 978 SkipUntil(tok::r_paren, StopAtSemi); 979 return; 980 } 981 982 if (Tok.isNot(tok::comma)) 983 break; 984 985 ConsumeToken(); 986 } 987 988 T.consumeClose(); 989 } 990 991 /// objc-method-proto: 992 /// objc-instance-method objc-method-decl objc-method-attributes[opt] 993 /// objc-class-method objc-method-decl objc-method-attributes[opt] 994 /// 995 /// objc-instance-method: '-' 996 /// objc-class-method: '+' 997 /// 998 /// objc-method-attributes: [OBJC2] 999 /// __attribute__((deprecated)) 1000 /// 1001 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind, 1002 bool MethodDefinition) { 1003 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-"); 1004 1005 tok::TokenKind methodType = Tok.getKind(); 1006 SourceLocation mLoc = ConsumeToken(); 1007 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind, 1008 MethodDefinition); 1009 // Since this rule is used for both method declarations and definitions, 1010 // the caller is (optionally) responsible for consuming the ';'. 1011 return MDecl; 1012 } 1013 1014 /// objc-selector: 1015 /// identifier 1016 /// one of 1017 /// enum struct union if else while do for switch case default 1018 /// break continue return goto asm sizeof typeof __alignof 1019 /// unsigned long const short volatile signed restrict _Complex 1020 /// in out inout bycopy byref oneway int char float double void _Bool 1021 /// 1022 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) { 1023 1024 switch (Tok.getKind()) { 1025 default: 1026 return nullptr; 1027 case tok::ampamp: 1028 case tok::ampequal: 1029 case tok::amp: 1030 case tok::pipe: 1031 case tok::tilde: 1032 case tok::exclaim: 1033 case tok::exclaimequal: 1034 case tok::pipepipe: 1035 case tok::pipeequal: 1036 case tok::caret: 1037 case tok::caretequal: { 1038 std::string ThisTok(PP.getSpelling(Tok)); 1039 if (isLetter(ThisTok[0])) { 1040 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok); 1041 Tok.setKind(tok::identifier); 1042 SelectorLoc = ConsumeToken(); 1043 return II; 1044 } 1045 return nullptr; 1046 } 1047 1048 case tok::identifier: 1049 case tok::kw_asm: 1050 case tok::kw_auto: 1051 case tok::kw_bool: 1052 case tok::kw_break: 1053 case tok::kw_case: 1054 case tok::kw_catch: 1055 case tok::kw_char: 1056 case tok::kw_class: 1057 case tok::kw_const: 1058 case tok::kw_const_cast: 1059 case tok::kw_continue: 1060 case tok::kw_default: 1061 case tok::kw_delete: 1062 case tok::kw_do: 1063 case tok::kw_double: 1064 case tok::kw_dynamic_cast: 1065 case tok::kw_else: 1066 case tok::kw_enum: 1067 case tok::kw_explicit: 1068 case tok::kw_export: 1069 case tok::kw_extern: 1070 case tok::kw_false: 1071 case tok::kw_float: 1072 case tok::kw_for: 1073 case tok::kw_friend: 1074 case tok::kw_goto: 1075 case tok::kw_if: 1076 case tok::kw_inline: 1077 case tok::kw_int: 1078 case tok::kw_long: 1079 case tok::kw_mutable: 1080 case tok::kw_namespace: 1081 case tok::kw_new: 1082 case tok::kw_operator: 1083 case tok::kw_private: 1084 case tok::kw_protected: 1085 case tok::kw_public: 1086 case tok::kw_register: 1087 case tok::kw_reinterpret_cast: 1088 case tok::kw_restrict: 1089 case tok::kw_return: 1090 case tok::kw_short: 1091 case tok::kw_signed: 1092 case tok::kw_sizeof: 1093 case tok::kw_static: 1094 case tok::kw_static_cast: 1095 case tok::kw_struct: 1096 case tok::kw_switch: 1097 case tok::kw_template: 1098 case tok::kw_this: 1099 case tok::kw_throw: 1100 case tok::kw_true: 1101 case tok::kw_try: 1102 case tok::kw_typedef: 1103 case tok::kw_typeid: 1104 case tok::kw_typename: 1105 case tok::kw_typeof: 1106 case tok::kw_union: 1107 case tok::kw_unsigned: 1108 case tok::kw_using: 1109 case tok::kw_virtual: 1110 case tok::kw_void: 1111 case tok::kw_volatile: 1112 case tok::kw_wchar_t: 1113 case tok::kw_while: 1114 case tok::kw__Bool: 1115 case tok::kw__Complex: 1116 case tok::kw___alignof: 1117 case tok::kw___auto_type: 1118 IdentifierInfo *II = Tok.getIdentifierInfo(); 1119 SelectorLoc = ConsumeToken(); 1120 return II; 1121 } 1122 } 1123 1124 /// objc-for-collection-in: 'in' 1125 /// 1126 bool Parser::isTokIdentifier_in() const { 1127 // FIXME: May have to do additional look-ahead to only allow for 1128 // valid tokens following an 'in'; such as an identifier, unary operators, 1129 // '[' etc. 1130 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) && 1131 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]); 1132 } 1133 1134 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type 1135 /// qualifier list and builds their bitmask representation in the input 1136 /// argument. 1137 /// 1138 /// objc-type-qualifiers: 1139 /// objc-type-qualifier 1140 /// objc-type-qualifiers objc-type-qualifier 1141 /// 1142 /// objc-type-qualifier: 1143 /// 'in' 1144 /// 'out' 1145 /// 'inout' 1146 /// 'oneway' 1147 /// 'bycopy' 1148 /// 'byref' 1149 /// 'nonnull' 1150 /// 'nullable' 1151 /// 'null_unspecified' 1152 /// 1153 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, 1154 Declarator::TheContext Context) { 1155 assert(Context == Declarator::ObjCParameterContext || 1156 Context == Declarator::ObjCResultContext); 1157 1158 while (1) { 1159 if (Tok.is(tok::code_completion)) { 1160 Actions.CodeCompleteObjCPassingType(getCurScope(), DS, 1161 Context == Declarator::ObjCParameterContext); 1162 return cutOffParsing(); 1163 } 1164 1165 if (Tok.isNot(tok::identifier)) 1166 return; 1167 1168 const IdentifierInfo *II = Tok.getIdentifierInfo(); 1169 for (unsigned i = 0; i != objc_NumQuals; ++i) { 1170 if (II != ObjCTypeQuals[i] || 1171 NextToken().is(tok::less) || 1172 NextToken().is(tok::coloncolon)) 1173 continue; 1174 1175 ObjCDeclSpec::ObjCDeclQualifier Qual; 1176 NullabilityKind Nullability; 1177 switch (i) { 1178 default: llvm_unreachable("Unknown decl qualifier"); 1179 case objc_in: Qual = ObjCDeclSpec::DQ_In; break; 1180 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break; 1181 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break; 1182 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break; 1183 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break; 1184 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break; 1185 1186 case objc_nonnull: 1187 Qual = ObjCDeclSpec::DQ_CSNullability; 1188 Nullability = NullabilityKind::NonNull; 1189 break; 1190 1191 case objc_nullable: 1192 Qual = ObjCDeclSpec::DQ_CSNullability; 1193 Nullability = NullabilityKind::Nullable; 1194 break; 1195 1196 case objc_null_unspecified: 1197 Qual = ObjCDeclSpec::DQ_CSNullability; 1198 Nullability = NullabilityKind::Unspecified; 1199 break; 1200 } 1201 1202 // FIXME: Diagnose redundant specifiers. 1203 DS.setObjCDeclQualifier(Qual); 1204 if (Qual == ObjCDeclSpec::DQ_CSNullability) 1205 DS.setNullability(Tok.getLocation(), Nullability); 1206 1207 ConsumeToken(); 1208 II = nullptr; 1209 break; 1210 } 1211 1212 // If this wasn't a recognized qualifier, bail out. 1213 if (II) return; 1214 } 1215 } 1216 1217 /// Take all the decl attributes out of the given list and add 1218 /// them to the given attribute set. 1219 static void takeDeclAttributes(ParsedAttributes &attrs, 1220 AttributeList *list) { 1221 while (list) { 1222 AttributeList *cur = list; 1223 list = cur->getNext(); 1224 1225 if (!cur->isUsedAsTypeAttr()) { 1226 // Clear out the next pointer. We're really completely 1227 // destroying the internal invariants of the declarator here, 1228 // but it doesn't matter because we're done with it. 1229 cur->setNext(nullptr); 1230 attrs.add(cur); 1231 } 1232 } 1233 } 1234 1235 /// takeDeclAttributes - Take all the decl attributes from the given 1236 /// declarator and add them to the given list. 1237 static void takeDeclAttributes(ParsedAttributes &attrs, 1238 Declarator &D) { 1239 // First, take ownership of all attributes. 1240 attrs.getPool().takeAllFrom(D.getAttributePool()); 1241 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool()); 1242 1243 // Now actually move the attributes over. 1244 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList()); 1245 takeDeclAttributes(attrs, D.getAttributes()); 1246 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 1247 takeDeclAttributes(attrs, 1248 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs())); 1249 } 1250 1251 /// objc-type-name: 1252 /// '(' objc-type-qualifiers[opt] type-name ')' 1253 /// '(' objc-type-qualifiers[opt] ')' 1254 /// 1255 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, 1256 Declarator::TheContext context, 1257 ParsedAttributes *paramAttrs) { 1258 assert(context == Declarator::ObjCParameterContext || 1259 context == Declarator::ObjCResultContext); 1260 assert((paramAttrs != nullptr) == 1261 (context == Declarator::ObjCParameterContext)); 1262 1263 assert(Tok.is(tok::l_paren) && "expected ("); 1264 1265 BalancedDelimiterTracker T(*this, tok::l_paren); 1266 T.consumeOpen(); 1267 1268 SourceLocation TypeStartLoc = Tok.getLocation(); 1269 ObjCDeclContextSwitch ObjCDC(*this); 1270 1271 // Parse type qualifiers, in, inout, etc. 1272 ParseObjCTypeQualifierList(DS, context); 1273 1274 ParsedType Ty; 1275 if (isTypeSpecifierQualifier() || isObjCInstancetype()) { 1276 // Parse an abstract declarator. 1277 DeclSpec declSpec(AttrFactory); 1278 declSpec.setObjCQualifiers(&DS); 1279 DeclSpecContext dsContext = DSC_normal; 1280 if (context == Declarator::ObjCResultContext) 1281 dsContext = DSC_objc_method_result; 1282 ParseSpecifierQualifierList(declSpec, AS_none, dsContext); 1283 Declarator declarator(declSpec, context); 1284 ParseDeclarator(declarator); 1285 1286 // If that's not invalid, extract a type. 1287 if (!declarator.isInvalidType()) { 1288 // Map a nullability specifier to a context-sensitive keyword attribute. 1289 bool addedToDeclSpec = false; 1290 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) 1291 addContextSensitiveTypeNullability(*this, declarator, 1292 DS.getNullability(), 1293 DS.getNullabilityLoc(), 1294 addedToDeclSpec); 1295 1296 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator); 1297 if (!type.isInvalid()) 1298 Ty = type.get(); 1299 1300 // If we're parsing a parameter, steal all the decl attributes 1301 // and add them to the decl spec. 1302 if (context == Declarator::ObjCParameterContext) 1303 takeDeclAttributes(*paramAttrs, declarator); 1304 } 1305 } 1306 1307 if (Tok.is(tok::r_paren)) 1308 T.consumeClose(); 1309 else if (Tok.getLocation() == TypeStartLoc) { 1310 // If we didn't eat any tokens, then this isn't a type. 1311 Diag(Tok, diag::err_expected_type); 1312 SkipUntil(tok::r_paren, StopAtSemi); 1313 } else { 1314 // Otherwise, we found *something*, but didn't get a ')' in the right 1315 // place. Emit an error then return what we have as the type. 1316 T.consumeClose(); 1317 } 1318 return Ty; 1319 } 1320 1321 /// objc-method-decl: 1322 /// objc-selector 1323 /// objc-keyword-selector objc-parmlist[opt] 1324 /// objc-type-name objc-selector 1325 /// objc-type-name objc-keyword-selector objc-parmlist[opt] 1326 /// 1327 /// objc-keyword-selector: 1328 /// objc-keyword-decl 1329 /// objc-keyword-selector objc-keyword-decl 1330 /// 1331 /// objc-keyword-decl: 1332 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier 1333 /// objc-selector ':' objc-keyword-attributes[opt] identifier 1334 /// ':' objc-type-name objc-keyword-attributes[opt] identifier 1335 /// ':' objc-keyword-attributes[opt] identifier 1336 /// 1337 /// objc-parmlist: 1338 /// objc-parms objc-ellipsis[opt] 1339 /// 1340 /// objc-parms: 1341 /// objc-parms , parameter-declaration 1342 /// 1343 /// objc-ellipsis: 1344 /// , ... 1345 /// 1346 /// objc-keyword-attributes: [OBJC2] 1347 /// __attribute__((unused)) 1348 /// 1349 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, 1350 tok::TokenKind mType, 1351 tok::ObjCKeywordKind MethodImplKind, 1352 bool MethodDefinition) { 1353 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 1354 1355 if (Tok.is(tok::code_completion)) { 1356 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 1357 /*ReturnType=*/nullptr); 1358 cutOffParsing(); 1359 return nullptr; 1360 } 1361 1362 // Parse the return type if present. 1363 ParsedType ReturnType; 1364 ObjCDeclSpec DSRet; 1365 if (Tok.is(tok::l_paren)) 1366 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 1367 nullptr); 1368 1369 // If attributes exist before the method, parse them. 1370 ParsedAttributes methodAttrs(AttrFactory); 1371 if (getLangOpts().ObjC2) 1372 MaybeParseGNUAttributes(methodAttrs); 1373 1374 if (Tok.is(tok::code_completion)) { 1375 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 1376 ReturnType); 1377 cutOffParsing(); 1378 return nullptr; 1379 } 1380 1381 // Now parse the selector. 1382 SourceLocation selLoc; 1383 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc); 1384 1385 // An unnamed colon is valid. 1386 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name. 1387 Diag(Tok, diag::err_expected_selector_for_method) 1388 << SourceRange(mLoc, Tok.getLocation()); 1389 // Skip until we get a ; or @. 1390 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch); 1391 return nullptr; 1392 } 1393 1394 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo; 1395 if (Tok.isNot(tok::colon)) { 1396 // If attributes exist after the method, parse them. 1397 if (getLangOpts().ObjC2) 1398 MaybeParseGNUAttributes(methodAttrs); 1399 1400 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent); 1401 Decl *Result 1402 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), 1403 mType, DSRet, ReturnType, 1404 selLoc, Sel, nullptr, 1405 CParamInfo.data(), CParamInfo.size(), 1406 methodAttrs.getList(), MethodImplKind, 1407 false, MethodDefinition); 1408 PD.complete(Result); 1409 return Result; 1410 } 1411 1412 SmallVector<IdentifierInfo *, 12> KeyIdents; 1413 SmallVector<SourceLocation, 12> KeyLocs; 1414 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos; 1415 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 1416 Scope::FunctionDeclarationScope | Scope::DeclScope); 1417 1418 AttributePool allParamAttrs(AttrFactory); 1419 while (1) { 1420 ParsedAttributes paramAttrs(AttrFactory); 1421 Sema::ObjCArgInfo ArgInfo; 1422 1423 // Each iteration parses a single keyword argument. 1424 if (ExpectAndConsume(tok::colon)) 1425 break; 1426 1427 ArgInfo.Type = nullptr; 1428 if (Tok.is(tok::l_paren)) // Parse the argument type if present. 1429 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, 1430 Declarator::ObjCParameterContext, 1431 ¶mAttrs); 1432 1433 // If attributes exist before the argument name, parse them. 1434 // Regardless, collect all the attributes we've parsed so far. 1435 ArgInfo.ArgAttrs = nullptr; 1436 if (getLangOpts().ObjC2) { 1437 MaybeParseGNUAttributes(paramAttrs); 1438 ArgInfo.ArgAttrs = paramAttrs.getList(); 1439 } 1440 1441 // Code completion for the next piece of the selector. 1442 if (Tok.is(tok::code_completion)) { 1443 KeyIdents.push_back(SelIdent); 1444 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1445 mType == tok::minus, 1446 /*AtParameterName=*/true, 1447 ReturnType, KeyIdents); 1448 cutOffParsing(); 1449 return nullptr; 1450 } 1451 1452 if (Tok.isNot(tok::identifier)) { 1453 Diag(Tok, diag::err_expected) 1454 << tok::identifier; // missing argument name. 1455 break; 1456 } 1457 1458 ArgInfo.Name = Tok.getIdentifierInfo(); 1459 ArgInfo.NameLoc = Tok.getLocation(); 1460 ConsumeToken(); // Eat the identifier. 1461 1462 ArgInfos.push_back(ArgInfo); 1463 KeyIdents.push_back(SelIdent); 1464 KeyLocs.push_back(selLoc); 1465 1466 // Make sure the attributes persist. 1467 allParamAttrs.takeAllFrom(paramAttrs.getPool()); 1468 1469 // Code completion for the next piece of the selector. 1470 if (Tok.is(tok::code_completion)) { 1471 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1472 mType == tok::minus, 1473 /*AtParameterName=*/false, 1474 ReturnType, KeyIdents); 1475 cutOffParsing(); 1476 return nullptr; 1477 } 1478 1479 // Check for another keyword selector. 1480 SelIdent = ParseObjCSelectorPiece(selLoc); 1481 if (!SelIdent && Tok.isNot(tok::colon)) 1482 break; 1483 if (!SelIdent) { 1484 SourceLocation ColonLoc = Tok.getLocation(); 1485 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) { 1486 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name; 1487 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name; 1488 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name; 1489 } 1490 } 1491 // We have a selector or a colon, continue parsing. 1492 } 1493 1494 bool isVariadic = false; 1495 bool cStyleParamWarned = false; 1496 // Parse the (optional) parameter list. 1497 while (Tok.is(tok::comma)) { 1498 ConsumeToken(); 1499 if (Tok.is(tok::ellipsis)) { 1500 isVariadic = true; 1501 ConsumeToken(); 1502 break; 1503 } 1504 if (!cStyleParamWarned) { 1505 Diag(Tok, diag::warn_cstyle_param); 1506 cStyleParamWarned = true; 1507 } 1508 DeclSpec DS(AttrFactory); 1509 ParseDeclarationSpecifiers(DS); 1510 // Parse the declarator. 1511 Declarator ParmDecl(DS, Declarator::PrototypeContext); 1512 ParseDeclarator(ParmDecl); 1513 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 1514 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 1515 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 1516 ParmDecl.getIdentifierLoc(), 1517 Param, 1518 nullptr)); 1519 } 1520 1521 // FIXME: Add support for optional parameter list... 1522 // If attributes exist after the method, parse them. 1523 if (getLangOpts().ObjC2) 1524 MaybeParseGNUAttributes(methodAttrs); 1525 1526 if (KeyIdents.size() == 0) 1527 return nullptr; 1528 1529 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(), 1530 &KeyIdents[0]); 1531 Decl *Result 1532 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), 1533 mType, DSRet, ReturnType, 1534 KeyLocs, Sel, &ArgInfos[0], 1535 CParamInfo.data(), CParamInfo.size(), 1536 methodAttrs.getList(), 1537 MethodImplKind, isVariadic, MethodDefinition); 1538 1539 PD.complete(Result); 1540 return Result; 1541 } 1542 1543 /// objc-protocol-refs: 1544 /// '<' identifier-list '>' 1545 /// 1546 bool Parser:: 1547 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols, 1548 SmallVectorImpl<SourceLocation> &ProtocolLocs, 1549 bool WarnOnDeclarations, bool ForObjCContainer, 1550 SourceLocation &LAngleLoc, SourceLocation &EndLoc, 1551 bool consumeLastToken) { 1552 assert(Tok.is(tok::less) && "expected <"); 1553 1554 LAngleLoc = ConsumeToken(); // the "<" 1555 1556 SmallVector<IdentifierLocPair, 8> ProtocolIdents; 1557 1558 while (1) { 1559 if (Tok.is(tok::code_completion)) { 1560 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents); 1561 cutOffParsing(); 1562 return true; 1563 } 1564 1565 if (Tok.isNot(tok::identifier)) { 1566 Diag(Tok, diag::err_expected) << tok::identifier; 1567 SkipUntil(tok::greater, StopAtSemi); 1568 return true; 1569 } 1570 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(), 1571 Tok.getLocation())); 1572 ProtocolLocs.push_back(Tok.getLocation()); 1573 ConsumeToken(); 1574 1575 if (!TryConsumeToken(tok::comma)) 1576 break; 1577 } 1578 1579 // Consume the '>'. 1580 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken, 1581 /*ObjCGenericList=*/false)) 1582 return true; 1583 1584 // Convert the list of protocols identifiers into a list of protocol decls. 1585 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer, 1586 ProtocolIdents, Protocols); 1587 return false; 1588 } 1589 1590 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) { 1591 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'"); 1592 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C"); 1593 1594 SourceLocation lAngleLoc; 1595 SmallVector<Decl *, 8> protocols; 1596 SmallVector<SourceLocation, 8> protocolLocs; 1597 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false, 1598 lAngleLoc, rAngleLoc, 1599 /*consumeLastToken=*/true); 1600 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc, 1601 protocols, 1602 protocolLocs, 1603 rAngleLoc); 1604 if (result.isUsable()) { 1605 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id) 1606 << FixItHint::CreateInsertion(lAngleLoc, "id") 1607 << SourceRange(lAngleLoc, rAngleLoc); 1608 } 1609 1610 return result; 1611 } 1612 1613 /// Parse Objective-C type arguments or protocol qualifiers. 1614 /// 1615 /// objc-type-arguments: 1616 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>' 1617 /// 1618 void Parser::parseObjCTypeArgsOrProtocolQualifiers( 1619 ParsedType baseType, 1620 SourceLocation &typeArgsLAngleLoc, 1621 SmallVectorImpl<ParsedType> &typeArgs, 1622 SourceLocation &typeArgsRAngleLoc, 1623 SourceLocation &protocolLAngleLoc, 1624 SmallVectorImpl<Decl *> &protocols, 1625 SmallVectorImpl<SourceLocation> &protocolLocs, 1626 SourceLocation &protocolRAngleLoc, 1627 bool consumeLastToken, 1628 bool warnOnIncompleteProtocols) { 1629 assert(Tok.is(tok::less) && "Not at the start of type args or protocols"); 1630 SourceLocation lAngleLoc = ConsumeToken(); 1631 1632 // Whether all of the elements we've parsed thus far are single 1633 // identifiers, which might be types or might be protocols. 1634 bool allSingleIdentifiers = true; 1635 SmallVector<IdentifierInfo *, 4> identifiers; 1636 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs; 1637 1638 // Parse a list of comma-separated identifiers, bailing out if we 1639 // see something different. 1640 do { 1641 // Parse a single identifier. 1642 if (Tok.is(tok::identifier) && 1643 (NextToken().is(tok::comma) || 1644 NextToken().is(tok::greater) || 1645 NextToken().is(tok::greatergreater))) { 1646 identifiers.push_back(Tok.getIdentifierInfo()); 1647 identifierLocs.push_back(ConsumeToken()); 1648 continue; 1649 } 1650 1651 if (Tok.is(tok::code_completion)) { 1652 // FIXME: Also include types here. 1653 SmallVector<IdentifierLocPair, 4> identifierLocPairs; 1654 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1655 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i], 1656 identifierLocs[i])); 1657 } 1658 1659 QualType BaseT = Actions.GetTypeFromParser(baseType); 1660 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) { 1661 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); 1662 } else { 1663 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs); 1664 } 1665 cutOffParsing(); 1666 return; 1667 } 1668 1669 allSingleIdentifiers = false; 1670 break; 1671 } while (TryConsumeToken(tok::comma)); 1672 1673 // If we parsed an identifier list, semantic analysis sorts out 1674 // whether it refers to protocols or to type arguments. 1675 if (allSingleIdentifiers) { 1676 // Parse the closing '>'. 1677 SourceLocation rAngleLoc; 1678 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken, 1679 /*ObjCGenericList=*/true); 1680 1681 // Let Sema figure out what we parsed. 1682 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(), 1683 baseType, 1684 lAngleLoc, 1685 identifiers, 1686 identifierLocs, 1687 rAngleLoc, 1688 typeArgsLAngleLoc, 1689 typeArgs, 1690 typeArgsRAngleLoc, 1691 protocolLAngleLoc, 1692 protocols, 1693 protocolRAngleLoc, 1694 warnOnIncompleteProtocols); 1695 return; 1696 } 1697 1698 // We parsed an identifier list but stumbled into non single identifiers, this 1699 // means we might (a) check that what we already parsed is a legitimate type 1700 // (not a protocol or unknown type) and (b) parse the remaining ones, which 1701 // must all be type args. 1702 1703 // Convert the identifiers into type arguments. 1704 bool invalid = false; 1705 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr; 1706 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc; 1707 SmallVector<IdentifierInfo *, 2> unknownTypeArgs; 1708 SmallVector<SourceLocation, 2> unknownTypeArgsLoc; 1709 1710 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1711 ParsedType typeArg 1712 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope()); 1713 if (typeArg) { 1714 DeclSpec DS(AttrFactory); 1715 const char *prevSpec = nullptr; 1716 unsigned diagID; 1717 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID, 1718 typeArg, Actions.getASTContext().getPrintingPolicy()); 1719 1720 // Form a declarator to turn this into a type. 1721 Declarator D(DS, Declarator::TypeNameContext); 1722 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D); 1723 if (fullTypeArg.isUsable()) { 1724 typeArgs.push_back(fullTypeArg.get()); 1725 if (!foundValidTypeId) { 1726 foundValidTypeId = identifiers[i]; 1727 foundValidTypeSrcLoc = identifierLocs[i]; 1728 } 1729 } else { 1730 invalid = true; 1731 unknownTypeArgs.push_back(identifiers[i]); 1732 unknownTypeArgsLoc.push_back(identifierLocs[i]); 1733 } 1734 } else { 1735 invalid = true; 1736 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) { 1737 unknownTypeArgs.push_back(identifiers[i]); 1738 unknownTypeArgsLoc.push_back(identifierLocs[i]); 1739 } else if (!foundProtocolId) { 1740 foundProtocolId = identifiers[i]; 1741 foundProtocolSrcLoc = identifierLocs[i]; 1742 } 1743 } 1744 } 1745 1746 // Continue parsing type-names. 1747 do { 1748 Token CurTypeTok = Tok; 1749 TypeResult typeArg = ParseTypeName(); 1750 1751 // Consume the '...' for a pack expansion. 1752 SourceLocation ellipsisLoc; 1753 TryConsumeToken(tok::ellipsis, ellipsisLoc); 1754 if (typeArg.isUsable() && ellipsisLoc.isValid()) { 1755 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc); 1756 } 1757 1758 if (typeArg.isUsable()) { 1759 typeArgs.push_back(typeArg.get()); 1760 if (!foundValidTypeId) { 1761 foundValidTypeId = CurTypeTok.getIdentifierInfo(); 1762 foundValidTypeSrcLoc = CurTypeTok.getLocation(); 1763 } 1764 } else { 1765 invalid = true; 1766 } 1767 } while (TryConsumeToken(tok::comma)); 1768 1769 // Diagnose the mix between type args and protocols. 1770 if (foundProtocolId && foundValidTypeId) 1771 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc, 1772 foundValidTypeId, 1773 foundValidTypeSrcLoc); 1774 1775 // Diagnose unknown arg types. 1776 ParsedType T; 1777 if (unknownTypeArgs.size()) 1778 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i) 1779 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i], 1780 getCurScope(), nullptr, T); 1781 1782 // Parse the closing '>'. 1783 SourceLocation rAngleLoc; 1784 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken, 1785 /*ObjCGenericList=*/true); 1786 1787 if (invalid) { 1788 typeArgs.clear(); 1789 return; 1790 } 1791 1792 // Record left/right angle locations. 1793 typeArgsLAngleLoc = lAngleLoc; 1794 typeArgsRAngleLoc = rAngleLoc; 1795 } 1796 1797 void Parser::parseObjCTypeArgsAndProtocolQualifiers( 1798 ParsedType baseType, 1799 SourceLocation &typeArgsLAngleLoc, 1800 SmallVectorImpl<ParsedType> &typeArgs, 1801 SourceLocation &typeArgsRAngleLoc, 1802 SourceLocation &protocolLAngleLoc, 1803 SmallVectorImpl<Decl *> &protocols, 1804 SmallVectorImpl<SourceLocation> &protocolLocs, 1805 SourceLocation &protocolRAngleLoc, 1806 bool consumeLastToken) { 1807 assert(Tok.is(tok::less)); 1808 1809 // Parse the first angle-bracket-delimited clause. 1810 parseObjCTypeArgsOrProtocolQualifiers(baseType, 1811 typeArgsLAngleLoc, 1812 typeArgs, 1813 typeArgsRAngleLoc, 1814 protocolLAngleLoc, 1815 protocols, 1816 protocolLocs, 1817 protocolRAngleLoc, 1818 consumeLastToken, 1819 /*warnOnIncompleteProtocols=*/false); 1820 if (Tok.is(tok::eof)) // Nothing else to do here... 1821 return; 1822 1823 // An Objective-C object pointer followed by type arguments 1824 // can then be followed again by a set of protocol references, e.g., 1825 // \c NSArray<NSView><NSTextDelegate> 1826 if ((consumeLastToken && Tok.is(tok::less)) || 1827 (!consumeLastToken && NextToken().is(tok::less))) { 1828 // If we aren't consuming the last token, the prior '>' is still hanging 1829 // there. Consume it before we parse the protocol qualifiers. 1830 if (!consumeLastToken) 1831 ConsumeToken(); 1832 1833 if (!protocols.empty()) { 1834 SkipUntilFlags skipFlags = SkipUntilFlags(); 1835 if (!consumeLastToken) 1836 skipFlags = skipFlags | StopBeforeMatch; 1837 Diag(Tok, diag::err_objc_type_args_after_protocols) 1838 << SourceRange(protocolLAngleLoc, protocolRAngleLoc); 1839 SkipUntil(tok::greater, tok::greatergreater, skipFlags); 1840 } else { 1841 ParseObjCProtocolReferences(protocols, protocolLocs, 1842 /*WarnOnDeclarations=*/false, 1843 /*ForObjCContainer=*/false, 1844 protocolLAngleLoc, protocolRAngleLoc, 1845 consumeLastToken); 1846 } 1847 } 1848 } 1849 1850 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers( 1851 SourceLocation loc, 1852 ParsedType type, 1853 bool consumeLastToken, 1854 SourceLocation &endLoc) { 1855 assert(Tok.is(tok::less)); 1856 SourceLocation typeArgsLAngleLoc; 1857 SmallVector<ParsedType, 4> typeArgs; 1858 SourceLocation typeArgsRAngleLoc; 1859 SourceLocation protocolLAngleLoc; 1860 SmallVector<Decl *, 4> protocols; 1861 SmallVector<SourceLocation, 4> protocolLocs; 1862 SourceLocation protocolRAngleLoc; 1863 1864 // Parse type arguments and protocol qualifiers. 1865 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs, 1866 typeArgsRAngleLoc, protocolLAngleLoc, 1867 protocols, protocolLocs, 1868 protocolRAngleLoc, consumeLastToken); 1869 1870 if (Tok.is(tok::eof)) 1871 return true; // Invalid type result. 1872 1873 // Compute the location of the last token. 1874 if (consumeLastToken) 1875 endLoc = PrevTokLocation; 1876 else 1877 endLoc = Tok.getLocation(); 1878 1879 return Actions.actOnObjCTypeArgsAndProtocolQualifiers( 1880 getCurScope(), 1881 loc, 1882 type, 1883 typeArgsLAngleLoc, 1884 typeArgs, 1885 typeArgsRAngleLoc, 1886 protocolLAngleLoc, 1887 protocols, 1888 protocolLocs, 1889 protocolRAngleLoc); 1890 } 1891 1892 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, 1893 BalancedDelimiterTracker &T, 1894 SmallVectorImpl<Decl *> &AllIvarDecls, 1895 bool RBraceMissing) { 1896 if (!RBraceMissing) 1897 T.consumeClose(); 1898 1899 Actions.ActOnObjCContainerStartDefinition(interfaceDecl); 1900 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls); 1901 Actions.ActOnObjCContainerFinishDefinition(); 1902 // Call ActOnFields() even if we don't have any decls. This is useful 1903 // for code rewriting tools that need to be aware of the empty list. 1904 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, 1905 AllIvarDecls, 1906 T.getOpenLocation(), T.getCloseLocation(), nullptr); 1907 } 1908 1909 /// objc-class-instance-variables: 1910 /// '{' objc-instance-variable-decl-list[opt] '}' 1911 /// 1912 /// objc-instance-variable-decl-list: 1913 /// objc-visibility-spec 1914 /// objc-instance-variable-decl ';' 1915 /// ';' 1916 /// objc-instance-variable-decl-list objc-visibility-spec 1917 /// objc-instance-variable-decl-list objc-instance-variable-decl ';' 1918 /// objc-instance-variable-decl-list ';' 1919 /// 1920 /// objc-visibility-spec: 1921 /// @private 1922 /// @protected 1923 /// @public 1924 /// @package [OBJC2] 1925 /// 1926 /// objc-instance-variable-decl: 1927 /// struct-declaration 1928 /// 1929 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, 1930 tok::ObjCKeywordKind visibility, 1931 SourceLocation atLoc) { 1932 assert(Tok.is(tok::l_brace) && "expected {"); 1933 SmallVector<Decl *, 32> AllIvarDecls; 1934 1935 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); 1936 ObjCDeclContextSwitch ObjCDC(*this); 1937 1938 BalancedDelimiterTracker T(*this, tok::l_brace); 1939 T.consumeOpen(); 1940 // While we still have something to read, read the instance variables. 1941 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 1942 // Each iteration of this loop reads one objc-instance-variable-decl. 1943 1944 // Check for extraneous top-level semicolon. 1945 if (Tok.is(tok::semi)) { 1946 ConsumeExtraSemi(InstanceVariableList); 1947 continue; 1948 } 1949 1950 // Set the default visibility to private. 1951 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec 1952 if (Tok.is(tok::code_completion)) { 1953 Actions.CodeCompleteObjCAtVisibility(getCurScope()); 1954 return cutOffParsing(); 1955 } 1956 1957 switch (Tok.getObjCKeywordID()) { 1958 case tok::objc_private: 1959 case tok::objc_public: 1960 case tok::objc_protected: 1961 case tok::objc_package: 1962 visibility = Tok.getObjCKeywordID(); 1963 ConsumeToken(); 1964 continue; 1965 1966 case tok::objc_end: 1967 Diag(Tok, diag::err_objc_unexpected_atend); 1968 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1)); 1969 Tok.setKind(tok::at); 1970 Tok.setLength(1); 1971 PP.EnterToken(Tok); 1972 HelperActionsForIvarDeclarations(interfaceDecl, atLoc, 1973 T, AllIvarDecls, true); 1974 return; 1975 1976 default: 1977 Diag(Tok, diag::err_objc_illegal_visibility_spec); 1978 continue; 1979 } 1980 } 1981 1982 if (Tok.is(tok::code_completion)) { 1983 Actions.CodeCompleteOrdinaryName(getCurScope(), 1984 Sema::PCC_ObjCInstanceVariableList); 1985 return cutOffParsing(); 1986 } 1987 1988 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) { 1989 Actions.ActOnObjCContainerStartDefinition(interfaceDecl); 1990 // Install the declarator into the interface decl. 1991 FD.D.setObjCIvar(true); 1992 Decl *Field = Actions.ActOnIvar( 1993 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D, 1994 FD.BitfieldSize, visibility); 1995 Actions.ActOnObjCContainerFinishDefinition(); 1996 if (Field) 1997 AllIvarDecls.push_back(Field); 1998 FD.complete(Field); 1999 }; 2000 2001 // Parse all the comma separated declarators. 2002 ParsingDeclSpec DS(*this); 2003 ParseStructDeclaration(DS, ObjCIvarCallback); 2004 2005 if (Tok.is(tok::semi)) { 2006 ConsumeToken(); 2007 } else { 2008 Diag(Tok, diag::err_expected_semi_decl_list); 2009 // Skip to end of block or statement 2010 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 2011 } 2012 } 2013 HelperActionsForIvarDeclarations(interfaceDecl, atLoc, 2014 T, AllIvarDecls, false); 2015 } 2016 2017 /// objc-protocol-declaration: 2018 /// objc-protocol-definition 2019 /// objc-protocol-forward-reference 2020 /// 2021 /// objc-protocol-definition: 2022 /// \@protocol identifier 2023 /// objc-protocol-refs[opt] 2024 /// objc-interface-decl-list 2025 /// \@end 2026 /// 2027 /// objc-protocol-forward-reference: 2028 /// \@protocol identifier-list ';' 2029 /// 2030 /// "\@protocol identifier ;" should be resolved as "\@protocol 2031 /// identifier-list ;": objc-interface-decl-list may not start with a 2032 /// semicolon in the first alternative if objc-protocol-refs are omitted. 2033 Parser::DeclGroupPtrTy 2034 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, 2035 ParsedAttributes &attrs) { 2036 assert(Tok.isObjCAtKeyword(tok::objc_protocol) && 2037 "ParseObjCAtProtocolDeclaration(): Expected @protocol"); 2038 ConsumeToken(); // the "protocol" identifier 2039 2040 if (Tok.is(tok::code_completion)) { 2041 Actions.CodeCompleteObjCProtocolDecl(getCurScope()); 2042 cutOffParsing(); 2043 return nullptr; 2044 } 2045 2046 MaybeSkipAttributes(tok::objc_protocol); 2047 2048 if (Tok.isNot(tok::identifier)) { 2049 Diag(Tok, diag::err_expected) << tok::identifier; // missing protocol name. 2050 return nullptr; 2051 } 2052 // Save the protocol name, then consume it. 2053 IdentifierInfo *protocolName = Tok.getIdentifierInfo(); 2054 SourceLocation nameLoc = ConsumeToken(); 2055 2056 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol. 2057 IdentifierLocPair ProtoInfo(protocolName, nameLoc); 2058 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo, 2059 attrs.getList()); 2060 } 2061 2062 CheckNestedObjCContexts(AtLoc); 2063 2064 if (Tok.is(tok::comma)) { // list of forward declarations. 2065 SmallVector<IdentifierLocPair, 8> ProtocolRefs; 2066 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc)); 2067 2068 // Parse the list of forward declarations. 2069 while (1) { 2070 ConsumeToken(); // the ',' 2071 if (Tok.isNot(tok::identifier)) { 2072 Diag(Tok, diag::err_expected) << tok::identifier; 2073 SkipUntil(tok::semi); 2074 return nullptr; 2075 } 2076 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(), 2077 Tok.getLocation())); 2078 ConsumeToken(); // the identifier 2079 2080 if (Tok.isNot(tok::comma)) 2081 break; 2082 } 2083 // Consume the ';'. 2084 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol")) 2085 return nullptr; 2086 2087 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs, 2088 attrs.getList()); 2089 } 2090 2091 // Last, and definitely not least, parse a protocol declaration. 2092 SourceLocation LAngleLoc, EndProtoLoc; 2093 2094 SmallVector<Decl *, 8> ProtocolRefs; 2095 SmallVector<SourceLocation, 8> ProtocolLocs; 2096 if (Tok.is(tok::less) && 2097 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true, 2098 LAngleLoc, EndProtoLoc, 2099 /*consumeLastToken=*/true)) 2100 return nullptr; 2101 2102 Decl *ProtoType = 2103 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc, 2104 ProtocolRefs.data(), 2105 ProtocolRefs.size(), 2106 ProtocolLocs.data(), 2107 EndProtoLoc, attrs.getList()); 2108 2109 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType); 2110 return Actions.ConvertDeclToDeclGroup(ProtoType); 2111 } 2112 2113 /// objc-implementation: 2114 /// objc-class-implementation-prologue 2115 /// objc-category-implementation-prologue 2116 /// 2117 /// objc-class-implementation-prologue: 2118 /// @implementation identifier objc-superclass[opt] 2119 /// objc-class-instance-variables[opt] 2120 /// 2121 /// objc-category-implementation-prologue: 2122 /// @implementation identifier ( identifier ) 2123 Parser::DeclGroupPtrTy 2124 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { 2125 assert(Tok.isObjCAtKeyword(tok::objc_implementation) && 2126 "ParseObjCAtImplementationDeclaration(): Expected @implementation"); 2127 CheckNestedObjCContexts(AtLoc); 2128 ConsumeToken(); // the "implementation" identifier 2129 2130 // Code completion after '@implementation'. 2131 if (Tok.is(tok::code_completion)) { 2132 Actions.CodeCompleteObjCImplementationDecl(getCurScope()); 2133 cutOffParsing(); 2134 return nullptr; 2135 } 2136 2137 MaybeSkipAttributes(tok::objc_implementation); 2138 2139 if (Tok.isNot(tok::identifier)) { 2140 Diag(Tok, diag::err_expected) 2141 << tok::identifier; // missing class or category name. 2142 return nullptr; 2143 } 2144 // We have a class or category name - consume it. 2145 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 2146 SourceLocation nameLoc = ConsumeToken(); // consume class or category name 2147 Decl *ObjCImpDecl = nullptr; 2148 2149 // Neither a type parameter list nor a list of protocol references is 2150 // permitted here. Parse and diagnose them. 2151 if (Tok.is(tok::less)) { 2152 SourceLocation lAngleLoc, rAngleLoc; 2153 SmallVector<IdentifierLocPair, 8> protocolIdents; 2154 SourceLocation diagLoc = Tok.getLocation(); 2155 ObjCTypeParamListScope typeParamScope(Actions, getCurScope()); 2156 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc, 2157 protocolIdents, rAngleLoc)) { 2158 Diag(diagLoc, diag::err_objc_parameterized_implementation) 2159 << SourceRange(diagLoc, PrevTokLocation); 2160 } else if (lAngleLoc.isValid()) { 2161 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier) 2162 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc)); 2163 } 2164 } 2165 2166 if (Tok.is(tok::l_paren)) { 2167 // we have a category implementation. 2168 ConsumeParen(); 2169 SourceLocation categoryLoc, rparenLoc; 2170 IdentifierInfo *categoryId = nullptr; 2171 2172 if (Tok.is(tok::code_completion)) { 2173 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc); 2174 cutOffParsing(); 2175 return nullptr; 2176 } 2177 2178 if (Tok.is(tok::identifier)) { 2179 categoryId = Tok.getIdentifierInfo(); 2180 categoryLoc = ConsumeToken(); 2181 } else { 2182 Diag(Tok, diag::err_expected) 2183 << tok::identifier; // missing category name. 2184 return nullptr; 2185 } 2186 if (Tok.isNot(tok::r_paren)) { 2187 Diag(Tok, diag::err_expected) << tok::r_paren; 2188 SkipUntil(tok::r_paren); // don't stop at ';' 2189 return nullptr; 2190 } 2191 rparenLoc = ConsumeParen(); 2192 if (Tok.is(tok::less)) { // we have illegal '<' try to recover 2193 Diag(Tok, diag::err_unexpected_protocol_qualifier); 2194 SourceLocation protocolLAngleLoc, protocolRAngleLoc; 2195 SmallVector<Decl *, 4> protocols; 2196 SmallVector<SourceLocation, 4> protocolLocs; 2197 (void)ParseObjCProtocolReferences(protocols, protocolLocs, 2198 /*warnOnIncompleteProtocols=*/false, 2199 /*ForObjCContainer=*/false, 2200 protocolLAngleLoc, protocolRAngleLoc, 2201 /*consumeLastToken=*/true); 2202 } 2203 ObjCImpDecl = Actions.ActOnStartCategoryImplementation( 2204 AtLoc, nameId, nameLoc, categoryId, 2205 categoryLoc); 2206 2207 } else { 2208 // We have a class implementation 2209 SourceLocation superClassLoc; 2210 IdentifierInfo *superClassId = nullptr; 2211 if (TryConsumeToken(tok::colon)) { 2212 // We have a super class 2213 if (Tok.isNot(tok::identifier)) { 2214 Diag(Tok, diag::err_expected) 2215 << tok::identifier; // missing super class name. 2216 return nullptr; 2217 } 2218 superClassId = Tok.getIdentifierInfo(); 2219 superClassLoc = ConsumeToken(); // Consume super class name 2220 } 2221 ObjCImpDecl = Actions.ActOnStartClassImplementation( 2222 AtLoc, nameId, nameLoc, 2223 superClassId, superClassLoc); 2224 2225 if (Tok.is(tok::l_brace)) // we have ivars 2226 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc); 2227 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover 2228 Diag(Tok, diag::err_unexpected_protocol_qualifier); 2229 2230 SourceLocation protocolLAngleLoc, protocolRAngleLoc; 2231 SmallVector<Decl *, 4> protocols; 2232 SmallVector<SourceLocation, 4> protocolLocs; 2233 (void)ParseObjCProtocolReferences(protocols, protocolLocs, 2234 /*warnOnIncompleteProtocols=*/false, 2235 /*ForObjCContainer=*/false, 2236 protocolLAngleLoc, protocolRAngleLoc, 2237 /*consumeLastToken=*/true); 2238 } 2239 } 2240 assert(ObjCImpDecl); 2241 2242 SmallVector<Decl *, 8> DeclsInGroup; 2243 2244 { 2245 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl); 2246 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) { 2247 ParsedAttributesWithRange attrs(AttrFactory); 2248 MaybeParseCXX11Attributes(attrs); 2249 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) { 2250 DeclGroupRef DG = DGP.get(); 2251 DeclsInGroup.append(DG.begin(), DG.end()); 2252 } 2253 } 2254 } 2255 2256 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup); 2257 } 2258 2259 Parser::DeclGroupPtrTy 2260 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) { 2261 assert(Tok.isObjCAtKeyword(tok::objc_end) && 2262 "ParseObjCAtEndDeclaration(): Expected @end"); 2263 ConsumeToken(); // the "end" identifier 2264 if (CurParsedObjCImpl) 2265 CurParsedObjCImpl->finish(atEnd); 2266 else 2267 // missing @implementation 2268 Diag(atEnd.getBegin(), diag::err_expected_objc_container); 2269 return nullptr; 2270 } 2271 2272 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() { 2273 if (!Finished) { 2274 finish(P.Tok.getLocation()); 2275 if (P.isEofOrEom()) { 2276 P.Diag(P.Tok, diag::err_objc_missing_end) 2277 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n"); 2278 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start) 2279 << Sema::OCK_Implementation; 2280 } 2281 } 2282 P.CurParsedObjCImpl = nullptr; 2283 assert(LateParsedObjCMethods.empty()); 2284 } 2285 2286 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) { 2287 assert(!Finished); 2288 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl); 2289 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 2290 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 2291 true/*Methods*/); 2292 2293 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd); 2294 2295 if (HasCFunction) 2296 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 2297 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 2298 false/*c-functions*/); 2299 2300 /// \brief Clear and free the cached objc methods. 2301 for (LateParsedObjCMethodContainer::iterator 2302 I = LateParsedObjCMethods.begin(), 2303 E = LateParsedObjCMethods.end(); I != E; ++I) 2304 delete *I; 2305 LateParsedObjCMethods.clear(); 2306 2307 Finished = true; 2308 } 2309 2310 /// compatibility-alias-decl: 2311 /// @compatibility_alias alias-name class-name ';' 2312 /// 2313 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) { 2314 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) && 2315 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias"); 2316 ConsumeToken(); // consume compatibility_alias 2317 if (Tok.isNot(tok::identifier)) { 2318 Diag(Tok, diag::err_expected) << tok::identifier; 2319 return nullptr; 2320 } 2321 IdentifierInfo *aliasId = Tok.getIdentifierInfo(); 2322 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name 2323 if (Tok.isNot(tok::identifier)) { 2324 Diag(Tok, diag::err_expected) << tok::identifier; 2325 return nullptr; 2326 } 2327 IdentifierInfo *classId = Tok.getIdentifierInfo(); 2328 SourceLocation classLoc = ConsumeToken(); // consume class-name; 2329 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias"); 2330 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc, 2331 classId, classLoc); 2332 } 2333 2334 /// property-synthesis: 2335 /// @synthesize property-ivar-list ';' 2336 /// 2337 /// property-ivar-list: 2338 /// property-ivar 2339 /// property-ivar-list ',' property-ivar 2340 /// 2341 /// property-ivar: 2342 /// identifier 2343 /// identifier '=' identifier 2344 /// 2345 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { 2346 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) && 2347 "ParseObjCPropertySynthesize(): Expected '@synthesize'"); 2348 ConsumeToken(); // consume synthesize 2349 2350 while (true) { 2351 if (Tok.is(tok::code_completion)) { 2352 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 2353 cutOffParsing(); 2354 return nullptr; 2355 } 2356 2357 if (Tok.isNot(tok::identifier)) { 2358 Diag(Tok, diag::err_synthesized_property_name); 2359 SkipUntil(tok::semi); 2360 return nullptr; 2361 } 2362 2363 IdentifierInfo *propertyIvar = nullptr; 2364 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 2365 SourceLocation propertyLoc = ConsumeToken(); // consume property name 2366 SourceLocation propertyIvarLoc; 2367 if (TryConsumeToken(tok::equal)) { 2368 // property '=' ivar-name 2369 if (Tok.is(tok::code_completion)) { 2370 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId); 2371 cutOffParsing(); 2372 return nullptr; 2373 } 2374 2375 if (Tok.isNot(tok::identifier)) { 2376 Diag(Tok, diag::err_expected) << tok::identifier; 2377 break; 2378 } 2379 propertyIvar = Tok.getIdentifierInfo(); 2380 propertyIvarLoc = ConsumeToken(); // consume ivar-name 2381 } 2382 Actions.ActOnPropertyImplDecl( 2383 getCurScope(), atLoc, propertyLoc, true, 2384 propertyId, propertyIvar, propertyIvarLoc, 2385 ObjCPropertyQueryKind::OBJC_PR_query_unknown); 2386 if (Tok.isNot(tok::comma)) 2387 break; 2388 ConsumeToken(); // consume ',' 2389 } 2390 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize"); 2391 return nullptr; 2392 } 2393 2394 /// property-dynamic: 2395 /// @dynamic property-list 2396 /// 2397 /// property-list: 2398 /// identifier 2399 /// property-list ',' identifier 2400 /// 2401 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { 2402 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) && 2403 "ParseObjCPropertyDynamic(): Expected '@dynamic'"); 2404 ConsumeToken(); // consume dynamic 2405 2406 bool isClassProperty = false; 2407 if (Tok.is(tok::l_paren)) { 2408 ConsumeParen(); 2409 const IdentifierInfo *II = Tok.getIdentifierInfo(); 2410 2411 if (!II) { 2412 Diag(Tok, diag::err_objc_expected_property_attr) << II; 2413 SkipUntil(tok::r_paren, StopAtSemi); 2414 } else { 2415 SourceLocation AttrName = ConsumeToken(); // consume attribute name 2416 if (II->isStr("class")) { 2417 isClassProperty = true; 2418 if (Tok.isNot(tok::r_paren)) { 2419 Diag(Tok, diag::err_expected) << tok::r_paren; 2420 SkipUntil(tok::r_paren, StopAtSemi); 2421 } else 2422 ConsumeParen(); 2423 } else { 2424 Diag(AttrName, diag::err_objc_expected_property_attr) << II; 2425 SkipUntil(tok::r_paren, StopAtSemi); 2426 } 2427 } 2428 } 2429 2430 while (true) { 2431 if (Tok.is(tok::code_completion)) { 2432 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 2433 cutOffParsing(); 2434 return nullptr; 2435 } 2436 2437 if (Tok.isNot(tok::identifier)) { 2438 Diag(Tok, diag::err_expected) << tok::identifier; 2439 SkipUntil(tok::semi); 2440 return nullptr; 2441 } 2442 2443 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 2444 SourceLocation propertyLoc = ConsumeToken(); // consume property name 2445 Actions.ActOnPropertyImplDecl( 2446 getCurScope(), atLoc, propertyLoc, false, 2447 propertyId, nullptr, SourceLocation(), 2448 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class : 2449 ObjCPropertyQueryKind::OBJC_PR_query_unknown); 2450 2451 if (Tok.isNot(tok::comma)) 2452 break; 2453 ConsumeToken(); // consume ',' 2454 } 2455 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic"); 2456 return nullptr; 2457 } 2458 2459 /// objc-throw-statement: 2460 /// throw expression[opt]; 2461 /// 2462 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) { 2463 ExprResult Res; 2464 ConsumeToken(); // consume throw 2465 if (Tok.isNot(tok::semi)) { 2466 Res = ParseExpression(); 2467 if (Res.isInvalid()) { 2468 SkipUntil(tok::semi); 2469 return StmtError(); 2470 } 2471 } 2472 // consume ';' 2473 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw"); 2474 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope()); 2475 } 2476 2477 /// objc-synchronized-statement: 2478 /// @synchronized '(' expression ')' compound-statement 2479 /// 2480 StmtResult 2481 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) { 2482 ConsumeToken(); // consume synchronized 2483 if (Tok.isNot(tok::l_paren)) { 2484 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized"; 2485 return StmtError(); 2486 } 2487 2488 // The operand is surrounded with parentheses. 2489 ConsumeParen(); // '(' 2490 ExprResult operand(ParseExpression()); 2491 2492 if (Tok.is(tok::r_paren)) { 2493 ConsumeParen(); // ')' 2494 } else { 2495 if (!operand.isInvalid()) 2496 Diag(Tok, diag::err_expected) << tok::r_paren; 2497 2498 // Skip forward until we see a left brace, but don't consume it. 2499 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 2500 } 2501 2502 // Require a compound statement. 2503 if (Tok.isNot(tok::l_brace)) { 2504 if (!operand.isInvalid()) 2505 Diag(Tok, diag::err_expected) << tok::l_brace; 2506 return StmtError(); 2507 } 2508 2509 // Check the @synchronized operand now. 2510 if (!operand.isInvalid()) 2511 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get()); 2512 2513 // Parse the compound statement within a new scope. 2514 ParseScope bodyScope(this, Scope::DeclScope); 2515 StmtResult body(ParseCompoundStatementBody()); 2516 bodyScope.Exit(); 2517 2518 // If there was a semantic or parse error earlier with the 2519 // operand, fail now. 2520 if (operand.isInvalid()) 2521 return StmtError(); 2522 2523 if (body.isInvalid()) 2524 body = Actions.ActOnNullStmt(Tok.getLocation()); 2525 2526 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get()); 2527 } 2528 2529 /// objc-try-catch-statement: 2530 /// @try compound-statement objc-catch-list[opt] 2531 /// @try compound-statement objc-catch-list[opt] @finally compound-statement 2532 /// 2533 /// objc-catch-list: 2534 /// @catch ( parameter-declaration ) compound-statement 2535 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement 2536 /// catch-parameter-declaration: 2537 /// parameter-declaration 2538 /// '...' [OBJC2] 2539 /// 2540 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { 2541 bool catch_or_finally_seen = false; 2542 2543 ConsumeToken(); // consume try 2544 if (Tok.isNot(tok::l_brace)) { 2545 Diag(Tok, diag::err_expected) << tok::l_brace; 2546 return StmtError(); 2547 } 2548 StmtVector CatchStmts; 2549 StmtResult FinallyStmt; 2550 ParseScope TryScope(this, Scope::DeclScope); 2551 StmtResult TryBody(ParseCompoundStatementBody()); 2552 TryScope.Exit(); 2553 if (TryBody.isInvalid()) 2554 TryBody = Actions.ActOnNullStmt(Tok.getLocation()); 2555 2556 while (Tok.is(tok::at)) { 2557 // At this point, we need to lookahead to determine if this @ is the start 2558 // of an @catch or @finally. We don't want to consume the @ token if this 2559 // is an @try or @encode or something else. 2560 Token AfterAt = GetLookAheadToken(1); 2561 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) && 2562 !AfterAt.isObjCAtKeyword(tok::objc_finally)) 2563 break; 2564 2565 SourceLocation AtCatchFinallyLoc = ConsumeToken(); 2566 if (Tok.isObjCAtKeyword(tok::objc_catch)) { 2567 Decl *FirstPart = nullptr; 2568 ConsumeToken(); // consume catch 2569 if (Tok.is(tok::l_paren)) { 2570 ConsumeParen(); 2571 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope); 2572 if (Tok.isNot(tok::ellipsis)) { 2573 DeclSpec DS(AttrFactory); 2574 ParseDeclarationSpecifiers(DS); 2575 Declarator ParmDecl(DS, Declarator::ObjCCatchContext); 2576 ParseDeclarator(ParmDecl); 2577 2578 // Inform the actions module about the declarator, so it 2579 // gets added to the current scope. 2580 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl); 2581 } else 2582 ConsumeToken(); // consume '...' 2583 2584 SourceLocation RParenLoc; 2585 2586 if (Tok.is(tok::r_paren)) 2587 RParenLoc = ConsumeParen(); 2588 else // Skip over garbage, until we get to ')'. Eat the ')'. 2589 SkipUntil(tok::r_paren, StopAtSemi); 2590 2591 StmtResult CatchBody(true); 2592 if (Tok.is(tok::l_brace)) 2593 CatchBody = ParseCompoundStatementBody(); 2594 else 2595 Diag(Tok, diag::err_expected) << tok::l_brace; 2596 if (CatchBody.isInvalid()) 2597 CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); 2598 2599 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, 2600 RParenLoc, 2601 FirstPart, 2602 CatchBody.get()); 2603 if (!Catch.isInvalid()) 2604 CatchStmts.push_back(Catch.get()); 2605 2606 } else { 2607 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) 2608 << "@catch clause"; 2609 return StmtError(); 2610 } 2611 catch_or_finally_seen = true; 2612 } else { 2613 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?"); 2614 ConsumeToken(); // consume finally 2615 ParseScope FinallyScope(this, Scope::DeclScope); 2616 2617 StmtResult FinallyBody(true); 2618 if (Tok.is(tok::l_brace)) 2619 FinallyBody = ParseCompoundStatementBody(); 2620 else 2621 Diag(Tok, diag::err_expected) << tok::l_brace; 2622 if (FinallyBody.isInvalid()) 2623 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation()); 2624 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc, 2625 FinallyBody.get()); 2626 catch_or_finally_seen = true; 2627 break; 2628 } 2629 } 2630 if (!catch_or_finally_seen) { 2631 Diag(atLoc, diag::err_missing_catch_finally); 2632 return StmtError(); 2633 } 2634 2635 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), 2636 CatchStmts, 2637 FinallyStmt.get()); 2638 } 2639 2640 /// objc-autoreleasepool-statement: 2641 /// @autoreleasepool compound-statement 2642 /// 2643 StmtResult 2644 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) { 2645 ConsumeToken(); // consume autoreleasepool 2646 if (Tok.isNot(tok::l_brace)) { 2647 Diag(Tok, diag::err_expected) << tok::l_brace; 2648 return StmtError(); 2649 } 2650 // Enter a scope to hold everything within the compound stmt. Compound 2651 // statements can always hold declarations. 2652 ParseScope BodyScope(this, Scope::DeclScope); 2653 2654 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody()); 2655 2656 BodyScope.Exit(); 2657 if (AutoreleasePoolBody.isInvalid()) 2658 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation()); 2659 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, 2660 AutoreleasePoolBody.get()); 2661 } 2662 2663 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them 2664 /// for later parsing. 2665 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) { 2666 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) && 2667 trySkippingFunctionBody()) { 2668 Actions.ActOnSkippedFunctionBody(MDecl); 2669 return; 2670 } 2671 2672 LexedMethod* LM = new LexedMethod(this, MDecl); 2673 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM); 2674 CachedTokens &Toks = LM->Toks; 2675 // Begin by storing the '{' or 'try' or ':' token. 2676 Toks.push_back(Tok); 2677 if (Tok.is(tok::kw_try)) { 2678 ConsumeToken(); 2679 if (Tok.is(tok::colon)) { 2680 Toks.push_back(Tok); 2681 ConsumeToken(); 2682 while (Tok.isNot(tok::l_brace)) { 2683 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); 2684 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 2685 } 2686 } 2687 Toks.push_back(Tok); // also store '{' 2688 } 2689 else if (Tok.is(tok::colon)) { 2690 ConsumeToken(); 2691 // FIXME: This is wrong, due to C++11 braced initialization. 2692 while (Tok.isNot(tok::l_brace)) { 2693 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); 2694 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 2695 } 2696 Toks.push_back(Tok); // also store '{' 2697 } 2698 ConsumeBrace(); 2699 // Consume everything up to (and including) the matching right brace. 2700 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 2701 while (Tok.is(tok::kw_catch)) { 2702 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); 2703 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 2704 } 2705 } 2706 2707 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}' 2708 /// 2709 Decl *Parser::ParseObjCMethodDefinition() { 2710 Decl *MDecl = ParseObjCMethodPrototype(); 2711 2712 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(), 2713 "parsing Objective-C method"); 2714 2715 // parse optional ';' 2716 if (Tok.is(tok::semi)) { 2717 if (CurParsedObjCImpl) { 2718 Diag(Tok, diag::warn_semicolon_before_method_body) 2719 << FixItHint::CreateRemoval(Tok.getLocation()); 2720 } 2721 ConsumeToken(); 2722 } 2723 2724 // We should have an opening brace now. 2725 if (Tok.isNot(tok::l_brace)) { 2726 Diag(Tok, diag::err_expected_method_body); 2727 2728 // Skip over garbage, until we get to '{'. Don't eat the '{'. 2729 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 2730 2731 // If we didn't find the '{', bail out. 2732 if (Tok.isNot(tok::l_brace)) 2733 return nullptr; 2734 } 2735 2736 if (!MDecl) { 2737 ConsumeBrace(); 2738 SkipUntil(tok::r_brace); 2739 return nullptr; 2740 } 2741 2742 // Allow the rest of sema to find private method decl implementations. 2743 Actions.AddAnyMethodToGlobalPool(MDecl); 2744 assert (CurParsedObjCImpl 2745 && "ParseObjCMethodDefinition - Method out of @implementation"); 2746 // Consume the tokens and store them for later parsing. 2747 StashAwayMethodOrFunctionBodyTokens(MDecl); 2748 return MDecl; 2749 } 2750 2751 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { 2752 if (Tok.is(tok::code_completion)) { 2753 Actions.CodeCompleteObjCAtStatement(getCurScope()); 2754 cutOffParsing(); 2755 return StmtError(); 2756 } 2757 2758 if (Tok.isObjCAtKeyword(tok::objc_try)) 2759 return ParseObjCTryStmt(AtLoc); 2760 2761 if (Tok.isObjCAtKeyword(tok::objc_throw)) 2762 return ParseObjCThrowStmt(AtLoc); 2763 2764 if (Tok.isObjCAtKeyword(tok::objc_synchronized)) 2765 return ParseObjCSynchronizedStmt(AtLoc); 2766 2767 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool)) 2768 return ParseObjCAutoreleasePoolStmt(AtLoc); 2769 2770 if (Tok.isObjCAtKeyword(tok::objc_import) && 2771 getLangOpts().DebuggerSupport) { 2772 SkipUntil(tok::semi); 2773 return Actions.ActOnNullStmt(Tok.getLocation()); 2774 } 2775 2776 ExprStatementTokLoc = AtLoc; 2777 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc)); 2778 if (Res.isInvalid()) { 2779 // If the expression is invalid, skip ahead to the next semicolon. Not 2780 // doing this opens us up to the possibility of infinite loops if 2781 // ParseExpression does not consume any tokens. 2782 SkipUntil(tok::semi); 2783 return StmtError(); 2784 } 2785 2786 // Otherwise, eat the semicolon. 2787 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 2788 return Actions.ActOnExprStmt(Res); 2789 } 2790 2791 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { 2792 switch (Tok.getKind()) { 2793 case tok::code_completion: 2794 Actions.CodeCompleteObjCAtExpression(getCurScope()); 2795 cutOffParsing(); 2796 return ExprError(); 2797 2798 case tok::minus: 2799 case tok::plus: { 2800 tok::TokenKind Kind = Tok.getKind(); 2801 SourceLocation OpLoc = ConsumeToken(); 2802 2803 if (!Tok.is(tok::numeric_constant)) { 2804 const char *Symbol = nullptr; 2805 switch (Kind) { 2806 case tok::minus: Symbol = "-"; break; 2807 case tok::plus: Symbol = "+"; break; 2808 default: llvm_unreachable("missing unary operator case"); 2809 } 2810 Diag(Tok, diag::err_nsnumber_nonliteral_unary) 2811 << Symbol; 2812 return ExprError(); 2813 } 2814 2815 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 2816 if (Lit.isInvalid()) { 2817 return Lit; 2818 } 2819 ConsumeToken(); // Consume the literal token. 2820 2821 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get()); 2822 if (Lit.isInvalid()) 2823 return Lit; 2824 2825 return ParsePostfixExpressionSuffix( 2826 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get())); 2827 } 2828 2829 case tok::string_literal: // primary-expression: string-literal 2830 case tok::wide_string_literal: 2831 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc)); 2832 2833 case tok::char_constant: 2834 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc)); 2835 2836 case tok::numeric_constant: 2837 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc)); 2838 2839 case tok::kw_true: // Objective-C++, etc. 2840 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes 2841 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true)); 2842 case tok::kw_false: // Objective-C++, etc. 2843 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no 2844 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false)); 2845 2846 case tok::l_square: 2847 // Objective-C array literal 2848 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc)); 2849 2850 case tok::l_brace: 2851 // Objective-C dictionary literal 2852 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc)); 2853 2854 case tok::l_paren: 2855 // Objective-C boxed expression 2856 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc)); 2857 2858 default: 2859 if (Tok.getIdentifierInfo() == nullptr) 2860 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2861 2862 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) { 2863 case tok::objc_encode: 2864 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc)); 2865 case tok::objc_protocol: 2866 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc)); 2867 case tok::objc_selector: 2868 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc)); 2869 case tok::objc_available: 2870 return ParseAvailabilityCheckExpr(AtLoc); 2871 default: { 2872 const char *str = nullptr; 2873 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure 2874 // that this is a proper statement where such directives could actually 2875 // occur. 2876 if (GetLookAheadToken(1).is(tok::l_brace) && 2877 ExprStatementTokLoc == AtLoc) { 2878 char ch = Tok.getIdentifierInfo()->getNameStart()[0]; 2879 str = 2880 ch == 't' ? "try" 2881 : (ch == 'f' ? "finally" 2882 : (ch == 'a' ? "autoreleasepool" : nullptr)); 2883 } 2884 if (str) { 2885 SourceLocation kwLoc = Tok.getLocation(); 2886 return ExprError(Diag(AtLoc, diag::err_unexpected_at) << 2887 FixItHint::CreateReplacement(kwLoc, str)); 2888 } 2889 else 2890 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2891 } 2892 } 2893 } 2894 } 2895 2896 /// \brief Parse the receiver of an Objective-C++ message send. 2897 /// 2898 /// This routine parses the receiver of a message send in 2899 /// Objective-C++ either as a type or as an expression. Note that this 2900 /// routine must not be called to parse a send to 'super', since it 2901 /// has no way to return such a result. 2902 /// 2903 /// \param IsExpr Whether the receiver was parsed as an expression. 2904 /// 2905 /// \param TypeOrExpr If the receiver was parsed as an expression (\c 2906 /// IsExpr is true), the parsed expression. If the receiver was parsed 2907 /// as a type (\c IsExpr is false), the parsed type. 2908 /// 2909 /// \returns True if an error occurred during parsing or semantic 2910 /// analysis, in which case the arguments do not have valid 2911 /// values. Otherwise, returns false for a successful parse. 2912 /// 2913 /// objc-receiver: [C++] 2914 /// 'super' [not parsed here] 2915 /// expression 2916 /// simple-type-specifier 2917 /// typename-specifier 2918 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { 2919 InMessageExpressionRAIIObject InMessage(*this, true); 2920 2921 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename, 2922 tok::annot_cxxscope)) 2923 TryAnnotateTypeOrScopeToken(); 2924 2925 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) { 2926 // objc-receiver: 2927 // expression 2928 // Make sure any typos in the receiver are corrected or diagnosed, so that 2929 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to 2930 // only the things that are valid ObjC receivers? 2931 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression()); 2932 if (Receiver.isInvalid()) 2933 return true; 2934 2935 IsExpr = true; 2936 TypeOrExpr = Receiver.get(); 2937 return false; 2938 } 2939 2940 // objc-receiver: 2941 // typename-specifier 2942 // simple-type-specifier 2943 // expression (that starts with one of the above) 2944 DeclSpec DS(AttrFactory); 2945 ParseCXXSimpleTypeSpecifier(DS); 2946 2947 if (Tok.is(tok::l_paren)) { 2948 // If we see an opening parentheses at this point, we are 2949 // actually parsing an expression that starts with a 2950 // function-style cast, e.g., 2951 // 2952 // postfix-expression: 2953 // simple-type-specifier ( expression-list [opt] ) 2954 // typename-specifier ( expression-list [opt] ) 2955 // 2956 // Parse the remainder of this case, then the (optional) 2957 // postfix-expression suffix, followed by the (optional) 2958 // right-hand side of the binary expression. We have an 2959 // instance method. 2960 ExprResult Receiver = ParseCXXTypeConstructExpression(DS); 2961 if (!Receiver.isInvalid()) 2962 Receiver = ParsePostfixExpressionSuffix(Receiver.get()); 2963 if (!Receiver.isInvalid()) 2964 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma); 2965 if (Receiver.isInvalid()) 2966 return true; 2967 2968 IsExpr = true; 2969 TypeOrExpr = Receiver.get(); 2970 return false; 2971 } 2972 2973 // We have a class message. Turn the simple-type-specifier or 2974 // typename-specifier we parsed into a type and parse the 2975 // remainder of the class message. 2976 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2977 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2978 if (Type.isInvalid()) 2979 return true; 2980 2981 IsExpr = false; 2982 TypeOrExpr = Type.get().getAsOpaquePtr(); 2983 return false; 2984 } 2985 2986 /// \brief Determine whether the parser is currently referring to a an 2987 /// Objective-C message send, using a simplified heuristic to avoid overhead. 2988 /// 2989 /// This routine will only return true for a subset of valid message-send 2990 /// expressions. 2991 bool Parser::isSimpleObjCMessageExpression() { 2992 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 && 2993 "Incorrect start for isSimpleObjCMessageExpression"); 2994 return GetLookAheadToken(1).is(tok::identifier) && 2995 GetLookAheadToken(2).is(tok::identifier); 2996 } 2997 2998 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { 2999 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || 3000 InMessageExpression) 3001 return false; 3002 3003 ParsedType Type; 3004 3005 if (Tok.is(tok::annot_typename)) 3006 Type = getTypeAnnotation(Tok); 3007 else if (Tok.is(tok::identifier)) 3008 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), 3009 getCurScope()); 3010 else 3011 return false; 3012 3013 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { 3014 const Token &AfterNext = GetLookAheadToken(2); 3015 if (AfterNext.isOneOf(tok::colon, tok::r_square)) { 3016 if (Tok.is(tok::identifier)) 3017 TryAnnotateTypeOrScopeToken(); 3018 3019 return Tok.is(tok::annot_typename); 3020 } 3021 } 3022 3023 return false; 3024 } 3025 3026 /// objc-message-expr: 3027 /// '[' objc-receiver objc-message-args ']' 3028 /// 3029 /// objc-receiver: [C] 3030 /// 'super' 3031 /// expression 3032 /// class-name 3033 /// type-name 3034 /// 3035 ExprResult Parser::ParseObjCMessageExpression() { 3036 assert(Tok.is(tok::l_square) && "'[' expected"); 3037 SourceLocation LBracLoc = ConsumeBracket(); // consume '[' 3038 3039 if (Tok.is(tok::code_completion)) { 3040 Actions.CodeCompleteObjCMessageReceiver(getCurScope()); 3041 cutOffParsing(); 3042 return ExprError(); 3043 } 3044 3045 InMessageExpressionRAIIObject InMessage(*this, true); 3046 3047 if (getLangOpts().CPlusPlus) { 3048 // We completely separate the C and C++ cases because C++ requires 3049 // more complicated (read: slower) parsing. 3050 3051 // Handle send to super. 3052 // FIXME: This doesn't benefit from the same typo-correction we 3053 // get in Objective-C. 3054 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && 3055 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) 3056 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr, 3057 nullptr); 3058 3059 // Parse the receiver, which is either a type or an expression. 3060 bool IsExpr; 3061 void *TypeOrExpr = nullptr; 3062 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { 3063 SkipUntil(tok::r_square, StopAtSemi); 3064 return ExprError(); 3065 } 3066 3067 if (IsExpr) 3068 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr, 3069 static_cast<Expr *>(TypeOrExpr)); 3070 3071 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 3072 ParsedType::getFromOpaquePtr(TypeOrExpr), 3073 nullptr); 3074 } 3075 3076 if (Tok.is(tok::identifier)) { 3077 IdentifierInfo *Name = Tok.getIdentifierInfo(); 3078 SourceLocation NameLoc = Tok.getLocation(); 3079 ParsedType ReceiverType; 3080 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc, 3081 Name == Ident_super, 3082 NextToken().is(tok::period), 3083 ReceiverType)) { 3084 case Sema::ObjCSuperMessage: 3085 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr, 3086 nullptr); 3087 3088 case Sema::ObjCClassMessage: 3089 if (!ReceiverType) { 3090 SkipUntil(tok::r_square, StopAtSemi); 3091 return ExprError(); 3092 } 3093 3094 ConsumeToken(); // the type name 3095 3096 // Parse type arguments and protocol qualifiers. 3097 if (Tok.is(tok::less)) { 3098 SourceLocation NewEndLoc; 3099 TypeResult NewReceiverType 3100 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType, 3101 /*consumeLastToken=*/true, 3102 NewEndLoc); 3103 if (!NewReceiverType.isUsable()) { 3104 SkipUntil(tok::r_square, StopAtSemi); 3105 return ExprError(); 3106 } 3107 3108 ReceiverType = NewReceiverType.get(); 3109 } 3110 3111 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 3112 ReceiverType, nullptr); 3113 3114 case Sema::ObjCInstanceMessage: 3115 // Fall through to parse an expression. 3116 break; 3117 } 3118 } 3119 3120 // Otherwise, an arbitrary expression can be the receiver of a send. 3121 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression()); 3122 if (Res.isInvalid()) { 3123 SkipUntil(tok::r_square, StopAtSemi); 3124 return Res; 3125 } 3126 3127 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr, 3128 Res.get()); 3129 } 3130 3131 /// \brief Parse the remainder of an Objective-C message following the 3132 /// '[' objc-receiver. 3133 /// 3134 /// This routine handles sends to super, class messages (sent to a 3135 /// class name), and instance messages (sent to an object), and the 3136 /// target is represented by \p SuperLoc, \p ReceiverType, or \p 3137 /// ReceiverExpr, respectively. Only one of these parameters may have 3138 /// a valid value. 3139 /// 3140 /// \param LBracLoc The location of the opening '['. 3141 /// 3142 /// \param SuperLoc If this is a send to 'super', the location of the 3143 /// 'super' keyword that indicates a send to the superclass. 3144 /// 3145 /// \param ReceiverType If this is a class message, the type of the 3146 /// class we are sending a message to. 3147 /// 3148 /// \param ReceiverExpr If this is an instance message, the expression 3149 /// used to compute the receiver object. 3150 /// 3151 /// objc-message-args: 3152 /// objc-selector 3153 /// objc-keywordarg-list 3154 /// 3155 /// objc-keywordarg-list: 3156 /// objc-keywordarg 3157 /// objc-keywordarg-list objc-keywordarg 3158 /// 3159 /// objc-keywordarg: 3160 /// selector-name[opt] ':' objc-keywordexpr 3161 /// 3162 /// objc-keywordexpr: 3163 /// nonempty-expr-list 3164 /// 3165 /// nonempty-expr-list: 3166 /// assignment-expression 3167 /// nonempty-expr-list , assignment-expression 3168 /// 3169 ExprResult 3170 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, 3171 SourceLocation SuperLoc, 3172 ParsedType ReceiverType, 3173 Expr *ReceiverExpr) { 3174 InMessageExpressionRAIIObject InMessage(*this, true); 3175 3176 if (Tok.is(tok::code_completion)) { 3177 if (SuperLoc.isValid()) 3178 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None, 3179 false); 3180 else if (ReceiverType) 3181 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None, 3182 false); 3183 else 3184 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 3185 None, false); 3186 cutOffParsing(); 3187 return ExprError(); 3188 } 3189 3190 // Parse objc-selector 3191 SourceLocation Loc; 3192 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); 3193 3194 SmallVector<IdentifierInfo *, 12> KeyIdents; 3195 SmallVector<SourceLocation, 12> KeyLocs; 3196 ExprVector KeyExprs; 3197 3198 if (Tok.is(tok::colon)) { 3199 while (1) { 3200 // Each iteration parses a single keyword argument. 3201 KeyIdents.push_back(selIdent); 3202 KeyLocs.push_back(Loc); 3203 3204 if (ExpectAndConsume(tok::colon)) { 3205 // We must manually skip to a ']', otherwise the expression skipper will 3206 // stop at the ']' when it skips to the ';'. We want it to skip beyond 3207 // the enclosing expression. 3208 SkipUntil(tok::r_square, StopAtSemi); 3209 return ExprError(); 3210 } 3211 3212 /// Parse the expression after ':' 3213 3214 if (Tok.is(tok::code_completion)) { 3215 if (SuperLoc.isValid()) 3216 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 3217 KeyIdents, 3218 /*AtArgumentEpression=*/true); 3219 else if (ReceiverType) 3220 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 3221 KeyIdents, 3222 /*AtArgumentEpression=*/true); 3223 else 3224 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 3225 KeyIdents, 3226 /*AtArgumentEpression=*/true); 3227 3228 cutOffParsing(); 3229 return ExprError(); 3230 } 3231 3232 ExprResult Expr; 3233 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 3234 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 3235 Expr = ParseBraceInitializer(); 3236 } else 3237 Expr = ParseAssignmentExpression(); 3238 3239 ExprResult Res(Expr); 3240 if (Res.isInvalid()) { 3241 // We must manually skip to a ']', otherwise the expression skipper will 3242 // stop at the ']' when it skips to the ';'. We want it to skip beyond 3243 // the enclosing expression. 3244 SkipUntil(tok::r_square, StopAtSemi); 3245 return Res; 3246 } 3247 3248 // We have a valid expression. 3249 KeyExprs.push_back(Res.get()); 3250 3251 // Code completion after each argument. 3252 if (Tok.is(tok::code_completion)) { 3253 if (SuperLoc.isValid()) 3254 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 3255 KeyIdents, 3256 /*AtArgumentEpression=*/false); 3257 else if (ReceiverType) 3258 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 3259 KeyIdents, 3260 /*AtArgumentEpression=*/false); 3261 else 3262 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 3263 KeyIdents, 3264 /*AtArgumentEpression=*/false); 3265 cutOffParsing(); 3266 return ExprError(); 3267 } 3268 3269 // Check for another keyword selector. 3270 selIdent = ParseObjCSelectorPiece(Loc); 3271 if (!selIdent && Tok.isNot(tok::colon)) 3272 break; 3273 // We have a selector or a colon, continue parsing. 3274 } 3275 // Parse the, optional, argument list, comma separated. 3276 while (Tok.is(tok::comma)) { 3277 SourceLocation commaLoc = ConsumeToken(); // Eat the ','. 3278 /// Parse the expression after ',' 3279 ExprResult Res(ParseAssignmentExpression()); 3280 if (Tok.is(tok::colon)) 3281 Res = Actions.CorrectDelayedTyposInExpr(Res); 3282 if (Res.isInvalid()) { 3283 if (Tok.is(tok::colon)) { 3284 Diag(commaLoc, diag::note_extra_comma_message_arg) << 3285 FixItHint::CreateRemoval(commaLoc); 3286 } 3287 // We must manually skip to a ']', otherwise the expression skipper will 3288 // stop at the ']' when it skips to the ';'. We want it to skip beyond 3289 // the enclosing expression. 3290 SkipUntil(tok::r_square, StopAtSemi); 3291 return Res; 3292 } 3293 3294 // We have a valid expression. 3295 KeyExprs.push_back(Res.get()); 3296 } 3297 } else if (!selIdent) { 3298 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name. 3299 3300 // We must manually skip to a ']', otherwise the expression skipper will 3301 // stop at the ']' when it skips to the ';'. We want it to skip beyond 3302 // the enclosing expression. 3303 SkipUntil(tok::r_square, StopAtSemi); 3304 return ExprError(); 3305 } 3306 3307 if (Tok.isNot(tok::r_square)) { 3308 Diag(Tok, diag::err_expected) 3309 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square); 3310 // We must manually skip to a ']', otherwise the expression skipper will 3311 // stop at the ']' when it skips to the ';'. We want it to skip beyond 3312 // the enclosing expression. 3313 SkipUntil(tok::r_square, StopAtSemi); 3314 return ExprError(); 3315 } 3316 3317 SourceLocation RBracLoc = ConsumeBracket(); // consume ']' 3318 3319 unsigned nKeys = KeyIdents.size(); 3320 if (nKeys == 0) { 3321 KeyIdents.push_back(selIdent); 3322 KeyLocs.push_back(Loc); 3323 } 3324 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]); 3325 3326 if (SuperLoc.isValid()) 3327 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel, 3328 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 3329 else if (ReceiverType) 3330 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel, 3331 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 3332 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel, 3333 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 3334 } 3335 3336 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { 3337 ExprResult Res(ParseStringLiteralExpression()); 3338 if (Res.isInvalid()) return Res; 3339 3340 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string 3341 // expressions. At this point, we know that the only valid thing that starts 3342 // with '@' is an @"". 3343 SmallVector<SourceLocation, 4> AtLocs; 3344 ExprVector AtStrings; 3345 AtLocs.push_back(AtLoc); 3346 AtStrings.push_back(Res.get()); 3347 3348 while (Tok.is(tok::at)) { 3349 AtLocs.push_back(ConsumeToken()); // eat the @. 3350 3351 // Invalid unless there is a string literal. 3352 if (!isTokenStringLiteral()) 3353 return ExprError(Diag(Tok, diag::err_objc_concat_string)); 3354 3355 ExprResult Lit(ParseStringLiteralExpression()); 3356 if (Lit.isInvalid()) 3357 return Lit; 3358 3359 AtStrings.push_back(Lit.get()); 3360 } 3361 3362 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings); 3363 } 3364 3365 /// ParseObjCBooleanLiteral - 3366 /// objc-scalar-literal : '@' boolean-keyword 3367 /// ; 3368 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no' 3369 /// ; 3370 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, 3371 bool ArgValue) { 3372 SourceLocation EndLoc = ConsumeToken(); // consume the keyword. 3373 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue); 3374 } 3375 3376 /// ParseObjCCharacterLiteral - 3377 /// objc-scalar-literal : '@' character-literal 3378 /// ; 3379 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) { 3380 ExprResult Lit(Actions.ActOnCharacterConstant(Tok)); 3381 if (Lit.isInvalid()) { 3382 return Lit; 3383 } 3384 ConsumeToken(); // Consume the literal token. 3385 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()); 3386 } 3387 3388 /// ParseObjCNumericLiteral - 3389 /// objc-scalar-literal : '@' scalar-literal 3390 /// ; 3391 /// scalar-literal : | numeric-constant /* any numeric constant. */ 3392 /// ; 3393 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) { 3394 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 3395 if (Lit.isInvalid()) { 3396 return Lit; 3397 } 3398 ConsumeToken(); // Consume the literal token. 3399 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()); 3400 } 3401 3402 /// ParseObjCBoxedExpr - 3403 /// objc-box-expression: 3404 /// @( assignment-expression ) 3405 ExprResult 3406 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) { 3407 if (Tok.isNot(tok::l_paren)) 3408 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@"); 3409 3410 BalancedDelimiterTracker T(*this, tok::l_paren); 3411 T.consumeOpen(); 3412 ExprResult ValueExpr(ParseAssignmentExpression()); 3413 if (T.consumeClose()) 3414 return ExprError(); 3415 3416 if (ValueExpr.isInvalid()) 3417 return ExprError(); 3418 3419 // Wrap the sub-expression in a parenthesized expression, to distinguish 3420 // a boxed expression from a literal. 3421 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation(); 3422 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get()); 3423 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc), 3424 ValueExpr.get()); 3425 } 3426 3427 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) { 3428 ExprVector ElementExprs; // array elements. 3429 ConsumeBracket(); // consume the l_square. 3430 3431 bool HasInvalidEltExpr = false; 3432 while (Tok.isNot(tok::r_square)) { 3433 // Parse list of array element expressions (all must be id types). 3434 ExprResult Res(ParseAssignmentExpression()); 3435 if (Res.isInvalid()) { 3436 // We must manually skip to a ']', otherwise the expression skipper will 3437 // stop at the ']' when it skips to the ';'. We want it to skip beyond 3438 // the enclosing expression. 3439 SkipUntil(tok::r_square, StopAtSemi); 3440 return Res; 3441 } 3442 3443 Res = Actions.CorrectDelayedTyposInExpr(Res.get()); 3444 if (Res.isInvalid()) 3445 HasInvalidEltExpr = true; 3446 3447 // Parse the ellipsis that indicates a pack expansion. 3448 if (Tok.is(tok::ellipsis)) 3449 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); 3450 if (Res.isInvalid()) 3451 HasInvalidEltExpr = true; 3452 3453 ElementExprs.push_back(Res.get()); 3454 3455 if (Tok.is(tok::comma)) 3456 ConsumeToken(); // Eat the ','. 3457 else if (Tok.isNot(tok::r_square)) 3458 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square 3459 << tok::comma); 3460 } 3461 SourceLocation EndLoc = ConsumeBracket(); // location of ']' 3462 3463 if (HasInvalidEltExpr) 3464 return ExprError(); 3465 3466 MultiExprArg Args(ElementExprs); 3467 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args); 3468 } 3469 3470 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { 3471 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements. 3472 ConsumeBrace(); // consume the l_square. 3473 bool HasInvalidEltExpr = false; 3474 while (Tok.isNot(tok::r_brace)) { 3475 // Parse the comma separated key : value expressions. 3476 ExprResult KeyExpr; 3477 { 3478 ColonProtectionRAIIObject X(*this); 3479 KeyExpr = ParseAssignmentExpression(); 3480 if (KeyExpr.isInvalid()) { 3481 // We must manually skip to a '}', otherwise the expression skipper will 3482 // stop at the '}' when it skips to the ';'. We want it to skip beyond 3483 // the enclosing expression. 3484 SkipUntil(tok::r_brace, StopAtSemi); 3485 return KeyExpr; 3486 } 3487 } 3488 3489 if (ExpectAndConsume(tok::colon)) { 3490 SkipUntil(tok::r_brace, StopAtSemi); 3491 return ExprError(); 3492 } 3493 3494 ExprResult ValueExpr(ParseAssignmentExpression()); 3495 if (ValueExpr.isInvalid()) { 3496 // We must manually skip to a '}', otherwise the expression skipper will 3497 // stop at the '}' when it skips to the ';'. We want it to skip beyond 3498 // the enclosing expression. 3499 SkipUntil(tok::r_brace, StopAtSemi); 3500 return ValueExpr; 3501 } 3502 3503 // Check the key and value for possible typos 3504 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get()); 3505 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get()); 3506 if (KeyExpr.isInvalid() || ValueExpr.isInvalid()) 3507 HasInvalidEltExpr = true; 3508 3509 // Parse the ellipsis that designates this as a pack expansion. Do not 3510 // ActOnPackExpansion here, leave it to template instantiation time where 3511 // we can get better diagnostics. 3512 SourceLocation EllipsisLoc; 3513 if (getLangOpts().CPlusPlus) 3514 TryConsumeToken(tok::ellipsis, EllipsisLoc); 3515 3516 // We have a valid expression. Collect it in a vector so we can 3517 // build the argument list. 3518 ObjCDictionaryElement Element = { 3519 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None 3520 }; 3521 Elements.push_back(Element); 3522 3523 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace)) 3524 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace 3525 << tok::comma); 3526 } 3527 SourceLocation EndLoc = ConsumeBrace(); 3528 3529 if (HasInvalidEltExpr) 3530 return ExprError(); 3531 3532 // Create the ObjCDictionaryLiteral. 3533 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc), 3534 Elements); 3535 } 3536 3537 /// objc-encode-expression: 3538 /// \@encode ( type-name ) 3539 ExprResult 3540 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) { 3541 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!"); 3542 3543 SourceLocation EncLoc = ConsumeToken(); 3544 3545 if (Tok.isNot(tok::l_paren)) 3546 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode"); 3547 3548 BalancedDelimiterTracker T(*this, tok::l_paren); 3549 T.consumeOpen(); 3550 3551 TypeResult Ty = ParseTypeName(); 3552 3553 T.consumeClose(); 3554 3555 if (Ty.isInvalid()) 3556 return ExprError(); 3557 3558 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(), 3559 Ty.get(), T.getCloseLocation()); 3560 } 3561 3562 /// objc-protocol-expression 3563 /// \@protocol ( protocol-name ) 3564 ExprResult 3565 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) { 3566 SourceLocation ProtoLoc = ConsumeToken(); 3567 3568 if (Tok.isNot(tok::l_paren)) 3569 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol"); 3570 3571 BalancedDelimiterTracker T(*this, tok::l_paren); 3572 T.consumeOpen(); 3573 3574 if (Tok.isNot(tok::identifier)) 3575 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); 3576 3577 IdentifierInfo *protocolId = Tok.getIdentifierInfo(); 3578 SourceLocation ProtoIdLoc = ConsumeToken(); 3579 3580 T.consumeClose(); 3581 3582 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc, 3583 T.getOpenLocation(), ProtoIdLoc, 3584 T.getCloseLocation()); 3585 } 3586 3587 /// objc-selector-expression 3588 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')' 3589 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { 3590 SourceLocation SelectorLoc = ConsumeToken(); 3591 3592 if (Tok.isNot(tok::l_paren)) 3593 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector"); 3594 3595 SmallVector<IdentifierInfo *, 12> KeyIdents; 3596 SourceLocation sLoc; 3597 3598 BalancedDelimiterTracker T(*this, tok::l_paren); 3599 T.consumeOpen(); 3600 bool HasOptionalParen = Tok.is(tok::l_paren); 3601 if (HasOptionalParen) 3602 ConsumeParen(); 3603 3604 if (Tok.is(tok::code_completion)) { 3605 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); 3606 cutOffParsing(); 3607 return ExprError(); 3608 } 3609 3610 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); 3611 if (!SelIdent && // missing selector name. 3612 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 3613 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); 3614 3615 KeyIdents.push_back(SelIdent); 3616 3617 unsigned nColons = 0; 3618 if (Tok.isNot(tok::r_paren)) { 3619 while (1) { 3620 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++. 3621 ++nColons; 3622 KeyIdents.push_back(nullptr); 3623 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'. 3624 return ExprError(); 3625 ++nColons; 3626 3627 if (Tok.is(tok::r_paren)) 3628 break; 3629 3630 if (Tok.is(tok::code_completion)) { 3631 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); 3632 cutOffParsing(); 3633 return ExprError(); 3634 } 3635 3636 // Check for another keyword selector. 3637 SourceLocation Loc; 3638 SelIdent = ParseObjCSelectorPiece(Loc); 3639 KeyIdents.push_back(SelIdent); 3640 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 3641 break; 3642 } 3643 } 3644 if (HasOptionalParen && Tok.is(tok::r_paren)) 3645 ConsumeParen(); // ')' 3646 T.consumeClose(); 3647 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]); 3648 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc, 3649 T.getOpenLocation(), 3650 T.getCloseLocation(), 3651 !HasOptionalParen); 3652 } 3653 3654 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { 3655 // MCDecl might be null due to error in method or c-function prototype, etc. 3656 Decl *MCDecl = LM.D; 3657 bool skip = MCDecl && 3658 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) || 3659 (!parseMethod && Actions.isObjCMethodDecl(MCDecl))); 3660 if (skip) 3661 return; 3662 3663 // Save the current token position. 3664 SourceLocation OrigLoc = Tok.getLocation(); 3665 3666 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!"); 3667 // Append the current token at the end of the new token stream so that it 3668 // doesn't get lost. 3669 LM.Toks.push_back(Tok); 3670 PP.EnterTokenStream(LM.Toks, true); 3671 3672 // Consume the previously pushed token. 3673 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 3674 3675 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && 3676 "Inline objective-c method not starting with '{' or 'try' or ':'"); 3677 // Enter a scope for the method or c-function body. 3678 ParseScope BodyScope(this, 3679 parseMethod 3680 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope 3681 : Scope::FnScope|Scope::DeclScope); 3682 3683 // Tell the actions module that we have entered a method or c-function definition 3684 // with the specified Declarator for the method/function. 3685 if (parseMethod) 3686 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl); 3687 else 3688 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl); 3689 if (Tok.is(tok::kw_try)) 3690 ParseFunctionTryBlock(MCDecl, BodyScope); 3691 else { 3692 if (Tok.is(tok::colon)) 3693 ParseConstructorInitializer(MCDecl); 3694 else 3695 Actions.ActOnDefaultCtorInitializers(MCDecl); 3696 ParseFunctionStatementBody(MCDecl, BodyScope); 3697 } 3698 3699 if (Tok.getLocation() != OrigLoc) { 3700 // Due to parsing error, we either went over the cached tokens or 3701 // there are still cached tokens left. If it's the latter case skip the 3702 // leftover tokens. 3703 // Since this is an uncommon situation that should be avoided, use the 3704 // expensive isBeforeInTranslationUnit call. 3705 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 3706 OrigLoc)) 3707 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof)) 3708 ConsumeAnyToken(); 3709 } 3710 } 3711