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