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