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/Basic/CharInfo.h" 17#include "clang/Parse/ParseDiagnostic.h" 18#include "clang/Sema/DeclSpec.h" 19#include "clang/Sema/PrettyDeclStackTrace.h" 20#include "clang/Sema/Scope.h" 21#include "llvm/ADT/SmallVector.h" 22#include "llvm/ADT/StringExtras.h" 23using namespace clang; 24 25/// Skips attributes after an Objective-C @ directive. Emits a diagnostic. 26void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) { 27 ParsedAttributes attrs(AttrFactory); 28 if (Tok.is(tok::kw___attribute)) { 29 if (Kind == tok::objc_interface || Kind == tok::objc_protocol) 30 Diag(Tok, diag::err_objc_postfix_attribute_hint) 31 << (Kind == tok::objc_protocol); 32 else 33 Diag(Tok, diag::err_objc_postfix_attribute); 34 ParseGNUAttributes(attrs); 35 } 36} 37 38/// ParseObjCAtDirectives - Handle parts of the external-declaration production: 39/// external-declaration: [C99 6.9] 40/// [OBJC] objc-class-definition 41/// [OBJC] objc-class-declaration 42/// [OBJC] objc-alias-declaration 43/// [OBJC] objc-protocol-definition 44/// [OBJC] objc-method-definition 45/// [OBJC] '@' 'end' 46Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() { 47 SourceLocation AtLoc = ConsumeToken(); // the "@" 48 49 if (Tok.is(tok::code_completion)) { 50 Actions.CodeCompleteObjCAtDirective(getCurScope()); 51 cutOffParsing(); 52 return DeclGroupPtrTy(); 53 } 54 55 Decl *SingleDecl = 0; 56 switch (Tok.getObjCKeywordID()) { 57 case tok::objc_class: 58 return ParseObjCAtClassDeclaration(AtLoc); 59 case tok::objc_interface: { 60 ParsedAttributes attrs(AttrFactory); 61 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs); 62 break; 63 } 64 case tok::objc_protocol: { 65 ParsedAttributes attrs(AttrFactory); 66 return ParseObjCAtProtocolDeclaration(AtLoc, attrs); 67 } 68 case tok::objc_implementation: 69 return ParseObjCAtImplementationDeclaration(AtLoc); 70 case tok::objc_end: 71 return ParseObjCAtEndDeclaration(AtLoc); 72 case tok::objc_compatibility_alias: 73 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc); 74 break; 75 case tok::objc_synthesize: 76 SingleDecl = ParseObjCPropertySynthesize(AtLoc); 77 break; 78 case tok::objc_dynamic: 79 SingleDecl = ParseObjCPropertyDynamic(AtLoc); 80 break; 81 case tok::objc_import: 82 if (getLangOpts().Modules) 83 return ParseModuleImport(AtLoc); 84 85 // Fall through 86 87 default: 88 Diag(AtLoc, diag::err_unexpected_at); 89 SkipUntil(tok::semi); 90 SingleDecl = 0; 91 break; 92 } 93 return Actions.ConvertDeclToDeclGroup(SingleDecl); 94} 95 96/// 97/// objc-class-declaration: 98/// '@' 'class' identifier-list ';' 99/// 100Parser::DeclGroupPtrTy 101Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { 102 ConsumeToken(); // the identifier "class" 103 SmallVector<IdentifierInfo *, 8> ClassNames; 104 SmallVector<SourceLocation, 8> ClassLocs; 105 106 107 while (1) { 108 MaybeSkipAttributes(tok::objc_class); 109 if (Tok.isNot(tok::identifier)) { 110 Diag(Tok, diag::err_expected_ident); 111 SkipUntil(tok::semi); 112 return Actions.ConvertDeclToDeclGroup(0); 113 } 114 ClassNames.push_back(Tok.getIdentifierInfo()); 115 ClassLocs.push_back(Tok.getLocation()); 116 ConsumeToken(); 117 118 if (Tok.isNot(tok::comma)) 119 break; 120 121 ConsumeToken(); 122 } 123 124 // Consume the ';'. 125 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class")) 126 return Actions.ConvertDeclToDeclGroup(0); 127 128 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(), 129 ClassLocs.data(), 130 ClassNames.size()); 131} 132 133void Parser::CheckNestedObjCContexts(SourceLocation AtLoc) 134{ 135 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind(); 136 if (ock == Sema::OCK_None) 137 return; 138 139 Decl *Decl = Actions.getObjCDeclContext(); 140 if (CurParsedObjCImpl) { 141 CurParsedObjCImpl->finish(AtLoc); 142 } else { 143 Actions.ActOnAtEnd(getCurScope(), AtLoc); 144 } 145 Diag(AtLoc, diag::err_objc_missing_end) 146 << FixItHint::CreateInsertion(AtLoc, "@end\n"); 147 if (Decl) 148 Diag(Decl->getLocStart(), diag::note_objc_container_start) 149 << (int) ock; 150} 151 152/// 153/// objc-interface: 154/// objc-class-interface-attributes[opt] objc-class-interface 155/// objc-category-interface 156/// 157/// objc-class-interface: 158/// '@' 'interface' identifier objc-superclass[opt] 159/// objc-protocol-refs[opt] 160/// objc-class-instance-variables[opt] 161/// objc-interface-decl-list 162/// @end 163/// 164/// objc-category-interface: 165/// '@' 'interface' identifier '(' identifier[opt] ')' 166/// objc-protocol-refs[opt] 167/// objc-interface-decl-list 168/// @end 169/// 170/// objc-superclass: 171/// ':' identifier 172/// 173/// objc-class-interface-attributes: 174/// __attribute__((visibility("default"))) 175/// __attribute__((visibility("hidden"))) 176/// __attribute__((deprecated)) 177/// __attribute__((unavailable)) 178/// __attribute__((objc_exception)) - used by NSException on 64-bit 179/// __attribute__((objc_root_class)) 180/// 181Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, 182 ParsedAttributes &attrs) { 183 assert(Tok.isObjCAtKeyword(tok::objc_interface) && 184 "ParseObjCAtInterfaceDeclaration(): Expected @interface"); 185 CheckNestedObjCContexts(AtLoc); 186 ConsumeToken(); // the "interface" identifier 187 188 // Code completion after '@interface'. 189 if (Tok.is(tok::code_completion)) { 190 Actions.CodeCompleteObjCInterfaceDecl(getCurScope()); 191 cutOffParsing(); 192 return 0; 193 } 194 195 MaybeSkipAttributes(tok::objc_interface); 196 197 if (Tok.isNot(tok::identifier)) { 198 Diag(Tok, diag::err_expected_ident); // missing class or category name. 199 return 0; 200 } 201 202 // We have a class or category name - consume it. 203 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 204 SourceLocation nameLoc = ConsumeToken(); 205 if (Tok.is(tok::l_paren) && 206 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. 207 208 BalancedDelimiterTracker T(*this, tok::l_paren); 209 T.consumeOpen(); 210 211 SourceLocation categoryLoc; 212 IdentifierInfo *categoryId = 0; 213 if (Tok.is(tok::code_completion)) { 214 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc); 215 cutOffParsing(); 216 return 0; 217 } 218 219 // For ObjC2, the category name is optional (not an error). 220 if (Tok.is(tok::identifier)) { 221 categoryId = Tok.getIdentifierInfo(); 222 categoryLoc = ConsumeToken(); 223 } 224 else if (!getLangOpts().ObjC2) { 225 Diag(Tok, diag::err_expected_ident); // missing category name. 226 return 0; 227 } 228 229 T.consumeClose(); 230 if (T.getCloseLocation().isInvalid()) 231 return 0; 232 233 if (!attrs.empty()) { // categories don't support attributes. 234 Diag(nameLoc, diag::err_objc_no_attributes_on_category); 235 attrs.clear(); 236 } 237 238 // Next, we need to check for any protocol references. 239 SourceLocation LAngleLoc, EndProtoLoc; 240 SmallVector<Decl *, 8> ProtocolRefs; 241 SmallVector<SourceLocation, 8> ProtocolLocs; 242 if (Tok.is(tok::less) && 243 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, 244 LAngleLoc, EndProtoLoc)) 245 return 0; 246 247 Decl *CategoryType = 248 Actions.ActOnStartCategoryInterface(AtLoc, 249 nameId, nameLoc, 250 categoryId, categoryLoc, 251 ProtocolRefs.data(), 252 ProtocolRefs.size(), 253 ProtocolLocs.data(), 254 EndProtoLoc); 255 256 if (Tok.is(tok::l_brace)) 257 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc); 258 259 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType); 260 return CategoryType; 261 } 262 // Parse a class interface. 263 IdentifierInfo *superClassId = 0; 264 SourceLocation superClassLoc; 265 266 if (Tok.is(tok::colon)) { // a super class is specified. 267 ConsumeToken(); 268 269 // Code completion of superclass names. 270 if (Tok.is(tok::code_completion)) { 271 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc); 272 cutOffParsing(); 273 return 0; 274 } 275 276 if (Tok.isNot(tok::identifier)) { 277 Diag(Tok, diag::err_expected_ident); // missing super class name. 278 return 0; 279 } 280 superClassId = Tok.getIdentifierInfo(); 281 superClassLoc = ConsumeToken(); 282 } 283 // Next, we need to check for any protocol references. 284 SmallVector<Decl *, 8> ProtocolRefs; 285 SmallVector<SourceLocation, 8> ProtocolLocs; 286 SourceLocation LAngleLoc, EndProtoLoc; 287 if (Tok.is(tok::less) && 288 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, 289 LAngleLoc, EndProtoLoc)) 290 return 0; 291 292 Decl *ClsType = 293 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc, 294 superClassId, superClassLoc, 295 ProtocolRefs.data(), ProtocolRefs.size(), 296 ProtocolLocs.data(), 297 EndProtoLoc, attrs.getList()); 298 299 if (Tok.is(tok::l_brace)) 300 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc); 301 302 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType); 303 return ClsType; 304} 305 306/// The Objective-C property callback. This should be defined where 307/// it's used, but instead it's been lifted to here to support VS2005. 308struct Parser::ObjCPropertyCallback : FieldCallback { 309private: 310 virtual void anchor(); 311public: 312 Parser &P; 313 SmallVectorImpl<Decl *> &Props; 314 ObjCDeclSpec &OCDS; 315 SourceLocation AtLoc; 316 SourceLocation LParenLoc; 317 tok::ObjCKeywordKind MethodImplKind; 318 319 ObjCPropertyCallback(Parser &P, 320 SmallVectorImpl<Decl *> &Props, 321 ObjCDeclSpec &OCDS, SourceLocation AtLoc, 322 SourceLocation LParenLoc, 323 tok::ObjCKeywordKind MethodImplKind) : 324 P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc), 325 MethodImplKind(MethodImplKind) { 326 } 327 328 void invoke(ParsingFieldDeclarator &FD) { 329 if (FD.D.getIdentifier() == 0) { 330 P.Diag(AtLoc, diag::err_objc_property_requires_field_name) 331 << FD.D.getSourceRange(); 332 return; 333 } 334 if (FD.BitfieldSize) { 335 P.Diag(AtLoc, diag::err_objc_property_bitfield) 336 << FD.D.getSourceRange(); 337 return; 338 } 339 340 // Install the property declarator into interfaceDecl. 341 IdentifierInfo *SelName = 342 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier(); 343 344 Selector GetterSel = 345 P.PP.getSelectorTable().getNullarySelector(SelName); 346 IdentifierInfo *SetterName = OCDS.getSetterName(); 347 Selector SetterSel; 348 if (SetterName) 349 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName); 350 else 351 SetterSel = 352 SelectorTable::constructSetterSelector(P.PP.getIdentifierTable(), 353 P.PP.getSelectorTable(), 354 FD.D.getIdentifier()); 355 bool isOverridingProperty = false; 356 Decl *Property = 357 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc, 358 FD, OCDS, 359 GetterSel, SetterSel, 360 &isOverridingProperty, 361 MethodImplKind); 362 if (!isOverridingProperty) 363 Props.push_back(Property); 364 365 FD.complete(Property); 366 } 367}; 368 369void Parser::ObjCPropertyCallback::anchor() { 370} 371 372/// objc-interface-decl-list: 373/// empty 374/// objc-interface-decl-list objc-property-decl [OBJC2] 375/// objc-interface-decl-list objc-method-requirement [OBJC2] 376/// objc-interface-decl-list objc-method-proto ';' 377/// objc-interface-decl-list declaration 378/// objc-interface-decl-list ';' 379/// 380/// objc-method-requirement: [OBJC2] 381/// @required 382/// @optional 383/// 384void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, 385 Decl *CDecl) { 386 SmallVector<Decl *, 32> allMethods; 387 SmallVector<Decl *, 16> allProperties; 388 SmallVector<DeclGroupPtrTy, 8> allTUVariables; 389 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; 390 391 SourceRange AtEnd; 392 393 while (1) { 394 // If this is a method prototype, parse it. 395 if (Tok.is(tok::minus) || Tok.is(tok::plus)) { 396 if (Decl *methodPrototype = 397 ParseObjCMethodPrototype(MethodImplKind, false)) 398 allMethods.push_back(methodPrototype); 399 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for 400 // method definitions. 401 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) { 402 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'. 403 SkipUntil(tok::at, /*StopAtSemi=*/true, /*DontConsume=*/true); 404 if (Tok.is(tok::semi)) 405 ConsumeToken(); 406 } 407 continue; 408 } 409 if (Tok.is(tok::l_paren)) { 410 Diag(Tok, diag::err_expected_minus_or_plus); 411 ParseObjCMethodDecl(Tok.getLocation(), 412 tok::minus, 413 MethodImplKind, false); 414 continue; 415 } 416 // Ignore excess semicolons. 417 if (Tok.is(tok::semi)) { 418 ConsumeToken(); 419 continue; 420 } 421 422 // If we got to the end of the file, exit the loop. 423 if (Tok.is(tok::eof)) 424 break; 425 426 // Code completion within an Objective-C interface. 427 if (Tok.is(tok::code_completion)) { 428 Actions.CodeCompleteOrdinaryName(getCurScope(), 429 CurParsedObjCImpl? Sema::PCC_ObjCImplementation 430 : Sema::PCC_ObjCInterface); 431 return cutOffParsing(); 432 } 433 434 // If we don't have an @ directive, parse it as a function definition. 435 if (Tok.isNot(tok::at)) { 436 // The code below does not consume '}'s because it is afraid of eating the 437 // end of a namespace. Because of the way this code is structured, an 438 // erroneous r_brace would cause an infinite loop if not handled here. 439 if (Tok.is(tok::r_brace)) 440 break; 441 ParsedAttributesWithRange attrs(AttrFactory); 442 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs)); 443 continue; 444 } 445 446 // Otherwise, we have an @ directive, eat the @. 447 SourceLocation AtLoc = ConsumeToken(); // the "@" 448 if (Tok.is(tok::code_completion)) { 449 Actions.CodeCompleteObjCAtDirective(getCurScope()); 450 return cutOffParsing(); 451 } 452 453 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID(); 454 455 if (DirectiveKind == tok::objc_end) { // @end -> terminate list 456 AtEnd.setBegin(AtLoc); 457 AtEnd.setEnd(Tok.getLocation()); 458 break; 459 } else if (DirectiveKind == tok::objc_not_keyword) { 460 Diag(Tok, diag::err_objc_unknown_at); 461 SkipUntil(tok::semi); 462 continue; 463 } 464 465 // Eat the identifier. 466 ConsumeToken(); 467 468 switch (DirectiveKind) { 469 default: 470 // FIXME: If someone forgets an @end on a protocol, this loop will 471 // continue to eat up tons of stuff and spew lots of nonsense errors. It 472 // would probably be better to bail out if we saw an @class or @interface 473 // or something like that. 474 Diag(AtLoc, diag::err_objc_illegal_interface_qual); 475 // Skip until we see an '@' or '}' or ';'. 476 SkipUntil(tok::r_brace, tok::at); 477 break; 478 479 case tok::objc_implementation: 480 case tok::objc_interface: 481 Diag(AtLoc, diag::err_objc_missing_end) 482 << FixItHint::CreateInsertion(AtLoc, "@end\n"); 483 Diag(CDecl->getLocStart(), diag::note_objc_container_start) 484 << (int) Actions.getObjCContainerKind(); 485 ConsumeToken(); 486 break; 487 488 case tok::objc_required: 489 case tok::objc_optional: 490 // This is only valid on protocols. 491 // FIXME: Should this check for ObjC2 being enabled? 492 if (contextKey != tok::objc_protocol) 493 Diag(AtLoc, diag::err_objc_directive_only_in_protocol); 494 else 495 MethodImplKind = DirectiveKind; 496 break; 497 498 case tok::objc_property: 499 if (!getLangOpts().ObjC2) 500 Diag(AtLoc, diag::err_objc_properties_require_objc2); 501 502 ObjCDeclSpec OCDS; 503 SourceLocation LParenLoc; 504 // Parse property attribute list, if any. 505 if (Tok.is(tok::l_paren)) { 506 LParenLoc = Tok.getLocation(); 507 ParseObjCPropertyAttribute(OCDS); 508 } 509 510 ObjCPropertyCallback Callback(*this, allProperties, 511 OCDS, AtLoc, LParenLoc, MethodImplKind); 512 513 // Parse all the comma separated declarators. 514 ParsingDeclSpec DS(*this); 515 ParseStructDeclaration(DS, Callback); 516 517 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 518 break; 519 } 520 } 521 522 // We break out of the big loop in two cases: when we see @end or when we see 523 // EOF. In the former case, eat the @end. In the later case, emit an error. 524 if (Tok.is(tok::code_completion)) { 525 Actions.CodeCompleteObjCAtDirective(getCurScope()); 526 return cutOffParsing(); 527 } else if (Tok.isObjCAtKeyword(tok::objc_end)) { 528 ConsumeToken(); // the "end" identifier 529 } else { 530 Diag(Tok, diag::err_objc_missing_end) 531 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n"); 532 Diag(CDecl->getLocStart(), diag::note_objc_container_start) 533 << (int) Actions.getObjCContainerKind(); 534 AtEnd.setBegin(Tok.getLocation()); 535 AtEnd.setEnd(Tok.getLocation()); 536 } 537 538 // Insert collected methods declarations into the @interface object. 539 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit. 540 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables); 541} 542 543/// Parse property attribute declarations. 544/// 545/// property-attr-decl: '(' property-attrlist ')' 546/// property-attrlist: 547/// property-attribute 548/// property-attrlist ',' property-attribute 549/// property-attribute: 550/// getter '=' identifier 551/// setter '=' identifier ':' 552/// readonly 553/// readwrite 554/// assign 555/// retain 556/// copy 557/// nonatomic 558/// atomic 559/// strong 560/// weak 561/// unsafe_unretained 562/// 563void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { 564 assert(Tok.getKind() == tok::l_paren); 565 BalancedDelimiterTracker T(*this, tok::l_paren); 566 T.consumeOpen(); 567 568 while (1) { 569 if (Tok.is(tok::code_completion)) { 570 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS); 571 return cutOffParsing(); 572 } 573 const IdentifierInfo *II = Tok.getIdentifierInfo(); 574 575 // If this is not an identifier at all, bail out early. 576 if (II == 0) { 577 T.consumeClose(); 578 return; 579 } 580 581 SourceLocation AttrName = ConsumeToken(); // consume last attribute name 582 583 if (II->isStr("readonly")) 584 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly); 585 else if (II->isStr("assign")) 586 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign); 587 else if (II->isStr("unsafe_unretained")) 588 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained); 589 else if (II->isStr("readwrite")) 590 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite); 591 else if (II->isStr("retain")) 592 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain); 593 else if (II->isStr("strong")) 594 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong); 595 else if (II->isStr("copy")) 596 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy); 597 else if (II->isStr("nonatomic")) 598 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic); 599 else if (II->isStr("atomic")) 600 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic); 601 else if (II->isStr("weak")) 602 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak); 603 else if (II->isStr("getter") || II->isStr("setter")) { 604 bool IsSetter = II->getNameStart()[0] == 's'; 605 606 // getter/setter require extra treatment. 607 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter : 608 diag::err_objc_expected_equal_for_getter; 609 610 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren)) 611 return; 612 613 if (Tok.is(tok::code_completion)) { 614 if (IsSetter) 615 Actions.CodeCompleteObjCPropertySetter(getCurScope()); 616 else 617 Actions.CodeCompleteObjCPropertyGetter(getCurScope()); 618 return cutOffParsing(); 619 } 620 621 622 SourceLocation SelLoc; 623 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc); 624 625 if (!SelIdent) { 626 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter) 627 << IsSetter; 628 SkipUntil(tok::r_paren); 629 return; 630 } 631 632 if (IsSetter) { 633 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter); 634 DS.setSetterName(SelIdent); 635 636 if (ExpectAndConsume(tok::colon, 637 diag::err_expected_colon_after_setter_name, "", 638 tok::r_paren)) 639 return; 640 } else { 641 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter); 642 DS.setGetterName(SelIdent); 643 } 644 } else { 645 Diag(AttrName, diag::err_objc_expected_property_attr) << II; 646 SkipUntil(tok::r_paren); 647 return; 648 } 649 650 if (Tok.isNot(tok::comma)) 651 break; 652 653 ConsumeToken(); 654 } 655 656 T.consumeClose(); 657} 658 659/// objc-method-proto: 660/// objc-instance-method objc-method-decl objc-method-attributes[opt] 661/// objc-class-method objc-method-decl objc-method-attributes[opt] 662/// 663/// objc-instance-method: '-' 664/// objc-class-method: '+' 665/// 666/// objc-method-attributes: [OBJC2] 667/// __attribute__((deprecated)) 668/// 669Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind, 670 bool MethodDefinition) { 671 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-"); 672 673 tok::TokenKind methodType = Tok.getKind(); 674 SourceLocation mLoc = ConsumeToken(); 675 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind, 676 MethodDefinition); 677 // Since this rule is used for both method declarations and definitions, 678 // the caller is (optionally) responsible for consuming the ';'. 679 return MDecl; 680} 681 682/// objc-selector: 683/// identifier 684/// one of 685/// enum struct union if else while do for switch case default 686/// break continue return goto asm sizeof typeof __alignof 687/// unsigned long const short volatile signed restrict _Complex 688/// in out inout bycopy byref oneway int char float double void _Bool 689/// 690IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) { 691 692 switch (Tok.getKind()) { 693 default: 694 return 0; 695 case tok::ampamp: 696 case tok::ampequal: 697 case tok::amp: 698 case tok::pipe: 699 case tok::tilde: 700 case tok::exclaim: 701 case tok::exclaimequal: 702 case tok::pipepipe: 703 case tok::pipeequal: 704 case tok::caret: 705 case tok::caretequal: { 706 std::string ThisTok(PP.getSpelling(Tok)); 707 if (isLetter(ThisTok[0])) { 708 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data()); 709 Tok.setKind(tok::identifier); 710 SelectorLoc = ConsumeToken(); 711 return II; 712 } 713 return 0; 714 } 715 716 case tok::identifier: 717 case tok::kw_asm: 718 case tok::kw_auto: 719 case tok::kw_bool: 720 case tok::kw_break: 721 case tok::kw_case: 722 case tok::kw_catch: 723 case tok::kw_char: 724 case tok::kw_class: 725 case tok::kw_const: 726 case tok::kw_const_cast: 727 case tok::kw_continue: 728 case tok::kw_default: 729 case tok::kw_delete: 730 case tok::kw_do: 731 case tok::kw_double: 732 case tok::kw_dynamic_cast: 733 case tok::kw_else: 734 case tok::kw_enum: 735 case tok::kw_explicit: 736 case tok::kw_export: 737 case tok::kw_extern: 738 case tok::kw_false: 739 case tok::kw_float: 740 case tok::kw_for: 741 case tok::kw_friend: 742 case tok::kw_goto: 743 case tok::kw_if: 744 case tok::kw_inline: 745 case tok::kw_int: 746 case tok::kw_long: 747 case tok::kw_mutable: 748 case tok::kw_namespace: 749 case tok::kw_new: 750 case tok::kw_operator: 751 case tok::kw_private: 752 case tok::kw_protected: 753 case tok::kw_public: 754 case tok::kw_register: 755 case tok::kw_reinterpret_cast: 756 case tok::kw_restrict: 757 case tok::kw_return: 758 case tok::kw_short: 759 case tok::kw_signed: 760 case tok::kw_sizeof: 761 case tok::kw_static: 762 case tok::kw_static_cast: 763 case tok::kw_struct: 764 case tok::kw_switch: 765 case tok::kw_template: 766 case tok::kw_this: 767 case tok::kw_throw: 768 case tok::kw_true: 769 case tok::kw_try: 770 case tok::kw_typedef: 771 case tok::kw_typeid: 772 case tok::kw_typename: 773 case tok::kw_typeof: 774 case tok::kw_union: 775 case tok::kw_unsigned: 776 case tok::kw_using: 777 case tok::kw_virtual: 778 case tok::kw_void: 779 case tok::kw_volatile: 780 case tok::kw_wchar_t: 781 case tok::kw_while: 782 case tok::kw__Bool: 783 case tok::kw__Complex: 784 case tok::kw___alignof: 785 IdentifierInfo *II = Tok.getIdentifierInfo(); 786 SelectorLoc = ConsumeToken(); 787 return II; 788 } 789} 790 791/// objc-for-collection-in: 'in' 792/// 793bool Parser::isTokIdentifier_in() const { 794 // FIXME: May have to do additional look-ahead to only allow for 795 // valid tokens following an 'in'; such as an identifier, unary operators, 796 // '[' etc. 797 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) && 798 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]); 799} 800 801/// ParseObjCTypeQualifierList - This routine parses the objective-c's type 802/// qualifier list and builds their bitmask representation in the input 803/// argument. 804/// 805/// objc-type-qualifiers: 806/// objc-type-qualifier 807/// objc-type-qualifiers objc-type-qualifier 808/// 809void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, 810 Declarator::TheContext Context) { 811 assert(Context == Declarator::ObjCParameterContext || 812 Context == Declarator::ObjCResultContext); 813 814 while (1) { 815 if (Tok.is(tok::code_completion)) { 816 Actions.CodeCompleteObjCPassingType(getCurScope(), DS, 817 Context == Declarator::ObjCParameterContext); 818 return cutOffParsing(); 819 } 820 821 if (Tok.isNot(tok::identifier)) 822 return; 823 824 const IdentifierInfo *II = Tok.getIdentifierInfo(); 825 for (unsigned i = 0; i != objc_NumQuals; ++i) { 826 if (II != ObjCTypeQuals[i]) 827 continue; 828 829 ObjCDeclSpec::ObjCDeclQualifier Qual; 830 switch (i) { 831 default: llvm_unreachable("Unknown decl qualifier"); 832 case objc_in: Qual = ObjCDeclSpec::DQ_In; break; 833 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break; 834 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break; 835 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break; 836 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break; 837 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break; 838 } 839 DS.setObjCDeclQualifier(Qual); 840 ConsumeToken(); 841 II = 0; 842 break; 843 } 844 845 // If this wasn't a recognized qualifier, bail out. 846 if (II) return; 847 } 848} 849 850/// Take all the decl attributes out of the given list and add 851/// them to the given attribute set. 852static void takeDeclAttributes(ParsedAttributes &attrs, 853 AttributeList *list) { 854 while (list) { 855 AttributeList *cur = list; 856 list = cur->getNext(); 857 858 if (!cur->isUsedAsTypeAttr()) { 859 // Clear out the next pointer. We're really completely 860 // destroying the internal invariants of the declarator here, 861 // but it doesn't matter because we're done with it. 862 cur->setNext(0); 863 attrs.add(cur); 864 } 865 } 866} 867 868/// takeDeclAttributes - Take all the decl attributes from the given 869/// declarator and add them to the given list. 870static void takeDeclAttributes(ParsedAttributes &attrs, 871 Declarator &D) { 872 // First, take ownership of all attributes. 873 attrs.getPool().takeAllFrom(D.getAttributePool()); 874 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool()); 875 876 // Now actually move the attributes over. 877 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList()); 878 takeDeclAttributes(attrs, D.getAttributes()); 879 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 880 takeDeclAttributes(attrs, 881 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs())); 882} 883 884/// objc-type-name: 885/// '(' objc-type-qualifiers[opt] type-name ')' 886/// '(' objc-type-qualifiers[opt] ')' 887/// 888ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, 889 Declarator::TheContext context, 890 ParsedAttributes *paramAttrs) { 891 assert(context == Declarator::ObjCParameterContext || 892 context == Declarator::ObjCResultContext); 893 assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext)); 894 895 assert(Tok.is(tok::l_paren) && "expected ("); 896 897 BalancedDelimiterTracker T(*this, tok::l_paren); 898 T.consumeOpen(); 899 900 SourceLocation TypeStartLoc = Tok.getLocation(); 901 ObjCDeclContextSwitch ObjCDC(*this); 902 903 // Parse type qualifiers, in, inout, etc. 904 ParseObjCTypeQualifierList(DS, context); 905 906 ParsedType Ty; 907 if (isTypeSpecifierQualifier()) { 908 // Parse an abstract declarator. 909 DeclSpec declSpec(AttrFactory); 910 declSpec.setObjCQualifiers(&DS); 911 ParseSpecifierQualifierList(declSpec); 912 declSpec.SetRangeEnd(Tok.getLocation()); 913 Declarator declarator(declSpec, context); 914 ParseDeclarator(declarator); 915 916 // If that's not invalid, extract a type. 917 if (!declarator.isInvalidType()) { 918 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator); 919 if (!type.isInvalid()) 920 Ty = type.get(); 921 922 // If we're parsing a parameter, steal all the decl attributes 923 // and add them to the decl spec. 924 if (context == Declarator::ObjCParameterContext) 925 takeDeclAttributes(*paramAttrs, declarator); 926 } 927 } else if (context == Declarator::ObjCResultContext && 928 Tok.is(tok::identifier)) { 929 if (!Ident_instancetype) 930 Ident_instancetype = PP.getIdentifierInfo("instancetype"); 931 932 if (Tok.getIdentifierInfo() == Ident_instancetype) { 933 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation()); 934 ConsumeToken(); 935 } 936 } 937 938 if (Tok.is(tok::r_paren)) 939 T.consumeClose(); 940 else if (Tok.getLocation() == TypeStartLoc) { 941 // If we didn't eat any tokens, then this isn't a type. 942 Diag(Tok, diag::err_expected_type); 943 SkipUntil(tok::r_paren); 944 } else { 945 // Otherwise, we found *something*, but didn't get a ')' in the right 946 // place. Emit an error then return what we have as the type. 947 T.consumeClose(); 948 } 949 return Ty; 950} 951 952/// objc-method-decl: 953/// objc-selector 954/// objc-keyword-selector objc-parmlist[opt] 955/// objc-type-name objc-selector 956/// objc-type-name objc-keyword-selector objc-parmlist[opt] 957/// 958/// objc-keyword-selector: 959/// objc-keyword-decl 960/// objc-keyword-selector objc-keyword-decl 961/// 962/// objc-keyword-decl: 963/// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier 964/// objc-selector ':' objc-keyword-attributes[opt] identifier 965/// ':' objc-type-name objc-keyword-attributes[opt] identifier 966/// ':' objc-keyword-attributes[opt] identifier 967/// 968/// objc-parmlist: 969/// objc-parms objc-ellipsis[opt] 970/// 971/// objc-parms: 972/// objc-parms , parameter-declaration 973/// 974/// objc-ellipsis: 975/// , ... 976/// 977/// objc-keyword-attributes: [OBJC2] 978/// __attribute__((unused)) 979/// 980Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, 981 tok::TokenKind mType, 982 tok::ObjCKeywordKind MethodImplKind, 983 bool MethodDefinition) { 984 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 985 986 if (Tok.is(tok::code_completion)) { 987 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 988 /*ReturnType=*/ ParsedType()); 989 cutOffParsing(); 990 return 0; 991 } 992 993 // Parse the return type if present. 994 ParsedType ReturnType; 995 ObjCDeclSpec DSRet; 996 if (Tok.is(tok::l_paren)) 997 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0); 998 999 // If attributes exist before the method, parse them. 1000 ParsedAttributes methodAttrs(AttrFactory); 1001 if (getLangOpts().ObjC2) 1002 MaybeParseGNUAttributes(methodAttrs); 1003 1004 if (Tok.is(tok::code_completion)) { 1005 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 1006 ReturnType); 1007 cutOffParsing(); 1008 return 0; 1009 } 1010 1011 // Now parse the selector. 1012 SourceLocation selLoc; 1013 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc); 1014 1015 // An unnamed colon is valid. 1016 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name. 1017 Diag(Tok, diag::err_expected_selector_for_method) 1018 << SourceRange(mLoc, Tok.getLocation()); 1019 // Skip until we get a ; or @. 1020 SkipUntil(tok::at, true /*StopAtSemi*/, true /*don't consume*/); 1021 return 0; 1022 } 1023 1024 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo; 1025 if (Tok.isNot(tok::colon)) { 1026 // If attributes exist after the method, parse them. 1027 if (getLangOpts().ObjC2) 1028 MaybeParseGNUAttributes(methodAttrs); 1029 1030 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent); 1031 Decl *Result 1032 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), 1033 mType, DSRet, ReturnType, 1034 selLoc, Sel, 0, 1035 CParamInfo.data(), CParamInfo.size(), 1036 methodAttrs.getList(), MethodImplKind, 1037 false, MethodDefinition); 1038 PD.complete(Result); 1039 return Result; 1040 } 1041 1042 SmallVector<IdentifierInfo *, 12> KeyIdents; 1043 SmallVector<SourceLocation, 12> KeyLocs; 1044 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos; 1045 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 1046 Scope::FunctionDeclarationScope | Scope::DeclScope); 1047 1048 AttributePool allParamAttrs(AttrFactory); 1049 while (1) { 1050 ParsedAttributes paramAttrs(AttrFactory); 1051 Sema::ObjCArgInfo ArgInfo; 1052 1053 // Each iteration parses a single keyword argument. 1054 if (Tok.isNot(tok::colon)) { 1055 Diag(Tok, diag::err_expected_colon); 1056 break; 1057 } 1058 ConsumeToken(); // Eat the ':'. 1059 1060 ArgInfo.Type = ParsedType(); 1061 if (Tok.is(tok::l_paren)) // Parse the argument type if present. 1062 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, 1063 Declarator::ObjCParameterContext, 1064 ¶mAttrs); 1065 1066 // If attributes exist before the argument name, parse them. 1067 // Regardless, collect all the attributes we've parsed so far. 1068 ArgInfo.ArgAttrs = 0; 1069 if (getLangOpts().ObjC2) { 1070 MaybeParseGNUAttributes(paramAttrs); 1071 ArgInfo.ArgAttrs = paramAttrs.getList(); 1072 } 1073 1074 // Code completion for the next piece of the selector. 1075 if (Tok.is(tok::code_completion)) { 1076 KeyIdents.push_back(SelIdent); 1077 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1078 mType == tok::minus, 1079 /*AtParameterName=*/true, 1080 ReturnType, KeyIdents); 1081 cutOffParsing(); 1082 return 0; 1083 } 1084 1085 if (Tok.isNot(tok::identifier)) { 1086 Diag(Tok, diag::err_expected_ident); // missing argument name. 1087 break; 1088 } 1089 1090 ArgInfo.Name = Tok.getIdentifierInfo(); 1091 ArgInfo.NameLoc = Tok.getLocation(); 1092 ConsumeToken(); // Eat the identifier. 1093 1094 ArgInfos.push_back(ArgInfo); 1095 KeyIdents.push_back(SelIdent); 1096 KeyLocs.push_back(selLoc); 1097 1098 // Make sure the attributes persist. 1099 allParamAttrs.takeAllFrom(paramAttrs.getPool()); 1100 1101 // Code completion for the next piece of the selector. 1102 if (Tok.is(tok::code_completion)) { 1103 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1104 mType == tok::minus, 1105 /*AtParameterName=*/false, 1106 ReturnType, KeyIdents); 1107 cutOffParsing(); 1108 return 0; 1109 } 1110 1111 // Check for another keyword selector. 1112 SelIdent = ParseObjCSelectorPiece(selLoc); 1113 if (!SelIdent && Tok.isNot(tok::colon)) 1114 break; 1115 if (!SelIdent) { 1116 SourceLocation ColonLoc = Tok.getLocation(); 1117 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) { 1118 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name; 1119 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name; 1120 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name; 1121 } 1122 } 1123 // We have a selector or a colon, continue parsing. 1124 } 1125 1126 bool isVariadic = false; 1127 bool cStyleParamWarned = false; 1128 // Parse the (optional) parameter list. 1129 while (Tok.is(tok::comma)) { 1130 ConsumeToken(); 1131 if (Tok.is(tok::ellipsis)) { 1132 isVariadic = true; 1133 ConsumeToken(); 1134 break; 1135 } 1136 if (!cStyleParamWarned) { 1137 Diag(Tok, diag::warn_cstyle_param); 1138 cStyleParamWarned = true; 1139 } 1140 DeclSpec DS(AttrFactory); 1141 ParseDeclarationSpecifiers(DS); 1142 // Parse the declarator. 1143 Declarator ParmDecl(DS, Declarator::PrototypeContext); 1144 ParseDeclarator(ParmDecl); 1145 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 1146 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 1147 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 1148 ParmDecl.getIdentifierLoc(), 1149 Param, 1150 0)); 1151 } 1152 1153 // FIXME: Add support for optional parameter list... 1154 // If attributes exist after the method, parse them. 1155 if (getLangOpts().ObjC2) 1156 MaybeParseGNUAttributes(methodAttrs); 1157 1158 if (KeyIdents.size() == 0) 1159 return 0; 1160 1161 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(), 1162 &KeyIdents[0]); 1163 Decl *Result 1164 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), 1165 mType, DSRet, ReturnType, 1166 KeyLocs, Sel, &ArgInfos[0], 1167 CParamInfo.data(), CParamInfo.size(), 1168 methodAttrs.getList(), 1169 MethodImplKind, isVariadic, MethodDefinition); 1170 1171 PD.complete(Result); 1172 return Result; 1173} 1174 1175/// objc-protocol-refs: 1176/// '<' identifier-list '>' 1177/// 1178bool Parser:: 1179ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols, 1180 SmallVectorImpl<SourceLocation> &ProtocolLocs, 1181 bool WarnOnDeclarations, 1182 SourceLocation &LAngleLoc, SourceLocation &EndLoc) { 1183 assert(Tok.is(tok::less) && "expected <"); 1184 1185 LAngleLoc = ConsumeToken(); // the "<" 1186 1187 SmallVector<IdentifierLocPair, 8> ProtocolIdents; 1188 1189 while (1) { 1190 if (Tok.is(tok::code_completion)) { 1191 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(), 1192 ProtocolIdents.size()); 1193 cutOffParsing(); 1194 return true; 1195 } 1196 1197 if (Tok.isNot(tok::identifier)) { 1198 Diag(Tok, diag::err_expected_ident); 1199 SkipUntil(tok::greater); 1200 return true; 1201 } 1202 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(), 1203 Tok.getLocation())); 1204 ProtocolLocs.push_back(Tok.getLocation()); 1205 ConsumeToken(); 1206 1207 if (Tok.isNot(tok::comma)) 1208 break; 1209 ConsumeToken(); 1210 } 1211 1212 // Consume the '>'. 1213 if (ParseGreaterThanInTemplateList(EndLoc, /*ConsumeLastToken=*/true)) 1214 return true; 1215 1216 // Convert the list of protocols identifiers into a list of protocol decls. 1217 Actions.FindProtocolDeclaration(WarnOnDeclarations, 1218 &ProtocolIdents[0], ProtocolIdents.size(), 1219 Protocols); 1220 return false; 1221} 1222 1223/// \brief Parse the Objective-C protocol qualifiers that follow a typename 1224/// in a decl-specifier-seq, starting at the '<'. 1225bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) { 1226 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'"); 1227 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C"); 1228 SourceLocation LAngleLoc, EndProtoLoc; 1229 SmallVector<Decl *, 8> ProtocolDecl; 1230 SmallVector<SourceLocation, 8> ProtocolLocs; 1231 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1232 LAngleLoc, EndProtoLoc); 1233 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1234 ProtocolLocs.data(), LAngleLoc); 1235 if (EndProtoLoc.isValid()) 1236 DS.SetRangeEnd(EndProtoLoc); 1237 return Result; 1238} 1239 1240void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, 1241 BalancedDelimiterTracker &T, 1242 SmallVectorImpl<Decl *> &AllIvarDecls, 1243 bool RBraceMissing) { 1244 if (!RBraceMissing) 1245 T.consumeClose(); 1246 1247 Actions.ActOnObjCContainerStartDefinition(interfaceDecl); 1248 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls); 1249 Actions.ActOnObjCContainerFinishDefinition(); 1250 // Call ActOnFields() even if we don't have any decls. This is useful 1251 // for code rewriting tools that need to be aware of the empty list. 1252 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, 1253 AllIvarDecls, 1254 T.getOpenLocation(), T.getCloseLocation(), 0); 1255} 1256 1257/// objc-class-instance-variables: 1258/// '{' objc-instance-variable-decl-list[opt] '}' 1259/// 1260/// objc-instance-variable-decl-list: 1261/// objc-visibility-spec 1262/// objc-instance-variable-decl ';' 1263/// ';' 1264/// objc-instance-variable-decl-list objc-visibility-spec 1265/// objc-instance-variable-decl-list objc-instance-variable-decl ';' 1266/// objc-instance-variable-decl-list ';' 1267/// 1268/// objc-visibility-spec: 1269/// @private 1270/// @protected 1271/// @public 1272/// @package [OBJC2] 1273/// 1274/// objc-instance-variable-decl: 1275/// struct-declaration 1276/// 1277void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, 1278 tok::ObjCKeywordKind visibility, 1279 SourceLocation atLoc) { 1280 assert(Tok.is(tok::l_brace) && "expected {"); 1281 SmallVector<Decl *, 32> AllIvarDecls; 1282 1283 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); 1284 ObjCDeclContextSwitch ObjCDC(*this); 1285 1286 BalancedDelimiterTracker T(*this, tok::l_brace); 1287 T.consumeOpen(); 1288 // While we still have something to read, read the instance variables. 1289 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1290 // Each iteration of this loop reads one objc-instance-variable-decl. 1291 1292 // Check for extraneous top-level semicolon. 1293 if (Tok.is(tok::semi)) { 1294 ConsumeExtraSemi(InstanceVariableList); 1295 continue; 1296 } 1297 1298 // Set the default visibility to private. 1299 if (Tok.is(tok::at)) { // parse objc-visibility-spec 1300 ConsumeToken(); // eat the @ sign 1301 1302 if (Tok.is(tok::code_completion)) { 1303 Actions.CodeCompleteObjCAtVisibility(getCurScope()); 1304 return cutOffParsing(); 1305 } 1306 1307 switch (Tok.getObjCKeywordID()) { 1308 case tok::objc_private: 1309 case tok::objc_public: 1310 case tok::objc_protected: 1311 case tok::objc_package: 1312 visibility = Tok.getObjCKeywordID(); 1313 ConsumeToken(); 1314 continue; 1315 1316 case tok::objc_end: 1317 Diag(Tok, diag::err_objc_unexpected_atend); 1318 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1)); 1319 Tok.setKind(tok::at); 1320 Tok.setLength(1); 1321 PP.EnterToken(Tok); 1322 HelperActionsForIvarDeclarations(interfaceDecl, atLoc, 1323 T, AllIvarDecls, true); 1324 return; 1325 1326 default: 1327 Diag(Tok, diag::err_objc_illegal_visibility_spec); 1328 continue; 1329 } 1330 } 1331 1332 if (Tok.is(tok::code_completion)) { 1333 Actions.CodeCompleteOrdinaryName(getCurScope(), 1334 Sema::PCC_ObjCInstanceVariableList); 1335 return cutOffParsing(); 1336 } 1337 1338 struct ObjCIvarCallback : FieldCallback { 1339 Parser &P; 1340 Decl *IDecl; 1341 tok::ObjCKeywordKind visibility; 1342 SmallVectorImpl<Decl *> &AllIvarDecls; 1343 1344 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V, 1345 SmallVectorImpl<Decl *> &AllIvarDecls) : 1346 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) { 1347 } 1348 1349 void invoke(ParsingFieldDeclarator &FD) { 1350 P.Actions.ActOnObjCContainerStartDefinition(IDecl); 1351 // Install the declarator into the interface decl. 1352 Decl *Field 1353 = P.Actions.ActOnIvar(P.getCurScope(), 1354 FD.D.getDeclSpec().getSourceRange().getBegin(), 1355 FD.D, FD.BitfieldSize, visibility); 1356 P.Actions.ActOnObjCContainerFinishDefinition(); 1357 if (Field) 1358 AllIvarDecls.push_back(Field); 1359 FD.complete(Field); 1360 } 1361 } Callback(*this, interfaceDecl, visibility, AllIvarDecls); 1362 1363 // Parse all the comma separated declarators. 1364 ParsingDeclSpec DS(*this); 1365 ParseStructDeclaration(DS, Callback); 1366 1367 if (Tok.is(tok::semi)) { 1368 ConsumeToken(); 1369 } else { 1370 Diag(Tok, diag::err_expected_semi_decl_list); 1371 // Skip to end of block or statement 1372 SkipUntil(tok::r_brace, true, true); 1373 } 1374 } 1375 HelperActionsForIvarDeclarations(interfaceDecl, atLoc, 1376 T, AllIvarDecls, false); 1377 return; 1378} 1379 1380/// objc-protocol-declaration: 1381/// objc-protocol-definition 1382/// objc-protocol-forward-reference 1383/// 1384/// objc-protocol-definition: 1385/// \@protocol identifier 1386/// objc-protocol-refs[opt] 1387/// objc-interface-decl-list 1388/// \@end 1389/// 1390/// objc-protocol-forward-reference: 1391/// \@protocol identifier-list ';' 1392/// 1393/// "\@protocol identifier ;" should be resolved as "\@protocol 1394/// identifier-list ;": objc-interface-decl-list may not start with a 1395/// semicolon in the first alternative if objc-protocol-refs are omitted. 1396Parser::DeclGroupPtrTy 1397Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, 1398 ParsedAttributes &attrs) { 1399 assert(Tok.isObjCAtKeyword(tok::objc_protocol) && 1400 "ParseObjCAtProtocolDeclaration(): Expected @protocol"); 1401 ConsumeToken(); // the "protocol" identifier 1402 1403 if (Tok.is(tok::code_completion)) { 1404 Actions.CodeCompleteObjCProtocolDecl(getCurScope()); 1405 cutOffParsing(); 1406 return DeclGroupPtrTy(); 1407 } 1408 1409 MaybeSkipAttributes(tok::objc_protocol); 1410 1411 if (Tok.isNot(tok::identifier)) { 1412 Diag(Tok, diag::err_expected_ident); // missing protocol name. 1413 return DeclGroupPtrTy(); 1414 } 1415 // Save the protocol name, then consume it. 1416 IdentifierInfo *protocolName = Tok.getIdentifierInfo(); 1417 SourceLocation nameLoc = ConsumeToken(); 1418 1419 if (Tok.is(tok::semi)) { // forward declaration of one protocol. 1420 IdentifierLocPair ProtoInfo(protocolName, nameLoc); 1421 ConsumeToken(); 1422 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1, 1423 attrs.getList()); 1424 } 1425 1426 CheckNestedObjCContexts(AtLoc); 1427 1428 if (Tok.is(tok::comma)) { // list of forward declarations. 1429 SmallVector<IdentifierLocPair, 8> ProtocolRefs; 1430 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc)); 1431 1432 // Parse the list of forward declarations. 1433 while (1) { 1434 ConsumeToken(); // the ',' 1435 if (Tok.isNot(tok::identifier)) { 1436 Diag(Tok, diag::err_expected_ident); 1437 SkipUntil(tok::semi); 1438 return DeclGroupPtrTy(); 1439 } 1440 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(), 1441 Tok.getLocation())); 1442 ConsumeToken(); // the identifier 1443 1444 if (Tok.isNot(tok::comma)) 1445 break; 1446 } 1447 // Consume the ';'. 1448 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol")) 1449 return DeclGroupPtrTy(); 1450 1451 return Actions.ActOnForwardProtocolDeclaration(AtLoc, 1452 &ProtocolRefs[0], 1453 ProtocolRefs.size(), 1454 attrs.getList()); 1455 } 1456 1457 // Last, and definitely not least, parse a protocol declaration. 1458 SourceLocation LAngleLoc, EndProtoLoc; 1459 1460 SmallVector<Decl *, 8> ProtocolRefs; 1461 SmallVector<SourceLocation, 8> ProtocolLocs; 1462 if (Tok.is(tok::less) && 1463 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, 1464 LAngleLoc, EndProtoLoc)) 1465 return DeclGroupPtrTy(); 1466 1467 Decl *ProtoType = 1468 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc, 1469 ProtocolRefs.data(), 1470 ProtocolRefs.size(), 1471 ProtocolLocs.data(), 1472 EndProtoLoc, attrs.getList()); 1473 1474 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType); 1475 return Actions.ConvertDeclToDeclGroup(ProtoType); 1476} 1477 1478/// objc-implementation: 1479/// objc-class-implementation-prologue 1480/// objc-category-implementation-prologue 1481/// 1482/// objc-class-implementation-prologue: 1483/// @implementation identifier objc-superclass[opt] 1484/// objc-class-instance-variables[opt] 1485/// 1486/// objc-category-implementation-prologue: 1487/// @implementation identifier ( identifier ) 1488Parser::DeclGroupPtrTy 1489Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { 1490 assert(Tok.isObjCAtKeyword(tok::objc_implementation) && 1491 "ParseObjCAtImplementationDeclaration(): Expected @implementation"); 1492 CheckNestedObjCContexts(AtLoc); 1493 ConsumeToken(); // the "implementation" identifier 1494 1495 // Code completion after '@implementation'. 1496 if (Tok.is(tok::code_completion)) { 1497 Actions.CodeCompleteObjCImplementationDecl(getCurScope()); 1498 cutOffParsing(); 1499 return DeclGroupPtrTy(); 1500 } 1501 1502 MaybeSkipAttributes(tok::objc_implementation); 1503 1504 if (Tok.isNot(tok::identifier)) { 1505 Diag(Tok, diag::err_expected_ident); // missing class or category name. 1506 return DeclGroupPtrTy(); 1507 } 1508 // We have a class or category name - consume it. 1509 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 1510 SourceLocation nameLoc = ConsumeToken(); // consume class or category name 1511 Decl *ObjCImpDecl = 0; 1512 1513 if (Tok.is(tok::l_paren)) { 1514 // we have a category implementation. 1515 ConsumeParen(); 1516 SourceLocation categoryLoc, rparenLoc; 1517 IdentifierInfo *categoryId = 0; 1518 1519 if (Tok.is(tok::code_completion)) { 1520 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc); 1521 cutOffParsing(); 1522 return DeclGroupPtrTy(); 1523 } 1524 1525 if (Tok.is(tok::identifier)) { 1526 categoryId = Tok.getIdentifierInfo(); 1527 categoryLoc = ConsumeToken(); 1528 } else { 1529 Diag(Tok, diag::err_expected_ident); // missing category name. 1530 return DeclGroupPtrTy(); 1531 } 1532 if (Tok.isNot(tok::r_paren)) { 1533 Diag(Tok, diag::err_expected_rparen); 1534 SkipUntil(tok::r_paren, false); // don't stop at ';' 1535 return DeclGroupPtrTy(); 1536 } 1537 rparenLoc = ConsumeParen(); 1538 if (Tok.is(tok::less)) { // we have illegal '<' try to recover 1539 Diag(Tok, diag::err_unexpected_protocol_qualifier); 1540 AttributeFactory attr; 1541 DeclSpec DS(attr); 1542 (void)ParseObjCProtocolQualifiers(DS); 1543 } 1544 ObjCImpDecl = Actions.ActOnStartCategoryImplementation( 1545 AtLoc, nameId, nameLoc, categoryId, 1546 categoryLoc); 1547 1548 } else { 1549 // We have a class implementation 1550 SourceLocation superClassLoc; 1551 IdentifierInfo *superClassId = 0; 1552 if (Tok.is(tok::colon)) { 1553 // We have a super class 1554 ConsumeToken(); 1555 if (Tok.isNot(tok::identifier)) { 1556 Diag(Tok, diag::err_expected_ident); // missing super class name. 1557 return DeclGroupPtrTy(); 1558 } 1559 superClassId = Tok.getIdentifierInfo(); 1560 superClassLoc = ConsumeToken(); // Consume super class name 1561 } 1562 ObjCImpDecl = Actions.ActOnStartClassImplementation( 1563 AtLoc, nameId, nameLoc, 1564 superClassId, superClassLoc); 1565 1566 if (Tok.is(tok::l_brace)) // we have ivars 1567 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc); 1568 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover 1569 Diag(Tok, diag::err_unexpected_protocol_qualifier); 1570 // try to recover. 1571 AttributeFactory attr; 1572 DeclSpec DS(attr); 1573 (void)ParseObjCProtocolQualifiers(DS); 1574 } 1575 } 1576 assert(ObjCImpDecl); 1577 1578 SmallVector<Decl *, 8> DeclsInGroup; 1579 1580 { 1581 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl); 1582 while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) { 1583 ParsedAttributesWithRange attrs(AttrFactory); 1584 MaybeParseCXX11Attributes(attrs); 1585 MaybeParseMicrosoftAttributes(attrs); 1586 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) { 1587 DeclGroupRef DG = DGP.get(); 1588 DeclsInGroup.append(DG.begin(), DG.end()); 1589 } 1590 } 1591 } 1592 1593 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup); 1594} 1595 1596Parser::DeclGroupPtrTy 1597Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) { 1598 assert(Tok.isObjCAtKeyword(tok::objc_end) && 1599 "ParseObjCAtEndDeclaration(): Expected @end"); 1600 ConsumeToken(); // the "end" identifier 1601 if (CurParsedObjCImpl) 1602 CurParsedObjCImpl->finish(atEnd); 1603 else 1604 // missing @implementation 1605 Diag(atEnd.getBegin(), diag::err_expected_objc_container); 1606 return DeclGroupPtrTy(); 1607} 1608 1609Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() { 1610 if (!Finished) { 1611 finish(P.Tok.getLocation()); 1612 if (P.Tok.is(tok::eof)) { 1613 P.Diag(P.Tok, diag::err_objc_missing_end) 1614 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n"); 1615 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start) 1616 << Sema::OCK_Implementation; 1617 } 1618 } 1619 P.CurParsedObjCImpl = 0; 1620 assert(LateParsedObjCMethods.empty()); 1621} 1622 1623void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) { 1624 assert(!Finished); 1625 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl); 1626 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 1627 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 1628 true/*Methods*/); 1629 1630 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd); 1631 1632 if (HasCFunction) 1633 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 1634 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 1635 false/*c-functions*/); 1636 1637 /// \brief Clear and free the cached objc methods. 1638 for (LateParsedObjCMethodContainer::iterator 1639 I = LateParsedObjCMethods.begin(), 1640 E = LateParsedObjCMethods.end(); I != E; ++I) 1641 delete *I; 1642 LateParsedObjCMethods.clear(); 1643 1644 Finished = true; 1645} 1646 1647/// compatibility-alias-decl: 1648/// @compatibility_alias alias-name class-name ';' 1649/// 1650Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) { 1651 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) && 1652 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias"); 1653 ConsumeToken(); // consume compatibility_alias 1654 if (Tok.isNot(tok::identifier)) { 1655 Diag(Tok, diag::err_expected_ident); 1656 return 0; 1657 } 1658 IdentifierInfo *aliasId = Tok.getIdentifierInfo(); 1659 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name 1660 if (Tok.isNot(tok::identifier)) { 1661 Diag(Tok, diag::err_expected_ident); 1662 return 0; 1663 } 1664 IdentifierInfo *classId = Tok.getIdentifierInfo(); 1665 SourceLocation classLoc = ConsumeToken(); // consume class-name; 1666 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 1667 "@compatibility_alias"); 1668 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc, 1669 classId, classLoc); 1670} 1671 1672/// property-synthesis: 1673/// @synthesize property-ivar-list ';' 1674/// 1675/// property-ivar-list: 1676/// property-ivar 1677/// property-ivar-list ',' property-ivar 1678/// 1679/// property-ivar: 1680/// identifier 1681/// identifier '=' identifier 1682/// 1683Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { 1684 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) && 1685 "ParseObjCPropertySynthesize(): Expected '@synthesize'"); 1686 ConsumeToken(); // consume synthesize 1687 1688 while (true) { 1689 if (Tok.is(tok::code_completion)) { 1690 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 1691 cutOffParsing(); 1692 return 0; 1693 } 1694 1695 if (Tok.isNot(tok::identifier)) { 1696 Diag(Tok, diag::err_synthesized_property_name); 1697 SkipUntil(tok::semi); 1698 return 0; 1699 } 1700 1701 IdentifierInfo *propertyIvar = 0; 1702 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1703 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1704 SourceLocation propertyIvarLoc; 1705 if (Tok.is(tok::equal)) { 1706 // property '=' ivar-name 1707 ConsumeToken(); // consume '=' 1708 1709 if (Tok.is(tok::code_completion)) { 1710 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId); 1711 cutOffParsing(); 1712 return 0; 1713 } 1714 1715 if (Tok.isNot(tok::identifier)) { 1716 Diag(Tok, diag::err_expected_ident); 1717 break; 1718 } 1719 propertyIvar = Tok.getIdentifierInfo(); 1720 propertyIvarLoc = ConsumeToken(); // consume ivar-name 1721 } 1722 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, 1723 propertyId, propertyIvar, propertyIvarLoc); 1724 if (Tok.isNot(tok::comma)) 1725 break; 1726 ConsumeToken(); // consume ',' 1727 } 1728 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize"); 1729 return 0; 1730} 1731 1732/// property-dynamic: 1733/// @dynamic property-list 1734/// 1735/// property-list: 1736/// identifier 1737/// property-list ',' identifier 1738/// 1739Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { 1740 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) && 1741 "ParseObjCPropertyDynamic(): Expected '@dynamic'"); 1742 ConsumeToken(); // consume dynamic 1743 while (true) { 1744 if (Tok.is(tok::code_completion)) { 1745 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 1746 cutOffParsing(); 1747 return 0; 1748 } 1749 1750 if (Tok.isNot(tok::identifier)) { 1751 Diag(Tok, diag::err_expected_ident); 1752 SkipUntil(tok::semi); 1753 return 0; 1754 } 1755 1756 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1757 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1758 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, 1759 propertyId, 0, SourceLocation()); 1760 1761 if (Tok.isNot(tok::comma)) 1762 break; 1763 ConsumeToken(); // consume ',' 1764 } 1765 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic"); 1766 return 0; 1767} 1768 1769/// objc-throw-statement: 1770/// throw expression[opt]; 1771/// 1772StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) { 1773 ExprResult Res; 1774 ConsumeToken(); // consume throw 1775 if (Tok.isNot(tok::semi)) { 1776 Res = ParseExpression(); 1777 if (Res.isInvalid()) { 1778 SkipUntil(tok::semi); 1779 return StmtError(); 1780 } 1781 } 1782 // consume ';' 1783 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw"); 1784 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope()); 1785} 1786 1787/// objc-synchronized-statement: 1788/// @synchronized '(' expression ')' compound-statement 1789/// 1790StmtResult 1791Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) { 1792 ConsumeToken(); // consume synchronized 1793 if (Tok.isNot(tok::l_paren)) { 1794 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized"; 1795 return StmtError(); 1796 } 1797 1798 // The operand is surrounded with parentheses. 1799 ConsumeParen(); // '(' 1800 ExprResult operand(ParseExpression()); 1801 1802 if (Tok.is(tok::r_paren)) { 1803 ConsumeParen(); // ')' 1804 } else { 1805 if (!operand.isInvalid()) 1806 Diag(Tok, diag::err_expected_rparen); 1807 1808 // Skip forward until we see a left brace, but don't consume it. 1809 SkipUntil(tok::l_brace, true, true); 1810 } 1811 1812 // Require a compound statement. 1813 if (Tok.isNot(tok::l_brace)) { 1814 if (!operand.isInvalid()) 1815 Diag(Tok, diag::err_expected_lbrace); 1816 return StmtError(); 1817 } 1818 1819 // Check the @synchronized operand now. 1820 if (!operand.isInvalid()) 1821 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take()); 1822 1823 // Parse the compound statement within a new scope. 1824 ParseScope bodyScope(this, Scope::DeclScope); 1825 StmtResult body(ParseCompoundStatementBody()); 1826 bodyScope.Exit(); 1827 1828 // If there was a semantic or parse error earlier with the 1829 // operand, fail now. 1830 if (operand.isInvalid()) 1831 return StmtError(); 1832 1833 if (body.isInvalid()) 1834 body = Actions.ActOnNullStmt(Tok.getLocation()); 1835 1836 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get()); 1837} 1838 1839/// objc-try-catch-statement: 1840/// @try compound-statement objc-catch-list[opt] 1841/// @try compound-statement objc-catch-list[opt] @finally compound-statement 1842/// 1843/// objc-catch-list: 1844/// @catch ( parameter-declaration ) compound-statement 1845/// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement 1846/// catch-parameter-declaration: 1847/// parameter-declaration 1848/// '...' [OBJC2] 1849/// 1850StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { 1851 bool catch_or_finally_seen = false; 1852 1853 ConsumeToken(); // consume try 1854 if (Tok.isNot(tok::l_brace)) { 1855 Diag(Tok, diag::err_expected_lbrace); 1856 return StmtError(); 1857 } 1858 StmtVector CatchStmts; 1859 StmtResult FinallyStmt; 1860 ParseScope TryScope(this, Scope::DeclScope); 1861 StmtResult TryBody(ParseCompoundStatementBody()); 1862 TryScope.Exit(); 1863 if (TryBody.isInvalid()) 1864 TryBody = Actions.ActOnNullStmt(Tok.getLocation()); 1865 1866 while (Tok.is(tok::at)) { 1867 // At this point, we need to lookahead to determine if this @ is the start 1868 // of an @catch or @finally. We don't want to consume the @ token if this 1869 // is an @try or @encode or something else. 1870 Token AfterAt = GetLookAheadToken(1); 1871 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) && 1872 !AfterAt.isObjCAtKeyword(tok::objc_finally)) 1873 break; 1874 1875 SourceLocation AtCatchFinallyLoc = ConsumeToken(); 1876 if (Tok.isObjCAtKeyword(tok::objc_catch)) { 1877 Decl *FirstPart = 0; 1878 ConsumeToken(); // consume catch 1879 if (Tok.is(tok::l_paren)) { 1880 ConsumeParen(); 1881 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope); 1882 if (Tok.isNot(tok::ellipsis)) { 1883 DeclSpec DS(AttrFactory); 1884 ParseDeclarationSpecifiers(DS); 1885 Declarator ParmDecl(DS, Declarator::ObjCCatchContext); 1886 ParseDeclarator(ParmDecl); 1887 1888 // Inform the actions module about the declarator, so it 1889 // gets added to the current scope. 1890 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl); 1891 } else 1892 ConsumeToken(); // consume '...' 1893 1894 SourceLocation RParenLoc; 1895 1896 if (Tok.is(tok::r_paren)) 1897 RParenLoc = ConsumeParen(); 1898 else // Skip over garbage, until we get to ')'. Eat the ')'. 1899 SkipUntil(tok::r_paren, true, false); 1900 1901 StmtResult CatchBody(true); 1902 if (Tok.is(tok::l_brace)) 1903 CatchBody = ParseCompoundStatementBody(); 1904 else 1905 Diag(Tok, diag::err_expected_lbrace); 1906 if (CatchBody.isInvalid()) 1907 CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); 1908 1909 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, 1910 RParenLoc, 1911 FirstPart, 1912 CatchBody.take()); 1913 if (!Catch.isInvalid()) 1914 CatchStmts.push_back(Catch.release()); 1915 1916 } else { 1917 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) 1918 << "@catch clause"; 1919 return StmtError(); 1920 } 1921 catch_or_finally_seen = true; 1922 } else { 1923 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?"); 1924 ConsumeToken(); // consume finally 1925 ParseScope FinallyScope(this, Scope::DeclScope); 1926 1927 StmtResult FinallyBody(true); 1928 if (Tok.is(tok::l_brace)) 1929 FinallyBody = ParseCompoundStatementBody(); 1930 else 1931 Diag(Tok, diag::err_expected_lbrace); 1932 if (FinallyBody.isInvalid()) 1933 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation()); 1934 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc, 1935 FinallyBody.take()); 1936 catch_or_finally_seen = true; 1937 break; 1938 } 1939 } 1940 if (!catch_or_finally_seen) { 1941 Diag(atLoc, diag::err_missing_catch_finally); 1942 return StmtError(); 1943 } 1944 1945 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(), 1946 CatchStmts, 1947 FinallyStmt.take()); 1948} 1949 1950/// objc-autoreleasepool-statement: 1951/// @autoreleasepool compound-statement 1952/// 1953StmtResult 1954Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) { 1955 ConsumeToken(); // consume autoreleasepool 1956 if (Tok.isNot(tok::l_brace)) { 1957 Diag(Tok, diag::err_expected_lbrace); 1958 return StmtError(); 1959 } 1960 // Enter a scope to hold everything within the compound stmt. Compound 1961 // statements can always hold declarations. 1962 ParseScope BodyScope(this, Scope::DeclScope); 1963 1964 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody()); 1965 1966 BodyScope.Exit(); 1967 if (AutoreleasePoolBody.isInvalid()) 1968 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation()); 1969 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, 1970 AutoreleasePoolBody.take()); 1971} 1972 1973/// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them 1974/// for later parsing. 1975void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) { 1976 LexedMethod* LM = new LexedMethod(this, MDecl); 1977 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM); 1978 CachedTokens &Toks = LM->Toks; 1979 // Begin by storing the '{' or 'try' or ':' token. 1980 Toks.push_back(Tok); 1981 if (Tok.is(tok::kw_try)) { 1982 ConsumeToken(); 1983 if (Tok.is(tok::colon)) { 1984 Toks.push_back(Tok); 1985 ConsumeToken(); 1986 while (Tok.isNot(tok::l_brace)) { 1987 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); 1988 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 1989 } 1990 } 1991 Toks.push_back(Tok); // also store '{' 1992 } 1993 else if (Tok.is(tok::colon)) { 1994 ConsumeToken(); 1995 while (Tok.isNot(tok::l_brace)) { 1996 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); 1997 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 1998 } 1999 Toks.push_back(Tok); // also store '{' 2000 } 2001 ConsumeBrace(); 2002 // Consume everything up to (and including) the matching right brace. 2003 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 2004 while (Tok.is(tok::kw_catch)) { 2005 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); 2006 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 2007 } 2008} 2009 2010/// objc-method-def: objc-method-proto ';'[opt] '{' body '}' 2011/// 2012Decl *Parser::ParseObjCMethodDefinition() { 2013 Decl *MDecl = ParseObjCMethodPrototype(); 2014 2015 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(), 2016 "parsing Objective-C method"); 2017 2018 // parse optional ';' 2019 if (Tok.is(tok::semi)) { 2020 if (CurParsedObjCImpl) { 2021 Diag(Tok, diag::warn_semicolon_before_method_body) 2022 << FixItHint::CreateRemoval(Tok.getLocation()); 2023 } 2024 ConsumeToken(); 2025 } 2026 2027 // We should have an opening brace now. 2028 if (Tok.isNot(tok::l_brace)) { 2029 Diag(Tok, diag::err_expected_method_body); 2030 2031 // Skip over garbage, until we get to '{'. Don't eat the '{'. 2032 SkipUntil(tok::l_brace, true, true); 2033 2034 // If we didn't find the '{', bail out. 2035 if (Tok.isNot(tok::l_brace)) 2036 return 0; 2037 } 2038 2039 if (!MDecl) { 2040 ConsumeBrace(); 2041 SkipUntil(tok::r_brace, /*StopAtSemi=*/false); 2042 return 0; 2043 } 2044 2045 // Allow the rest of sema to find private method decl implementations. 2046 Actions.AddAnyMethodToGlobalPool(MDecl); 2047 assert (CurParsedObjCImpl 2048 && "ParseObjCMethodDefinition - Method out of @implementation"); 2049 // Consume the tokens and store them for later parsing. 2050 StashAwayMethodOrFunctionBodyTokens(MDecl); 2051 return MDecl; 2052} 2053 2054StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { 2055 if (Tok.is(tok::code_completion)) { 2056 Actions.CodeCompleteObjCAtStatement(getCurScope()); 2057 cutOffParsing(); 2058 return StmtError(); 2059 } 2060 2061 if (Tok.isObjCAtKeyword(tok::objc_try)) 2062 return ParseObjCTryStmt(AtLoc); 2063 2064 if (Tok.isObjCAtKeyword(tok::objc_throw)) 2065 return ParseObjCThrowStmt(AtLoc); 2066 2067 if (Tok.isObjCAtKeyword(tok::objc_synchronized)) 2068 return ParseObjCSynchronizedStmt(AtLoc); 2069 2070 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool)) 2071 return ParseObjCAutoreleasePoolStmt(AtLoc); 2072 2073 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc)); 2074 if (Res.isInvalid()) { 2075 // If the expression is invalid, skip ahead to the next semicolon. Not 2076 // doing this opens us up to the possibility of infinite loops if 2077 // ParseExpression does not consume any tokens. 2078 SkipUntil(tok::semi); 2079 return StmtError(); 2080 } 2081 2082 // Otherwise, eat the semicolon. 2083 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 2084 return Actions.ActOnExprStmt(Res); 2085} 2086 2087ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { 2088 switch (Tok.getKind()) { 2089 case tok::code_completion: 2090 Actions.CodeCompleteObjCAtExpression(getCurScope()); 2091 cutOffParsing(); 2092 return ExprError(); 2093 2094 case tok::minus: 2095 case tok::plus: { 2096 tok::TokenKind Kind = Tok.getKind(); 2097 SourceLocation OpLoc = ConsumeToken(); 2098 2099 if (!Tok.is(tok::numeric_constant)) { 2100 const char *Symbol = 0; 2101 switch (Kind) { 2102 case tok::minus: Symbol = "-"; break; 2103 case tok::plus: Symbol = "+"; break; 2104 default: llvm_unreachable("missing unary operator case"); 2105 } 2106 Diag(Tok, diag::err_nsnumber_nonliteral_unary) 2107 << Symbol; 2108 return ExprError(); 2109 } 2110 2111 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 2112 if (Lit.isInvalid()) { 2113 return Lit; 2114 } 2115 ConsumeToken(); // Consume the literal token. 2116 2117 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take()); 2118 if (Lit.isInvalid()) 2119 return Lit; 2120 2121 return ParsePostfixExpressionSuffix( 2122 Actions.BuildObjCNumericLiteral(AtLoc, Lit.take())); 2123 } 2124 2125 case tok::string_literal: // primary-expression: string-literal 2126 case tok::wide_string_literal: 2127 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc)); 2128 2129 case tok::char_constant: 2130 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc)); 2131 2132 case tok::numeric_constant: 2133 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc)); 2134 2135 case tok::kw_true: // Objective-C++, etc. 2136 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes 2137 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true)); 2138 case tok::kw_false: // Objective-C++, etc. 2139 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no 2140 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false)); 2141 2142 case tok::l_square: 2143 // Objective-C array literal 2144 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc)); 2145 2146 case tok::l_brace: 2147 // Objective-C dictionary literal 2148 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc)); 2149 2150 case tok::l_paren: 2151 // Objective-C boxed expression 2152 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc)); 2153 2154 default: 2155 if (Tok.getIdentifierInfo() == 0) 2156 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2157 2158 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) { 2159 case tok::objc_encode: 2160 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc)); 2161 case tok::objc_protocol: 2162 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc)); 2163 case tok::objc_selector: 2164 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc)); 2165 default: { 2166 const char *str = 0; 2167 if (GetLookAheadToken(1).is(tok::l_brace)) { 2168 char ch = Tok.getIdentifierInfo()->getNameStart()[0]; 2169 str = 2170 ch == 't' ? "try" 2171 : (ch == 'f' ? "finally" 2172 : (ch == 'a' ? "autoreleasepool" : 0)); 2173 } 2174 if (str) { 2175 SourceLocation kwLoc = Tok.getLocation(); 2176 return ExprError(Diag(AtLoc, diag::err_unexpected_at) << 2177 FixItHint::CreateReplacement(kwLoc, str)); 2178 } 2179 else 2180 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2181 } 2182 } 2183 } 2184} 2185 2186/// \brief Parse the receiver of an Objective-C++ message send. 2187/// 2188/// This routine parses the receiver of a message send in 2189/// Objective-C++ either as a type or as an expression. Note that this 2190/// routine must not be called to parse a send to 'super', since it 2191/// has no way to return such a result. 2192/// 2193/// \param IsExpr Whether the receiver was parsed as an expression. 2194/// 2195/// \param TypeOrExpr If the receiver was parsed as an expression (\c 2196/// IsExpr is true), the parsed expression. If the receiver was parsed 2197/// as a type (\c IsExpr is false), the parsed type. 2198/// 2199/// \returns True if an error occurred during parsing or semantic 2200/// analysis, in which case the arguments do not have valid 2201/// values. Otherwise, returns false for a successful parse. 2202/// 2203/// objc-receiver: [C++] 2204/// 'super' [not parsed here] 2205/// expression 2206/// simple-type-specifier 2207/// typename-specifier 2208bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { 2209 InMessageExpressionRAIIObject InMessage(*this, true); 2210 2211 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 2212 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)) 2213 TryAnnotateTypeOrScopeToken(); 2214 2215 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) { 2216 // objc-receiver: 2217 // expression 2218 ExprResult Receiver = ParseExpression(); 2219 if (Receiver.isInvalid()) 2220 return true; 2221 2222 IsExpr = true; 2223 TypeOrExpr = Receiver.take(); 2224 return false; 2225 } 2226 2227 // objc-receiver: 2228 // typename-specifier 2229 // simple-type-specifier 2230 // expression (that starts with one of the above) 2231 DeclSpec DS(AttrFactory); 2232 ParseCXXSimpleTypeSpecifier(DS); 2233 2234 if (Tok.is(tok::l_paren)) { 2235 // If we see an opening parentheses at this point, we are 2236 // actually parsing an expression that starts with a 2237 // function-style cast, e.g., 2238 // 2239 // postfix-expression: 2240 // simple-type-specifier ( expression-list [opt] ) 2241 // typename-specifier ( expression-list [opt] ) 2242 // 2243 // Parse the remainder of this case, then the (optional) 2244 // postfix-expression suffix, followed by the (optional) 2245 // right-hand side of the binary expression. We have an 2246 // instance method. 2247 ExprResult Receiver = ParseCXXTypeConstructExpression(DS); 2248 if (!Receiver.isInvalid()) 2249 Receiver = ParsePostfixExpressionSuffix(Receiver.take()); 2250 if (!Receiver.isInvalid()) 2251 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma); 2252 if (Receiver.isInvalid()) 2253 return true; 2254 2255 IsExpr = true; 2256 TypeOrExpr = Receiver.take(); 2257 return false; 2258 } 2259 2260 // We have a class message. Turn the simple-type-specifier or 2261 // typename-specifier we parsed into a type and parse the 2262 // remainder of the class message. 2263 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2264 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2265 if (Type.isInvalid()) 2266 return true; 2267 2268 IsExpr = false; 2269 TypeOrExpr = Type.get().getAsOpaquePtr(); 2270 return false; 2271} 2272 2273/// \brief Determine whether the parser is currently referring to a an 2274/// Objective-C message send, using a simplified heuristic to avoid overhead. 2275/// 2276/// This routine will only return true for a subset of valid message-send 2277/// expressions. 2278bool Parser::isSimpleObjCMessageExpression() { 2279 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 && 2280 "Incorrect start for isSimpleObjCMessageExpression"); 2281 return GetLookAheadToken(1).is(tok::identifier) && 2282 GetLookAheadToken(2).is(tok::identifier); 2283} 2284 2285bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { 2286 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || 2287 InMessageExpression) 2288 return false; 2289 2290 2291 ParsedType Type; 2292 2293 if (Tok.is(tok::annot_typename)) 2294 Type = getTypeAnnotation(Tok); 2295 else if (Tok.is(tok::identifier)) 2296 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), 2297 getCurScope()); 2298 else 2299 return false; 2300 2301 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { 2302 const Token &AfterNext = GetLookAheadToken(2); 2303 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) { 2304 if (Tok.is(tok::identifier)) 2305 TryAnnotateTypeOrScopeToken(); 2306 2307 return Tok.is(tok::annot_typename); 2308 } 2309 } 2310 2311 return false; 2312} 2313 2314/// objc-message-expr: 2315/// '[' objc-receiver objc-message-args ']' 2316/// 2317/// objc-receiver: [C] 2318/// 'super' 2319/// expression 2320/// class-name 2321/// type-name 2322/// 2323ExprResult Parser::ParseObjCMessageExpression() { 2324 assert(Tok.is(tok::l_square) && "'[' expected"); 2325 SourceLocation LBracLoc = ConsumeBracket(); // consume '[' 2326 2327 if (Tok.is(tok::code_completion)) { 2328 Actions.CodeCompleteObjCMessageReceiver(getCurScope()); 2329 cutOffParsing(); 2330 return ExprError(); 2331 } 2332 2333 InMessageExpressionRAIIObject InMessage(*this, true); 2334 2335 if (getLangOpts().CPlusPlus) { 2336 // We completely separate the C and C++ cases because C++ requires 2337 // more complicated (read: slower) parsing. 2338 2339 // Handle send to super. 2340 // FIXME: This doesn't benefit from the same typo-correction we 2341 // get in Objective-C. 2342 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && 2343 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) 2344 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 2345 ParsedType(), 0); 2346 2347 // Parse the receiver, which is either a type or an expression. 2348 bool IsExpr; 2349 void *TypeOrExpr = NULL; 2350 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { 2351 SkipUntil(tok::r_square); 2352 return ExprError(); 2353 } 2354 2355 if (IsExpr) 2356 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2357 ParsedType(), 2358 static_cast<Expr*>(TypeOrExpr)); 2359 2360 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2361 ParsedType::getFromOpaquePtr(TypeOrExpr), 2362 0); 2363 } 2364 2365 if (Tok.is(tok::identifier)) { 2366 IdentifierInfo *Name = Tok.getIdentifierInfo(); 2367 SourceLocation NameLoc = Tok.getLocation(); 2368 ParsedType ReceiverType; 2369 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc, 2370 Name == Ident_super, 2371 NextToken().is(tok::period), 2372 ReceiverType)) { 2373 case Sema::ObjCSuperMessage: 2374 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 2375 ParsedType(), 0); 2376 2377 case Sema::ObjCClassMessage: 2378 if (!ReceiverType) { 2379 SkipUntil(tok::r_square); 2380 return ExprError(); 2381 } 2382 2383 ConsumeToken(); // the type name 2384 2385 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2386 ReceiverType, 0); 2387 2388 case Sema::ObjCInstanceMessage: 2389 // Fall through to parse an expression. 2390 break; 2391 } 2392 } 2393 2394 // Otherwise, an arbitrary expression can be the receiver of a send. 2395 ExprResult Res(ParseExpression()); 2396 if (Res.isInvalid()) { 2397 SkipUntil(tok::r_square); 2398 return Res; 2399 } 2400 2401 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2402 ParsedType(), Res.take()); 2403} 2404 2405/// \brief Parse the remainder of an Objective-C message following the 2406/// '[' objc-receiver. 2407/// 2408/// This routine handles sends to super, class messages (sent to a 2409/// class name), and instance messages (sent to an object), and the 2410/// target is represented by \p SuperLoc, \p ReceiverType, or \p 2411/// ReceiverExpr, respectively. Only one of these parameters may have 2412/// a valid value. 2413/// 2414/// \param LBracLoc The location of the opening '['. 2415/// 2416/// \param SuperLoc If this is a send to 'super', the location of the 2417/// 'super' keyword that indicates a send to the superclass. 2418/// 2419/// \param ReceiverType If this is a class message, the type of the 2420/// class we are sending a message to. 2421/// 2422/// \param ReceiverExpr If this is an instance message, the expression 2423/// used to compute the receiver object. 2424/// 2425/// objc-message-args: 2426/// objc-selector 2427/// objc-keywordarg-list 2428/// 2429/// objc-keywordarg-list: 2430/// objc-keywordarg 2431/// objc-keywordarg-list objc-keywordarg 2432/// 2433/// objc-keywordarg: 2434/// selector-name[opt] ':' objc-keywordexpr 2435/// 2436/// objc-keywordexpr: 2437/// nonempty-expr-list 2438/// 2439/// nonempty-expr-list: 2440/// assignment-expression 2441/// nonempty-expr-list , assignment-expression 2442/// 2443ExprResult 2444Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, 2445 SourceLocation SuperLoc, 2446 ParsedType ReceiverType, 2447 ExprArg ReceiverExpr) { 2448 InMessageExpressionRAIIObject InMessage(*this, true); 2449 2450 if (Tok.is(tok::code_completion)) { 2451 if (SuperLoc.isValid()) 2452 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None, 2453 false); 2454 else if (ReceiverType) 2455 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None, 2456 false); 2457 else 2458 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2459 None, false); 2460 cutOffParsing(); 2461 return ExprError(); 2462 } 2463 2464 // Parse objc-selector 2465 SourceLocation Loc; 2466 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); 2467 2468 SmallVector<IdentifierInfo *, 12> KeyIdents; 2469 SmallVector<SourceLocation, 12> KeyLocs; 2470 ExprVector KeyExprs; 2471 2472 if (Tok.is(tok::colon)) { 2473 while (1) { 2474 // Each iteration parses a single keyword argument. 2475 KeyIdents.push_back(selIdent); 2476 KeyLocs.push_back(Loc); 2477 2478 if (Tok.isNot(tok::colon)) { 2479 Diag(Tok, diag::err_expected_colon); 2480 // We must manually skip to a ']', otherwise the expression skipper will 2481 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2482 // the enclosing expression. 2483 SkipUntil(tok::r_square); 2484 return ExprError(); 2485 } 2486 2487 ConsumeToken(); // Eat the ':'. 2488 /// Parse the expression after ':' 2489 2490 if (Tok.is(tok::code_completion)) { 2491 if (SuperLoc.isValid()) 2492 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2493 KeyIdents, 2494 /*AtArgumentEpression=*/true); 2495 else if (ReceiverType) 2496 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2497 KeyIdents, 2498 /*AtArgumentEpression=*/true); 2499 else 2500 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2501 KeyIdents, 2502 /*AtArgumentEpression=*/true); 2503 2504 cutOffParsing(); 2505 return ExprError(); 2506 } 2507 2508 ExprResult Expr; 2509 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 2510 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2511 Expr = ParseBraceInitializer(); 2512 } else 2513 Expr = ParseAssignmentExpression(); 2514 2515 ExprResult Res(Expr); 2516 if (Res.isInvalid()) { 2517 // We must manually skip to a ']', otherwise the expression skipper will 2518 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2519 // the enclosing expression. 2520 SkipUntil(tok::r_square); 2521 return Res; 2522 } 2523 2524 // We have a valid expression. 2525 KeyExprs.push_back(Res.release()); 2526 2527 // Code completion after each argument. 2528 if (Tok.is(tok::code_completion)) { 2529 if (SuperLoc.isValid()) 2530 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2531 KeyIdents, 2532 /*AtArgumentEpression=*/false); 2533 else if (ReceiverType) 2534 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2535 KeyIdents, 2536 /*AtArgumentEpression=*/false); 2537 else 2538 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2539 KeyIdents, 2540 /*AtArgumentEpression=*/false); 2541 cutOffParsing(); 2542 return ExprError(); 2543 } 2544 2545 // Check for another keyword selector. 2546 selIdent = ParseObjCSelectorPiece(Loc); 2547 if (!selIdent && Tok.isNot(tok::colon)) 2548 break; 2549 // We have a selector or a colon, continue parsing. 2550 } 2551 // Parse the, optional, argument list, comma separated. 2552 while (Tok.is(tok::comma)) { 2553 SourceLocation commaLoc = ConsumeToken(); // Eat the ','. 2554 /// Parse the expression after ',' 2555 ExprResult Res(ParseAssignmentExpression()); 2556 if (Res.isInvalid()) { 2557 if (Tok.is(tok::colon)) { 2558 Diag(commaLoc, diag::note_extra_comma_message_arg) << 2559 FixItHint::CreateRemoval(commaLoc); 2560 } 2561 // We must manually skip to a ']', otherwise the expression skipper will 2562 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2563 // the enclosing expression. 2564 SkipUntil(tok::r_square); 2565 return Res; 2566 } 2567 2568 // We have a valid expression. 2569 KeyExprs.push_back(Res.release()); 2570 } 2571 } else if (!selIdent) { 2572 Diag(Tok, diag::err_expected_ident); // missing selector name. 2573 2574 // We must manually skip to a ']', otherwise the expression skipper will 2575 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2576 // the enclosing expression. 2577 SkipUntil(tok::r_square); 2578 return ExprError(); 2579 } 2580 2581 if (Tok.isNot(tok::r_square)) { 2582 if (Tok.is(tok::identifier)) 2583 Diag(Tok, diag::err_expected_colon); 2584 else 2585 Diag(Tok, diag::err_expected_rsquare); 2586 // We must manually skip to a ']', otherwise the expression skipper will 2587 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2588 // the enclosing expression. 2589 SkipUntil(tok::r_square); 2590 return ExprError(); 2591 } 2592 2593 SourceLocation RBracLoc = ConsumeBracket(); // consume ']' 2594 2595 unsigned nKeys = KeyIdents.size(); 2596 if (nKeys == 0) { 2597 KeyIdents.push_back(selIdent); 2598 KeyLocs.push_back(Loc); 2599 } 2600 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]); 2601 2602 if (SuperLoc.isValid()) 2603 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel, 2604 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 2605 else if (ReceiverType) 2606 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel, 2607 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 2608 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel, 2609 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 2610} 2611 2612ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { 2613 ExprResult Res(ParseStringLiteralExpression()); 2614 if (Res.isInvalid()) return Res; 2615 2616 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string 2617 // expressions. At this point, we know that the only valid thing that starts 2618 // with '@' is an @"". 2619 SmallVector<SourceLocation, 4> AtLocs; 2620 ExprVector AtStrings; 2621 AtLocs.push_back(AtLoc); 2622 AtStrings.push_back(Res.release()); 2623 2624 while (Tok.is(tok::at)) { 2625 AtLocs.push_back(ConsumeToken()); // eat the @. 2626 2627 // Invalid unless there is a string literal. 2628 if (!isTokenStringLiteral()) 2629 return ExprError(Diag(Tok, diag::err_objc_concat_string)); 2630 2631 ExprResult Lit(ParseStringLiteralExpression()); 2632 if (Lit.isInvalid()) 2633 return Lit; 2634 2635 AtStrings.push_back(Lit.release()); 2636 } 2637 2638 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(), 2639 AtStrings.size()); 2640} 2641 2642/// ParseObjCBooleanLiteral - 2643/// objc-scalar-literal : '@' boolean-keyword 2644/// ; 2645/// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no' 2646/// ; 2647ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, 2648 bool ArgValue) { 2649 SourceLocation EndLoc = ConsumeToken(); // consume the keyword. 2650 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue); 2651} 2652 2653/// ParseObjCCharacterLiteral - 2654/// objc-scalar-literal : '@' character-literal 2655/// ; 2656ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) { 2657 ExprResult Lit(Actions.ActOnCharacterConstant(Tok)); 2658 if (Lit.isInvalid()) { 2659 return Lit; 2660 } 2661 ConsumeToken(); // Consume the literal token. 2662 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()); 2663} 2664 2665/// ParseObjCNumericLiteral - 2666/// objc-scalar-literal : '@' scalar-literal 2667/// ; 2668/// scalar-literal : | numeric-constant /* any numeric constant. */ 2669/// ; 2670ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) { 2671 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 2672 if (Lit.isInvalid()) { 2673 return Lit; 2674 } 2675 ConsumeToken(); // Consume the literal token. 2676 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()); 2677} 2678 2679/// ParseObjCBoxedExpr - 2680/// objc-box-expression: 2681/// @( assignment-expression ) 2682ExprResult 2683Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) { 2684 if (Tok.isNot(tok::l_paren)) 2685 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@"); 2686 2687 BalancedDelimiterTracker T(*this, tok::l_paren); 2688 T.consumeOpen(); 2689 ExprResult ValueExpr(ParseAssignmentExpression()); 2690 if (T.consumeClose()) 2691 return ExprError(); 2692 2693 if (ValueExpr.isInvalid()) 2694 return ExprError(); 2695 2696 // Wrap the sub-expression in a parenthesized expression, to distinguish 2697 // a boxed expression from a literal. 2698 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation(); 2699 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take()); 2700 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc), 2701 ValueExpr.take()); 2702} 2703 2704ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) { 2705 ExprVector ElementExprs; // array elements. 2706 ConsumeBracket(); // consume the l_square. 2707 2708 while (Tok.isNot(tok::r_square)) { 2709 // Parse list of array element expressions (all must be id types). 2710 ExprResult Res(ParseAssignmentExpression()); 2711 if (Res.isInvalid()) { 2712 // We must manually skip to a ']', otherwise the expression skipper will 2713 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2714 // the enclosing expression. 2715 SkipUntil(tok::r_square); 2716 return Res; 2717 } 2718 2719 // Parse the ellipsis that indicates a pack expansion. 2720 if (Tok.is(tok::ellipsis)) 2721 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); 2722 if (Res.isInvalid()) 2723 return true; 2724 2725 ElementExprs.push_back(Res.release()); 2726 2727 if (Tok.is(tok::comma)) 2728 ConsumeToken(); // Eat the ','. 2729 else if (Tok.isNot(tok::r_square)) 2730 return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma)); 2731 } 2732 SourceLocation EndLoc = ConsumeBracket(); // location of ']' 2733 MultiExprArg Args(ElementExprs); 2734 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args); 2735} 2736 2737ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { 2738 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements. 2739 ConsumeBrace(); // consume the l_square. 2740 while (Tok.isNot(tok::r_brace)) { 2741 // Parse the comma separated key : value expressions. 2742 ExprResult KeyExpr; 2743 { 2744 ColonProtectionRAIIObject X(*this); 2745 KeyExpr = ParseAssignmentExpression(); 2746 if (KeyExpr.isInvalid()) { 2747 // We must manually skip to a '}', otherwise the expression skipper will 2748 // stop at the '}' when it skips to the ';'. We want it to skip beyond 2749 // the enclosing expression. 2750 SkipUntil(tok::r_brace); 2751 return KeyExpr; 2752 } 2753 } 2754 2755 if (Tok.is(tok::colon)) { 2756 ConsumeToken(); 2757 } else { 2758 Diag(Tok, diag::err_expected_colon); 2759 SkipUntil(tok::r_brace); 2760 return ExprError(); 2761 } 2762 2763 ExprResult ValueExpr(ParseAssignmentExpression()); 2764 if (ValueExpr.isInvalid()) { 2765 // We must manually skip to a '}', otherwise the expression skipper will 2766 // stop at the '}' when it skips to the ';'. We want it to skip beyond 2767 // the enclosing expression. 2768 SkipUntil(tok::r_brace); 2769 return ValueExpr; 2770 } 2771 2772 // Parse the ellipsis that designates this as a pack expansion. 2773 SourceLocation EllipsisLoc; 2774 if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus) 2775 EllipsisLoc = ConsumeToken(); 2776 2777 // We have a valid expression. Collect it in a vector so we can 2778 // build the argument list. 2779 ObjCDictionaryElement Element = { 2780 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None 2781 }; 2782 Elements.push_back(Element); 2783 2784 if (Tok.is(tok::comma)) 2785 ConsumeToken(); // Eat the ','. 2786 else if (Tok.isNot(tok::r_brace)) 2787 return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma)); 2788 } 2789 SourceLocation EndLoc = ConsumeBrace(); 2790 2791 // Create the ObjCDictionaryLiteral. 2792 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc), 2793 Elements.data(), Elements.size()); 2794} 2795 2796/// objc-encode-expression: 2797/// \@encode ( type-name ) 2798ExprResult 2799Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) { 2800 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!"); 2801 2802 SourceLocation EncLoc = ConsumeToken(); 2803 2804 if (Tok.isNot(tok::l_paren)) 2805 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode"); 2806 2807 BalancedDelimiterTracker T(*this, tok::l_paren); 2808 T.consumeOpen(); 2809 2810 TypeResult Ty = ParseTypeName(); 2811 2812 T.consumeClose(); 2813 2814 if (Ty.isInvalid()) 2815 return ExprError(); 2816 2817 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(), 2818 Ty.get(), T.getCloseLocation()); 2819} 2820 2821/// objc-protocol-expression 2822/// \@protocol ( protocol-name ) 2823ExprResult 2824Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) { 2825 SourceLocation ProtoLoc = ConsumeToken(); 2826 2827 if (Tok.isNot(tok::l_paren)) 2828 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol"); 2829 2830 BalancedDelimiterTracker T(*this, tok::l_paren); 2831 T.consumeOpen(); 2832 2833 if (Tok.isNot(tok::identifier)) 2834 return ExprError(Diag(Tok, diag::err_expected_ident)); 2835 2836 IdentifierInfo *protocolId = Tok.getIdentifierInfo(); 2837 SourceLocation ProtoIdLoc = ConsumeToken(); 2838 2839 T.consumeClose(); 2840 2841 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc, 2842 T.getOpenLocation(), ProtoIdLoc, 2843 T.getCloseLocation()); 2844} 2845 2846/// objc-selector-expression 2847/// @selector '(' objc-keyword-selector ')' 2848ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { 2849 SourceLocation SelectorLoc = ConsumeToken(); 2850 2851 if (Tok.isNot(tok::l_paren)) 2852 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector"); 2853 2854 SmallVector<IdentifierInfo *, 12> KeyIdents; 2855 SourceLocation sLoc; 2856 2857 BalancedDelimiterTracker T(*this, tok::l_paren); 2858 T.consumeOpen(); 2859 2860 if (Tok.is(tok::code_completion)) { 2861 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); 2862 cutOffParsing(); 2863 return ExprError(); 2864 } 2865 2866 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); 2867 if (!SelIdent && // missing selector name. 2868 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 2869 return ExprError(Diag(Tok, diag::err_expected_ident)); 2870 2871 KeyIdents.push_back(SelIdent); 2872 unsigned nColons = 0; 2873 if (Tok.isNot(tok::r_paren)) { 2874 while (1) { 2875 if (Tok.is(tok::coloncolon)) { // Handle :: in C++. 2876 ++nColons; 2877 KeyIdents.push_back(0); 2878 } else if (Tok.isNot(tok::colon)) 2879 return ExprError(Diag(Tok, diag::err_expected_colon)); 2880 2881 ++nColons; 2882 ConsumeToken(); // Eat the ':' or '::'. 2883 if (Tok.is(tok::r_paren)) 2884 break; 2885 2886 if (Tok.is(tok::code_completion)) { 2887 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); 2888 cutOffParsing(); 2889 return ExprError(); 2890 } 2891 2892 // Check for another keyword selector. 2893 SourceLocation Loc; 2894 SelIdent = ParseObjCSelectorPiece(Loc); 2895 KeyIdents.push_back(SelIdent); 2896 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 2897 break; 2898 } 2899 } 2900 T.consumeClose(); 2901 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]); 2902 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc, 2903 T.getOpenLocation(), 2904 T.getCloseLocation()); 2905 } 2906 2907void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { 2908 // MCDecl might be null due to error in method or c-function prototype, etc. 2909 Decl *MCDecl = LM.D; 2910 bool skip = MCDecl && 2911 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) || 2912 (!parseMethod && Actions.isObjCMethodDecl(MCDecl))); 2913 if (skip) 2914 return; 2915 2916 // Save the current token position. 2917 SourceLocation OrigLoc = Tok.getLocation(); 2918 2919 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!"); 2920 // Append the current token at the end of the new token stream so that it 2921 // doesn't get lost. 2922 LM.Toks.push_back(Tok); 2923 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false); 2924 2925 // Consume the previously pushed token. 2926 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 2927 2928 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || 2929 Tok.is(tok::colon)) && 2930 "Inline objective-c method not starting with '{' or 'try' or ':'"); 2931 // Enter a scope for the method or c-fucntion body. 2932 ParseScope BodyScope(this, 2933 parseMethod 2934 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope 2935 : Scope::FnScope|Scope::DeclScope); 2936 2937 // Tell the actions module that we have entered a method or c-function definition 2938 // with the specified Declarator for the method/function. 2939 if (parseMethod) 2940 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl); 2941 else 2942 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl); 2943 if (Tok.is(tok::kw_try)) 2944 MCDecl = ParseFunctionTryBlock(MCDecl, BodyScope); 2945 else { 2946 if (Tok.is(tok::colon)) 2947 ParseConstructorInitializer(MCDecl); 2948 MCDecl = ParseFunctionStatementBody(MCDecl, BodyScope); 2949 } 2950 2951 if (Tok.getLocation() != OrigLoc) { 2952 // Due to parsing error, we either went over the cached tokens or 2953 // there are still cached tokens left. If it's the latter case skip the 2954 // leftover tokens. 2955 // Since this is an uncommon situation that should be avoided, use the 2956 // expensive isBeforeInTranslationUnit call. 2957 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 2958 OrigLoc)) 2959 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof)) 2960 ConsumeAnyToken(); 2961 } 2962 2963 return; 2964} 2965