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