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