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