1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Objective-C portions of the Parser interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Parse/ParseDiagnostic.h" 15 #include "clang/Parse/Parser.h" 16 #include "RAIIObjectsForParser.h" 17 #include "clang/Sema/DeclSpec.h" 18 #include "clang/Sema/PrettyDeclStackTrace.h" 19 #include "clang/Sema/Scope.h" 20 #include "llvm/ADT/SmallVector.h" 21 using namespace clang; 22 23 24 /// ParseObjCAtDirectives - Handle parts of the external-declaration production: 25 /// external-declaration: [C99 6.9] 26 /// [OBJC] objc-class-definition 27 /// [OBJC] objc-class-declaration 28 /// [OBJC] objc-alias-declaration 29 /// [OBJC] objc-protocol-definition 30 /// [OBJC] objc-method-definition 31 /// [OBJC] '@' 'end' 32 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() { 33 SourceLocation AtLoc = ConsumeToken(); // the "@" 34 35 if (Tok.is(tok::code_completion)) { 36 Actions.CodeCompleteObjCAtDirective(getCurScope()); 37 cutOffParsing(); 38 return DeclGroupPtrTy(); 39 } 40 41 Decl *SingleDecl = 0; 42 switch (Tok.getObjCKeywordID()) { 43 case tok::objc_class: 44 return ParseObjCAtClassDeclaration(AtLoc); 45 case tok::objc_interface: { 46 ParsedAttributes attrs(AttrFactory); 47 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs); 48 break; 49 } 50 case tok::objc_protocol: { 51 ParsedAttributes attrs(AttrFactory); 52 return ParseObjCAtProtocolDeclaration(AtLoc, attrs); 53 } 54 case tok::objc_implementation: 55 return ParseObjCAtImplementationDeclaration(AtLoc); 56 case tok::objc_end: 57 return ParseObjCAtEndDeclaration(AtLoc); 58 case tok::objc_compatibility_alias: 59 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc); 60 break; 61 case tok::objc_synthesize: 62 SingleDecl = ParseObjCPropertySynthesize(AtLoc); 63 break; 64 case tok::objc_dynamic: 65 SingleDecl = ParseObjCPropertyDynamic(AtLoc); 66 break; 67 case tok::objc___experimental_modules_import: 68 if (getLangOpts().Modules) 69 return ParseModuleImport(AtLoc); 70 71 // Fall through 72 73 default: 74 Diag(AtLoc, diag::err_unexpected_at); 75 SkipUntil(tok::semi); 76 SingleDecl = 0; 77 break; 78 } 79 return Actions.ConvertDeclToDeclGroup(SingleDecl); 80 } 81 82 /// 83 /// objc-class-declaration: 84 /// '@' 'class' identifier-list ';' 85 /// 86 Parser::DeclGroupPtrTy 87 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { 88 ConsumeToken(); // the identifier "class" 89 SmallVector<IdentifierInfo *, 8> ClassNames; 90 SmallVector<SourceLocation, 8> ClassLocs; 91 92 93 while (1) { 94 if (Tok.isNot(tok::identifier)) { 95 Diag(Tok, diag::err_expected_ident); 96 SkipUntil(tok::semi); 97 return Actions.ConvertDeclToDeclGroup(0); 98 } 99 ClassNames.push_back(Tok.getIdentifierInfo()); 100 ClassLocs.push_back(Tok.getLocation()); 101 ConsumeToken(); 102 103 if (Tok.isNot(tok::comma)) 104 break; 105 106 ConsumeToken(); 107 } 108 109 // Consume the ';'. 110 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class")) 111 return Actions.ConvertDeclToDeclGroup(0); 112 113 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(), 114 ClassLocs.data(), 115 ClassNames.size()); 116 } 117 118 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc) 119 { 120 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind(); 121 if (ock == Sema::OCK_None) 122 return; 123 124 Decl *Decl = Actions.getObjCDeclContext(); 125 if (CurParsedObjCImpl) { 126 CurParsedObjCImpl->finish(AtLoc); 127 } else { 128 Actions.ActOnAtEnd(getCurScope(), AtLoc); 129 } 130 Diag(AtLoc, diag::err_objc_missing_end) 131 << FixItHint::CreateInsertion(AtLoc, "@end\n"); 132 if (Decl) 133 Diag(Decl->getLocStart(), diag::note_objc_container_start) 134 << (int) ock; 135 } 136 137 /// 138 /// objc-interface: 139 /// objc-class-interface-attributes[opt] objc-class-interface 140 /// objc-category-interface 141 /// 142 /// objc-class-interface: 143 /// '@' 'interface' identifier objc-superclass[opt] 144 /// objc-protocol-refs[opt] 145 /// objc-class-instance-variables[opt] 146 /// objc-interface-decl-list 147 /// @end 148 /// 149 /// objc-category-interface: 150 /// '@' 'interface' identifier '(' identifier[opt] ')' 151 /// objc-protocol-refs[opt] 152 /// objc-interface-decl-list 153 /// @end 154 /// 155 /// objc-superclass: 156 /// ':' identifier 157 /// 158 /// objc-class-interface-attributes: 159 /// __attribute__((visibility("default"))) 160 /// __attribute__((visibility("hidden"))) 161 /// __attribute__((deprecated)) 162 /// __attribute__((unavailable)) 163 /// __attribute__((objc_exception)) - used by NSException on 64-bit 164 /// __attribute__((objc_root_class)) 165 /// 166 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, 167 ParsedAttributes &attrs) { 168 assert(Tok.isObjCAtKeyword(tok::objc_interface) && 169 "ParseObjCAtInterfaceDeclaration(): Expected @interface"); 170 CheckNestedObjCContexts(AtLoc); 171 ConsumeToken(); // the "interface" identifier 172 173 // Code completion after '@interface'. 174 if (Tok.is(tok::code_completion)) { 175 Actions.CodeCompleteObjCInterfaceDecl(getCurScope()); 176 cutOffParsing(); 177 return 0; 178 } 179 180 if (Tok.isNot(tok::identifier)) { 181 Diag(Tok, diag::err_expected_ident); // missing class or category name. 182 return 0; 183 } 184 185 // We have a class or category name - consume it. 186 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 187 SourceLocation nameLoc = ConsumeToken(); 188 if (Tok.is(tok::l_paren) && 189 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. 190 191 BalancedDelimiterTracker T(*this, tok::l_paren); 192 T.consumeOpen(); 193 194 SourceLocation categoryLoc; 195 IdentifierInfo *categoryId = 0; 196 if (Tok.is(tok::code_completion)) { 197 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc); 198 cutOffParsing(); 199 return 0; 200 } 201 202 // For ObjC2, the category name is optional (not an error). 203 if (Tok.is(tok::identifier)) { 204 categoryId = Tok.getIdentifierInfo(); 205 categoryLoc = ConsumeToken(); 206 } 207 else if (!getLangOpts().ObjC2) { 208 Diag(Tok, diag::err_expected_ident); // missing category name. 209 return 0; 210 } 211 212 T.consumeClose(); 213 if (T.getCloseLocation().isInvalid()) 214 return 0; 215 216 if (!attrs.empty()) { // categories don't support attributes. 217 Diag(nameLoc, diag::err_objc_no_attributes_on_category); 218 attrs.clear(); 219 } 220 221 // Next, we need to check for any protocol references. 222 SourceLocation LAngleLoc, EndProtoLoc; 223 SmallVector<Decl *, 8> ProtocolRefs; 224 SmallVector<SourceLocation, 8> ProtocolLocs; 225 if (Tok.is(tok::less) && 226 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, 227 LAngleLoc, EndProtoLoc)) 228 return 0; 229 230 Decl *CategoryType = 231 Actions.ActOnStartCategoryInterface(AtLoc, 232 nameId, nameLoc, 233 categoryId, categoryLoc, 234 ProtocolRefs.data(), 235 ProtocolRefs.size(), 236 ProtocolLocs.data(), 237 EndProtoLoc); 238 239 if (Tok.is(tok::l_brace)) 240 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc); 241 242 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType); 243 return CategoryType; 244 } 245 // Parse a class interface. 246 IdentifierInfo *superClassId = 0; 247 SourceLocation superClassLoc; 248 249 if (Tok.is(tok::colon)) { // a super class is specified. 250 ConsumeToken(); 251 252 // Code completion of superclass names. 253 if (Tok.is(tok::code_completion)) { 254 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc); 255 cutOffParsing(); 256 return 0; 257 } 258 259 if (Tok.isNot(tok::identifier)) { 260 Diag(Tok, diag::err_expected_ident); // missing super class name. 261 return 0; 262 } 263 superClassId = Tok.getIdentifierInfo(); 264 superClassLoc = ConsumeToken(); 265 } 266 // Next, we need to check for any protocol references. 267 SmallVector<Decl *, 8> ProtocolRefs; 268 SmallVector<SourceLocation, 8> ProtocolLocs; 269 SourceLocation LAngleLoc, EndProtoLoc; 270 if (Tok.is(tok::less) && 271 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, 272 LAngleLoc, EndProtoLoc)) 273 return 0; 274 275 Decl *ClsType = 276 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc, 277 superClassId, superClassLoc, 278 ProtocolRefs.data(), ProtocolRefs.size(), 279 ProtocolLocs.data(), 280 EndProtoLoc, attrs.getList()); 281 282 if (Tok.is(tok::l_brace)) 283 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc); 284 285 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType); 286 return ClsType; 287 } 288 289 /// The Objective-C property callback. This should be defined where 290 /// it's used, but instead it's been lifted to here to support VS2005. 291 struct Parser::ObjCPropertyCallback : FieldCallback { 292 private: 293 virtual void anchor(); 294 public: 295 Parser &P; 296 SmallVectorImpl<Decl *> &Props; 297 ObjCDeclSpec &OCDS; 298 SourceLocation AtLoc; 299 SourceLocation LParenLoc; 300 tok::ObjCKeywordKind MethodImplKind; 301 302 ObjCPropertyCallback(Parser &P, 303 SmallVectorImpl<Decl *> &Props, 304 ObjCDeclSpec &OCDS, SourceLocation AtLoc, 305 SourceLocation LParenLoc, 306 tok::ObjCKeywordKind MethodImplKind) : 307 P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc), 308 MethodImplKind(MethodImplKind) { 309 } 310 311 Decl *invoke(ParsingFieldDeclarator &FD) { 312 if (FD.D.getIdentifier() == 0) { 313 P.Diag(AtLoc, diag::err_objc_property_requires_field_name) 314 << FD.D.getSourceRange(); 315 return 0; 316 } 317 if (FD.BitfieldSize) { 318 P.Diag(AtLoc, diag::err_objc_property_bitfield) 319 << FD.D.getSourceRange(); 320 return 0; 321 } 322 323 // Install the property declarator into interfaceDecl. 324 IdentifierInfo *SelName = 325 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier(); 326 327 Selector GetterSel = 328 P.PP.getSelectorTable().getNullarySelector(SelName); 329 IdentifierInfo *SetterName = OCDS.getSetterName(); 330 Selector SetterSel; 331 if (SetterName) 332 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName); 333 else 334 SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(), 335 P.PP.getSelectorTable(), 336 FD.D.getIdentifier()); 337 bool isOverridingProperty = false; 338 Decl *Property = 339 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc, 340 FD, OCDS, 341 GetterSel, SetterSel, 342 &isOverridingProperty, 343 MethodImplKind); 344 if (!isOverridingProperty) 345 Props.push_back(Property); 346 347 FD.complete(Property); 348 return 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 1036 while (1) { 1037 ParsedAttributes paramAttrs(AttrFactory); 1038 Sema::ObjCArgInfo ArgInfo; 1039 1040 // Each iteration parses a single keyword argument. 1041 if (Tok.isNot(tok::colon)) { 1042 Diag(Tok, diag::err_expected_colon); 1043 break; 1044 } 1045 ConsumeToken(); // Eat the ':'. 1046 1047 ArgInfo.Type = ParsedType(); 1048 if (Tok.is(tok::l_paren)) // Parse the argument type if present. 1049 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, 1050 Declarator::ObjCParameterContext, 1051 ¶mAttrs); 1052 1053 // If attributes exist before the argument name, parse them. 1054 // Regardless, collect all the attributes we've parsed so far. 1055 ArgInfo.ArgAttrs = 0; 1056 if (getLangOpts().ObjC2) { 1057 MaybeParseGNUAttributes(paramAttrs); 1058 ArgInfo.ArgAttrs = paramAttrs.getList(); 1059 } 1060 1061 // Code completion for the next piece of the selector. 1062 if (Tok.is(tok::code_completion)) { 1063 KeyIdents.push_back(SelIdent); 1064 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1065 mType == tok::minus, 1066 /*AtParameterName=*/true, 1067 ReturnType, 1068 KeyIdents.data(), 1069 KeyIdents.size()); 1070 cutOffParsing(); 1071 return 0; 1072 } 1073 1074 if (Tok.isNot(tok::identifier)) { 1075 Diag(Tok, diag::err_expected_ident); // missing argument name. 1076 break; 1077 } 1078 1079 ArgInfo.Name = Tok.getIdentifierInfo(); 1080 ArgInfo.NameLoc = Tok.getLocation(); 1081 ConsumeToken(); // Eat the identifier. 1082 1083 ArgInfos.push_back(ArgInfo); 1084 KeyIdents.push_back(SelIdent); 1085 KeyLocs.push_back(selLoc); 1086 1087 // Make sure the attributes persist. 1088 allParamAttrs.takeAllFrom(paramAttrs.getPool()); 1089 1090 // Code completion for the next piece of the selector. 1091 if (Tok.is(tok::code_completion)) { 1092 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1093 mType == tok::minus, 1094 /*AtParameterName=*/false, 1095 ReturnType, 1096 KeyIdents.data(), 1097 KeyIdents.size()); 1098 cutOffParsing(); 1099 return 0; 1100 } 1101 1102 // Check for another keyword selector. 1103 SelIdent = ParseObjCSelectorPiece(selLoc); 1104 if (!SelIdent && Tok.isNot(tok::colon)) 1105 break; 1106 // We have a selector or a colon, continue parsing. 1107 } 1108 1109 bool isVariadic = false; 1110 bool cStyleParamWarned = false; 1111 // Parse the (optional) parameter list. 1112 while (Tok.is(tok::comma)) { 1113 ConsumeToken(); 1114 if (Tok.is(tok::ellipsis)) { 1115 isVariadic = true; 1116 ConsumeToken(); 1117 break; 1118 } 1119 if (!cStyleParamWarned) { 1120 Diag(Tok, diag::warn_cstyle_param); 1121 cStyleParamWarned = true; 1122 } 1123 DeclSpec DS(AttrFactory); 1124 ParseDeclarationSpecifiers(DS); 1125 // Parse the declarator. 1126 Declarator ParmDecl(DS, Declarator::PrototypeContext); 1127 ParseDeclarator(ParmDecl); 1128 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 1129 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 1130 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 1131 ParmDecl.getIdentifierLoc(), 1132 Param, 1133 0)); 1134 } 1135 1136 // FIXME: Add support for optional parameter list... 1137 // If attributes exist after the method, parse them. 1138 if (getLangOpts().ObjC2) 1139 MaybeParseGNUAttributes(methodAttrs); 1140 1141 if (KeyIdents.size() == 0) 1142 return 0; 1143 1144 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(), 1145 &KeyIdents[0]); 1146 Decl *Result 1147 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), 1148 mType, DSRet, ReturnType, 1149 KeyLocs, Sel, &ArgInfos[0], 1150 CParamInfo.data(), CParamInfo.size(), 1151 methodAttrs.getList(), 1152 MethodImplKind, isVariadic, MethodDefinition); 1153 1154 PD.complete(Result); 1155 return Result; 1156 } 1157 1158 /// objc-protocol-refs: 1159 /// '<' identifier-list '>' 1160 /// 1161 bool Parser:: 1162 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols, 1163 SmallVectorImpl<SourceLocation> &ProtocolLocs, 1164 bool WarnOnDeclarations, 1165 SourceLocation &LAngleLoc, SourceLocation &EndLoc) { 1166 assert(Tok.is(tok::less) && "expected <"); 1167 1168 LAngleLoc = ConsumeToken(); // the "<" 1169 1170 SmallVector<IdentifierLocPair, 8> ProtocolIdents; 1171 1172 while (1) { 1173 if (Tok.is(tok::code_completion)) { 1174 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(), 1175 ProtocolIdents.size()); 1176 cutOffParsing(); 1177 return true; 1178 } 1179 1180 if (Tok.isNot(tok::identifier)) { 1181 Diag(Tok, diag::err_expected_ident); 1182 SkipUntil(tok::greater); 1183 return true; 1184 } 1185 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(), 1186 Tok.getLocation())); 1187 ProtocolLocs.push_back(Tok.getLocation()); 1188 ConsumeToken(); 1189 1190 if (Tok.isNot(tok::comma)) 1191 break; 1192 ConsumeToken(); 1193 } 1194 1195 // Consume the '>'. 1196 if (Tok.isNot(tok::greater)) { 1197 Diag(Tok, diag::err_expected_greater); 1198 return true; 1199 } 1200 1201 EndLoc = ConsumeToken(); 1202 1203 // Convert the list of protocols identifiers into a list of protocol decls. 1204 Actions.FindProtocolDeclaration(WarnOnDeclarations, 1205 &ProtocolIdents[0], ProtocolIdents.size(), 1206 Protocols); 1207 return false; 1208 } 1209 1210 /// \brief Parse the Objective-C protocol qualifiers that follow a typename 1211 /// in a decl-specifier-seq, starting at the '<'. 1212 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) { 1213 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'"); 1214 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C"); 1215 SourceLocation LAngleLoc, EndProtoLoc; 1216 SmallVector<Decl *, 8> ProtocolDecl; 1217 SmallVector<SourceLocation, 8> ProtocolLocs; 1218 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1219 LAngleLoc, EndProtoLoc); 1220 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1221 ProtocolLocs.data(), LAngleLoc); 1222 if (EndProtoLoc.isValid()) 1223 DS.SetRangeEnd(EndProtoLoc); 1224 return Result; 1225 } 1226 1227 1228 /// objc-class-instance-variables: 1229 /// '{' objc-instance-variable-decl-list[opt] '}' 1230 /// 1231 /// objc-instance-variable-decl-list: 1232 /// objc-visibility-spec 1233 /// objc-instance-variable-decl ';' 1234 /// ';' 1235 /// objc-instance-variable-decl-list objc-visibility-spec 1236 /// objc-instance-variable-decl-list objc-instance-variable-decl ';' 1237 /// objc-instance-variable-decl-list ';' 1238 /// 1239 /// objc-visibility-spec: 1240 /// @private 1241 /// @protected 1242 /// @public 1243 /// @package [OBJC2] 1244 /// 1245 /// objc-instance-variable-decl: 1246 /// struct-declaration 1247 /// 1248 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, 1249 tok::ObjCKeywordKind visibility, 1250 SourceLocation atLoc) { 1251 assert(Tok.is(tok::l_brace) && "expected {"); 1252 SmallVector<Decl *, 32> AllIvarDecls; 1253 1254 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); 1255 ObjCDeclContextSwitch ObjCDC(*this); 1256 1257 BalancedDelimiterTracker T(*this, tok::l_brace); 1258 T.consumeOpen(); 1259 1260 // While we still have something to read, read the instance variables. 1261 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1262 // Each iteration of this loop reads one objc-instance-variable-decl. 1263 1264 // Check for extraneous top-level semicolon. 1265 if (Tok.is(tok::semi)) { 1266 ConsumeExtraSemi(InstanceVariableList); 1267 continue; 1268 } 1269 1270 // Set the default visibility to private. 1271 if (Tok.is(tok::at)) { // parse objc-visibility-spec 1272 ConsumeToken(); // eat the @ sign 1273 1274 if (Tok.is(tok::code_completion)) { 1275 Actions.CodeCompleteObjCAtVisibility(getCurScope()); 1276 return cutOffParsing(); 1277 } 1278 1279 switch (Tok.getObjCKeywordID()) { 1280 case tok::objc_private: 1281 case tok::objc_public: 1282 case tok::objc_protected: 1283 case tok::objc_package: 1284 visibility = Tok.getObjCKeywordID(); 1285 ConsumeToken(); 1286 continue; 1287 default: 1288 Diag(Tok, diag::err_objc_illegal_visibility_spec); 1289 continue; 1290 } 1291 } 1292 1293 if (Tok.is(tok::code_completion)) { 1294 Actions.CodeCompleteOrdinaryName(getCurScope(), 1295 Sema::PCC_ObjCInstanceVariableList); 1296 return cutOffParsing(); 1297 } 1298 1299 struct ObjCIvarCallback : FieldCallback { 1300 Parser &P; 1301 Decl *IDecl; 1302 tok::ObjCKeywordKind visibility; 1303 SmallVectorImpl<Decl *> &AllIvarDecls; 1304 1305 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V, 1306 SmallVectorImpl<Decl *> &AllIvarDecls) : 1307 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) { 1308 } 1309 1310 Decl *invoke(ParsingFieldDeclarator &FD) { 1311 P.Actions.ActOnObjCContainerStartDefinition(IDecl); 1312 // Install the declarator into the interface decl. 1313 Decl *Field 1314 = P.Actions.ActOnIvar(P.getCurScope(), 1315 FD.D.getDeclSpec().getSourceRange().getBegin(), 1316 FD.D, FD.BitfieldSize, visibility); 1317 P.Actions.ActOnObjCContainerFinishDefinition(); 1318 if (Field) 1319 AllIvarDecls.push_back(Field); 1320 FD.complete(Field); 1321 return Field; 1322 } 1323 } Callback(*this, interfaceDecl, visibility, AllIvarDecls); 1324 1325 // Parse all the comma separated declarators. 1326 ParsingDeclSpec DS(*this); 1327 ParseStructDeclaration(DS, Callback); 1328 1329 if (Tok.is(tok::semi)) { 1330 ConsumeToken(); 1331 } else { 1332 Diag(Tok, diag::err_expected_semi_decl_list); 1333 // Skip to end of block or statement 1334 SkipUntil(tok::r_brace, true, true); 1335 } 1336 } 1337 T.consumeClose(); 1338 1339 Actions.ActOnObjCContainerStartDefinition(interfaceDecl); 1340 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls); 1341 Actions.ActOnObjCContainerFinishDefinition(); 1342 // Call ActOnFields() even if we don't have any decls. This is useful 1343 // for code rewriting tools that need to be aware of the empty list. 1344 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, 1345 AllIvarDecls, 1346 T.getOpenLocation(), T.getCloseLocation(), 0); 1347 return; 1348 } 1349 1350 /// objc-protocol-declaration: 1351 /// objc-protocol-definition 1352 /// objc-protocol-forward-reference 1353 /// 1354 /// objc-protocol-definition: 1355 /// \@protocol identifier 1356 /// objc-protocol-refs[opt] 1357 /// objc-interface-decl-list 1358 /// \@end 1359 /// 1360 /// objc-protocol-forward-reference: 1361 /// \@protocol identifier-list ';' 1362 /// 1363 /// "\@protocol identifier ;" should be resolved as "\@protocol 1364 /// identifier-list ;": objc-interface-decl-list may not start with a 1365 /// semicolon in the first alternative if objc-protocol-refs are omitted. 1366 Parser::DeclGroupPtrTy 1367 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, 1368 ParsedAttributes &attrs) { 1369 assert(Tok.isObjCAtKeyword(tok::objc_protocol) && 1370 "ParseObjCAtProtocolDeclaration(): Expected @protocol"); 1371 ConsumeToken(); // the "protocol" identifier 1372 1373 if (Tok.is(tok::code_completion)) { 1374 Actions.CodeCompleteObjCProtocolDecl(getCurScope()); 1375 cutOffParsing(); 1376 return DeclGroupPtrTy(); 1377 } 1378 1379 if (Tok.isNot(tok::identifier)) { 1380 Diag(Tok, diag::err_expected_ident); // missing protocol name. 1381 return DeclGroupPtrTy(); 1382 } 1383 // Save the protocol name, then consume it. 1384 IdentifierInfo *protocolName = Tok.getIdentifierInfo(); 1385 SourceLocation nameLoc = ConsumeToken(); 1386 1387 if (Tok.is(tok::semi)) { // forward declaration of one protocol. 1388 IdentifierLocPair ProtoInfo(protocolName, nameLoc); 1389 ConsumeToken(); 1390 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1, 1391 attrs.getList()); 1392 } 1393 1394 CheckNestedObjCContexts(AtLoc); 1395 1396 if (Tok.is(tok::comma)) { // list of forward declarations. 1397 SmallVector<IdentifierLocPair, 8> ProtocolRefs; 1398 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc)); 1399 1400 // Parse the list of forward declarations. 1401 while (1) { 1402 ConsumeToken(); // the ',' 1403 if (Tok.isNot(tok::identifier)) { 1404 Diag(Tok, diag::err_expected_ident); 1405 SkipUntil(tok::semi); 1406 return DeclGroupPtrTy(); 1407 } 1408 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(), 1409 Tok.getLocation())); 1410 ConsumeToken(); // the identifier 1411 1412 if (Tok.isNot(tok::comma)) 1413 break; 1414 } 1415 // Consume the ';'. 1416 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol")) 1417 return DeclGroupPtrTy(); 1418 1419 return Actions.ActOnForwardProtocolDeclaration(AtLoc, 1420 &ProtocolRefs[0], 1421 ProtocolRefs.size(), 1422 attrs.getList()); 1423 } 1424 1425 // Last, and definitely not least, parse a protocol declaration. 1426 SourceLocation LAngleLoc, EndProtoLoc; 1427 1428 SmallVector<Decl *, 8> ProtocolRefs; 1429 SmallVector<SourceLocation, 8> ProtocolLocs; 1430 if (Tok.is(tok::less) && 1431 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, 1432 LAngleLoc, EndProtoLoc)) 1433 return DeclGroupPtrTy(); 1434 1435 Decl *ProtoType = 1436 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc, 1437 ProtocolRefs.data(), 1438 ProtocolRefs.size(), 1439 ProtocolLocs.data(), 1440 EndProtoLoc, attrs.getList()); 1441 1442 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType); 1443 return Actions.ConvertDeclToDeclGroup(ProtoType); 1444 } 1445 1446 /// objc-implementation: 1447 /// objc-class-implementation-prologue 1448 /// objc-category-implementation-prologue 1449 /// 1450 /// objc-class-implementation-prologue: 1451 /// @implementation identifier objc-superclass[opt] 1452 /// objc-class-instance-variables[opt] 1453 /// 1454 /// objc-category-implementation-prologue: 1455 /// @implementation identifier ( identifier ) 1456 Parser::DeclGroupPtrTy 1457 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { 1458 assert(Tok.isObjCAtKeyword(tok::objc_implementation) && 1459 "ParseObjCAtImplementationDeclaration(): Expected @implementation"); 1460 CheckNestedObjCContexts(AtLoc); 1461 ConsumeToken(); // the "implementation" identifier 1462 1463 // Code completion after '@implementation'. 1464 if (Tok.is(tok::code_completion)) { 1465 Actions.CodeCompleteObjCImplementationDecl(getCurScope()); 1466 cutOffParsing(); 1467 return DeclGroupPtrTy(); 1468 } 1469 1470 if (Tok.isNot(tok::identifier)) { 1471 Diag(Tok, diag::err_expected_ident); // missing class or category name. 1472 return DeclGroupPtrTy(); 1473 } 1474 // We have a class or category name - consume it. 1475 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 1476 SourceLocation nameLoc = ConsumeToken(); // consume class or category name 1477 Decl *ObjCImpDecl = 0; 1478 1479 if (Tok.is(tok::l_paren)) { 1480 // we have a category implementation. 1481 ConsumeParen(); 1482 SourceLocation categoryLoc, rparenLoc; 1483 IdentifierInfo *categoryId = 0; 1484 1485 if (Tok.is(tok::code_completion)) { 1486 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc); 1487 cutOffParsing(); 1488 return DeclGroupPtrTy(); 1489 } 1490 1491 if (Tok.is(tok::identifier)) { 1492 categoryId = Tok.getIdentifierInfo(); 1493 categoryLoc = ConsumeToken(); 1494 } else { 1495 Diag(Tok, diag::err_expected_ident); // missing category name. 1496 return DeclGroupPtrTy(); 1497 } 1498 if (Tok.isNot(tok::r_paren)) { 1499 Diag(Tok, diag::err_expected_rparen); 1500 SkipUntil(tok::r_paren, false); // don't stop at ';' 1501 return DeclGroupPtrTy(); 1502 } 1503 rparenLoc = ConsumeParen(); 1504 ObjCImpDecl = Actions.ActOnStartCategoryImplementation( 1505 AtLoc, nameId, nameLoc, categoryId, 1506 categoryLoc); 1507 1508 } else { 1509 // We have a class implementation 1510 SourceLocation superClassLoc; 1511 IdentifierInfo *superClassId = 0; 1512 if (Tok.is(tok::colon)) { 1513 // We have a super class 1514 ConsumeToken(); 1515 if (Tok.isNot(tok::identifier)) { 1516 Diag(Tok, diag::err_expected_ident); // missing super class name. 1517 return DeclGroupPtrTy(); 1518 } 1519 superClassId = Tok.getIdentifierInfo(); 1520 superClassLoc = ConsumeToken(); // Consume super class name 1521 } 1522 ObjCImpDecl = Actions.ActOnStartClassImplementation( 1523 AtLoc, nameId, nameLoc, 1524 superClassId, superClassLoc); 1525 1526 if (Tok.is(tok::l_brace)) // we have ivars 1527 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc); 1528 } 1529 assert(ObjCImpDecl); 1530 1531 SmallVector<Decl *, 8> DeclsInGroup; 1532 1533 { 1534 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl); 1535 while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) { 1536 ParsedAttributesWithRange attrs(AttrFactory); 1537 MaybeParseCXX0XAttributes(attrs); 1538 MaybeParseMicrosoftAttributes(attrs); 1539 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) { 1540 DeclGroupRef DG = DGP.get(); 1541 DeclsInGroup.append(DG.begin(), DG.end()); 1542 } 1543 } 1544 } 1545 1546 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup); 1547 } 1548 1549 Parser::DeclGroupPtrTy 1550 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) { 1551 assert(Tok.isObjCAtKeyword(tok::objc_end) && 1552 "ParseObjCAtEndDeclaration(): Expected @end"); 1553 ConsumeToken(); // the "end" identifier 1554 if (CurParsedObjCImpl) 1555 CurParsedObjCImpl->finish(atEnd); 1556 else 1557 // missing @implementation 1558 Diag(atEnd.getBegin(), diag::err_expected_objc_container); 1559 return DeclGroupPtrTy(); 1560 } 1561 1562 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() { 1563 if (!Finished) { 1564 finish(P.Tok.getLocation()); 1565 if (P.Tok.is(tok::eof)) { 1566 P.Diag(P.Tok, diag::err_objc_missing_end) 1567 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n"); 1568 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start) 1569 << Sema::OCK_Implementation; 1570 } 1571 } 1572 P.CurParsedObjCImpl = 0; 1573 assert(LateParsedObjCMethods.empty()); 1574 } 1575 1576 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) { 1577 assert(!Finished); 1578 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl); 1579 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 1580 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 1581 true/*Methods*/); 1582 1583 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd); 1584 1585 if (HasCFunction) 1586 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 1587 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 1588 false/*c-functions*/); 1589 1590 /// \brief Clear and free the cached objc methods. 1591 for (LateParsedObjCMethodContainer::iterator 1592 I = LateParsedObjCMethods.begin(), 1593 E = LateParsedObjCMethods.end(); I != E; ++I) 1594 delete *I; 1595 LateParsedObjCMethods.clear(); 1596 1597 Finished = true; 1598 } 1599 1600 /// compatibility-alias-decl: 1601 /// @compatibility_alias alias-name class-name ';' 1602 /// 1603 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) { 1604 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) && 1605 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias"); 1606 ConsumeToken(); // consume compatibility_alias 1607 if (Tok.isNot(tok::identifier)) { 1608 Diag(Tok, diag::err_expected_ident); 1609 return 0; 1610 } 1611 IdentifierInfo *aliasId = Tok.getIdentifierInfo(); 1612 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name 1613 if (Tok.isNot(tok::identifier)) { 1614 Diag(Tok, diag::err_expected_ident); 1615 return 0; 1616 } 1617 IdentifierInfo *classId = Tok.getIdentifierInfo(); 1618 SourceLocation classLoc = ConsumeToken(); // consume class-name; 1619 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 1620 "@compatibility_alias"); 1621 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc, 1622 classId, classLoc); 1623 } 1624 1625 /// property-synthesis: 1626 /// @synthesize property-ivar-list ';' 1627 /// 1628 /// property-ivar-list: 1629 /// property-ivar 1630 /// property-ivar-list ',' property-ivar 1631 /// 1632 /// property-ivar: 1633 /// identifier 1634 /// identifier '=' identifier 1635 /// 1636 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { 1637 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) && 1638 "ParseObjCPropertyDynamic(): Expected '@synthesize'"); 1639 ConsumeToken(); // consume synthesize 1640 1641 while (true) { 1642 if (Tok.is(tok::code_completion)) { 1643 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 1644 cutOffParsing(); 1645 return 0; 1646 } 1647 1648 if (Tok.isNot(tok::identifier)) { 1649 Diag(Tok, diag::err_synthesized_property_name); 1650 SkipUntil(tok::semi); 1651 return 0; 1652 } 1653 1654 IdentifierInfo *propertyIvar = 0; 1655 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1656 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1657 SourceLocation propertyIvarLoc; 1658 if (Tok.is(tok::equal)) { 1659 // property '=' ivar-name 1660 ConsumeToken(); // consume '=' 1661 1662 if (Tok.is(tok::code_completion)) { 1663 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId); 1664 cutOffParsing(); 1665 return 0; 1666 } 1667 1668 if (Tok.isNot(tok::identifier)) { 1669 Diag(Tok, diag::err_expected_ident); 1670 break; 1671 } 1672 propertyIvar = Tok.getIdentifierInfo(); 1673 propertyIvarLoc = ConsumeToken(); // consume ivar-name 1674 } 1675 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, 1676 propertyId, propertyIvar, propertyIvarLoc); 1677 if (Tok.isNot(tok::comma)) 1678 break; 1679 ConsumeToken(); // consume ',' 1680 } 1681 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize"); 1682 return 0; 1683 } 1684 1685 /// property-dynamic: 1686 /// @dynamic property-list 1687 /// 1688 /// property-list: 1689 /// identifier 1690 /// property-list ',' identifier 1691 /// 1692 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { 1693 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) && 1694 "ParseObjCPropertyDynamic(): Expected '@dynamic'"); 1695 ConsumeToken(); // consume dynamic 1696 while (true) { 1697 if (Tok.is(tok::code_completion)) { 1698 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 1699 cutOffParsing(); 1700 return 0; 1701 } 1702 1703 if (Tok.isNot(tok::identifier)) { 1704 Diag(Tok, diag::err_expected_ident); 1705 SkipUntil(tok::semi); 1706 return 0; 1707 } 1708 1709 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1710 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1711 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, 1712 propertyId, 0, SourceLocation()); 1713 1714 if (Tok.isNot(tok::comma)) 1715 break; 1716 ConsumeToken(); // consume ',' 1717 } 1718 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic"); 1719 return 0; 1720 } 1721 1722 /// objc-throw-statement: 1723 /// throw expression[opt]; 1724 /// 1725 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) { 1726 ExprResult Res; 1727 ConsumeToken(); // consume throw 1728 if (Tok.isNot(tok::semi)) { 1729 Res = ParseExpression(); 1730 if (Res.isInvalid()) { 1731 SkipUntil(tok::semi); 1732 return StmtError(); 1733 } 1734 } 1735 // consume ';' 1736 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw"); 1737 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope()); 1738 } 1739 1740 /// objc-synchronized-statement: 1741 /// @synchronized '(' expression ')' compound-statement 1742 /// 1743 StmtResult 1744 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) { 1745 ConsumeToken(); // consume synchronized 1746 if (Tok.isNot(tok::l_paren)) { 1747 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized"; 1748 return StmtError(); 1749 } 1750 1751 // The operand is surrounded with parentheses. 1752 ConsumeParen(); // '(' 1753 ExprResult operand(ParseExpression()); 1754 1755 if (Tok.is(tok::r_paren)) { 1756 ConsumeParen(); // ')' 1757 } else { 1758 if (!operand.isInvalid()) 1759 Diag(Tok, diag::err_expected_rparen); 1760 1761 // Skip forward until we see a left brace, but don't consume it. 1762 SkipUntil(tok::l_brace, true, true); 1763 } 1764 1765 // Require a compound statement. 1766 if (Tok.isNot(tok::l_brace)) { 1767 if (!operand.isInvalid()) 1768 Diag(Tok, diag::err_expected_lbrace); 1769 return StmtError(); 1770 } 1771 1772 // Check the @synchronized operand now. 1773 if (!operand.isInvalid()) 1774 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take()); 1775 1776 // Parse the compound statement within a new scope. 1777 ParseScope bodyScope(this, Scope::DeclScope); 1778 StmtResult body(ParseCompoundStatementBody()); 1779 bodyScope.Exit(); 1780 1781 // If there was a semantic or parse error earlier with the 1782 // operand, fail now. 1783 if (operand.isInvalid()) 1784 return StmtError(); 1785 1786 if (body.isInvalid()) 1787 body = Actions.ActOnNullStmt(Tok.getLocation()); 1788 1789 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get()); 1790 } 1791 1792 /// objc-try-catch-statement: 1793 /// @try compound-statement objc-catch-list[opt] 1794 /// @try compound-statement objc-catch-list[opt] @finally compound-statement 1795 /// 1796 /// objc-catch-list: 1797 /// @catch ( parameter-declaration ) compound-statement 1798 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement 1799 /// catch-parameter-declaration: 1800 /// parameter-declaration 1801 /// '...' [OBJC2] 1802 /// 1803 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { 1804 bool catch_or_finally_seen = false; 1805 1806 ConsumeToken(); // consume try 1807 if (Tok.isNot(tok::l_brace)) { 1808 Diag(Tok, diag::err_expected_lbrace); 1809 return StmtError(); 1810 } 1811 StmtVector CatchStmts(Actions); 1812 StmtResult FinallyStmt; 1813 ParseScope TryScope(this, Scope::DeclScope); 1814 StmtResult TryBody(ParseCompoundStatementBody()); 1815 TryScope.Exit(); 1816 if (TryBody.isInvalid()) 1817 TryBody = Actions.ActOnNullStmt(Tok.getLocation()); 1818 1819 while (Tok.is(tok::at)) { 1820 // At this point, we need to lookahead to determine if this @ is the start 1821 // of an @catch or @finally. We don't want to consume the @ token if this 1822 // is an @try or @encode or something else. 1823 Token AfterAt = GetLookAheadToken(1); 1824 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) && 1825 !AfterAt.isObjCAtKeyword(tok::objc_finally)) 1826 break; 1827 1828 SourceLocation AtCatchFinallyLoc = ConsumeToken(); 1829 if (Tok.isObjCAtKeyword(tok::objc_catch)) { 1830 Decl *FirstPart = 0; 1831 ConsumeToken(); // consume catch 1832 if (Tok.is(tok::l_paren)) { 1833 ConsumeParen(); 1834 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope); 1835 if (Tok.isNot(tok::ellipsis)) { 1836 DeclSpec DS(AttrFactory); 1837 ParseDeclarationSpecifiers(DS); 1838 Declarator ParmDecl(DS, Declarator::ObjCCatchContext); 1839 ParseDeclarator(ParmDecl); 1840 1841 // Inform the actions module about the declarator, so it 1842 // gets added to the current scope. 1843 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl); 1844 } else 1845 ConsumeToken(); // consume '...' 1846 1847 SourceLocation RParenLoc; 1848 1849 if (Tok.is(tok::r_paren)) 1850 RParenLoc = ConsumeParen(); 1851 else // Skip over garbage, until we get to ')'. Eat the ')'. 1852 SkipUntil(tok::r_paren, true, false); 1853 1854 StmtResult CatchBody(true); 1855 if (Tok.is(tok::l_brace)) 1856 CatchBody = ParseCompoundStatementBody(); 1857 else 1858 Diag(Tok, diag::err_expected_lbrace); 1859 if (CatchBody.isInvalid()) 1860 CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); 1861 1862 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, 1863 RParenLoc, 1864 FirstPart, 1865 CatchBody.take()); 1866 if (!Catch.isInvalid()) 1867 CatchStmts.push_back(Catch.release()); 1868 1869 } else { 1870 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) 1871 << "@catch clause"; 1872 return StmtError(); 1873 } 1874 catch_or_finally_seen = true; 1875 } else { 1876 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?"); 1877 ConsumeToken(); // consume finally 1878 ParseScope FinallyScope(this, Scope::DeclScope); 1879 1880 StmtResult FinallyBody(true); 1881 if (Tok.is(tok::l_brace)) 1882 FinallyBody = ParseCompoundStatementBody(); 1883 else 1884 Diag(Tok, diag::err_expected_lbrace); 1885 if (FinallyBody.isInvalid()) 1886 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation()); 1887 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc, 1888 FinallyBody.take()); 1889 catch_or_finally_seen = true; 1890 break; 1891 } 1892 } 1893 if (!catch_or_finally_seen) { 1894 Diag(atLoc, diag::err_missing_catch_finally); 1895 return StmtError(); 1896 } 1897 1898 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(), 1899 move_arg(CatchStmts), 1900 FinallyStmt.take()); 1901 } 1902 1903 /// objc-autoreleasepool-statement: 1904 /// @autoreleasepool compound-statement 1905 /// 1906 StmtResult 1907 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) { 1908 ConsumeToken(); // consume autoreleasepool 1909 if (Tok.isNot(tok::l_brace)) { 1910 Diag(Tok, diag::err_expected_lbrace); 1911 return StmtError(); 1912 } 1913 // Enter a scope to hold everything within the compound stmt. Compound 1914 // statements can always hold declarations. 1915 ParseScope BodyScope(this, Scope::DeclScope); 1916 1917 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody()); 1918 1919 BodyScope.Exit(); 1920 if (AutoreleasePoolBody.isInvalid()) 1921 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation()); 1922 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, 1923 AutoreleasePoolBody.take()); 1924 } 1925 1926 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them 1927 /// for later parsing. 1928 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) { 1929 LexedMethod* LM = new LexedMethod(this, MDecl); 1930 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM); 1931 CachedTokens &Toks = LM->Toks; 1932 // Begin by storing the '{' token. 1933 Toks.push_back(Tok); 1934 ConsumeBrace(); 1935 // Consume everything up to (and including) the matching right brace. 1936 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 1937 } 1938 1939 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}' 1940 /// 1941 Decl *Parser::ParseObjCMethodDefinition() { 1942 Decl *MDecl = ParseObjCMethodPrototype(); 1943 1944 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(), 1945 "parsing Objective-C method"); 1946 1947 // parse optional ';' 1948 if (Tok.is(tok::semi)) { 1949 if (CurParsedObjCImpl) { 1950 Diag(Tok, diag::warn_semicolon_before_method_body) 1951 << FixItHint::CreateRemoval(Tok.getLocation()); 1952 } 1953 ConsumeToken(); 1954 } 1955 1956 // We should have an opening brace now. 1957 if (Tok.isNot(tok::l_brace)) { 1958 Diag(Tok, diag::err_expected_method_body); 1959 1960 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1961 SkipUntil(tok::l_brace, true, true); 1962 1963 // If we didn't find the '{', bail out. 1964 if (Tok.isNot(tok::l_brace)) 1965 return 0; 1966 } 1967 1968 if (!MDecl) { 1969 ConsumeBrace(); 1970 SkipUntil(tok::r_brace, /*StopAtSemi=*/false); 1971 return 0; 1972 } 1973 1974 // Allow the rest of sema to find private method decl implementations. 1975 Actions.AddAnyMethodToGlobalPool(MDecl); 1976 1977 if (CurParsedObjCImpl) { 1978 // Consume the tokens and store them for later parsing. 1979 StashAwayMethodOrFunctionBodyTokens(MDecl); 1980 } else { 1981 ConsumeBrace(); 1982 SkipUntil(tok::r_brace, /*StopAtSemi=*/false); 1983 } 1984 1985 return MDecl; 1986 } 1987 1988 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { 1989 if (Tok.is(tok::code_completion)) { 1990 Actions.CodeCompleteObjCAtStatement(getCurScope()); 1991 cutOffParsing(); 1992 return StmtError(); 1993 } 1994 1995 if (Tok.isObjCAtKeyword(tok::objc_try)) 1996 return ParseObjCTryStmt(AtLoc); 1997 1998 if (Tok.isObjCAtKeyword(tok::objc_throw)) 1999 return ParseObjCThrowStmt(AtLoc); 2000 2001 if (Tok.isObjCAtKeyword(tok::objc_synchronized)) 2002 return ParseObjCSynchronizedStmt(AtLoc); 2003 2004 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool)) 2005 return ParseObjCAutoreleasePoolStmt(AtLoc); 2006 2007 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc)); 2008 if (Res.isInvalid()) { 2009 // If the expression is invalid, skip ahead to the next semicolon. Not 2010 // doing this opens us up to the possibility of infinite loops if 2011 // ParseExpression does not consume any tokens. 2012 SkipUntil(tok::semi); 2013 return StmtError(); 2014 } 2015 2016 // Otherwise, eat the semicolon. 2017 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 2018 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take())); 2019 } 2020 2021 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { 2022 switch (Tok.getKind()) { 2023 case tok::code_completion: 2024 Actions.CodeCompleteObjCAtExpression(getCurScope()); 2025 cutOffParsing(); 2026 return ExprError(); 2027 2028 case tok::minus: 2029 case tok::plus: { 2030 tok::TokenKind Kind = Tok.getKind(); 2031 SourceLocation OpLoc = ConsumeToken(); 2032 2033 if (!Tok.is(tok::numeric_constant)) { 2034 const char *Symbol = 0; 2035 switch (Kind) { 2036 case tok::minus: Symbol = "-"; break; 2037 case tok::plus: Symbol = "+"; break; 2038 default: llvm_unreachable("missing unary operator case"); 2039 } 2040 Diag(Tok, diag::err_nsnumber_nonliteral_unary) 2041 << Symbol; 2042 return ExprError(); 2043 } 2044 2045 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 2046 if (Lit.isInvalid()) { 2047 return move(Lit); 2048 } 2049 ConsumeToken(); // Consume the literal token. 2050 2051 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take()); 2052 if (Lit.isInvalid()) 2053 return move(Lit); 2054 2055 return ParsePostfixExpressionSuffix( 2056 Actions.BuildObjCNumericLiteral(AtLoc, Lit.take())); 2057 } 2058 2059 case tok::string_literal: // primary-expression: string-literal 2060 case tok::wide_string_literal: 2061 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc)); 2062 2063 case tok::char_constant: 2064 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc)); 2065 2066 case tok::numeric_constant: 2067 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc)); 2068 2069 case tok::kw_true: // Objective-C++, etc. 2070 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes 2071 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true)); 2072 case tok::kw_false: // Objective-C++, etc. 2073 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no 2074 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false)); 2075 2076 case tok::l_square: 2077 // Objective-C array literal 2078 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc)); 2079 2080 case tok::l_brace: 2081 // Objective-C dictionary literal 2082 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc)); 2083 2084 case tok::l_paren: 2085 // Objective-C boxed expression 2086 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc)); 2087 2088 default: 2089 if (Tok.getIdentifierInfo() == 0) 2090 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2091 2092 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) { 2093 case tok::objc_encode: 2094 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc)); 2095 case tok::objc_protocol: 2096 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc)); 2097 case tok::objc_selector: 2098 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc)); 2099 default: { 2100 const char *str = 0; 2101 if (GetLookAheadToken(1).is(tok::l_brace)) { 2102 char ch = Tok.getIdentifierInfo()->getNameStart()[0]; 2103 str = 2104 ch == 't' ? "try" 2105 : (ch == 'f' ? "finally" 2106 : (ch == 'a' ? "autoreleasepool" : 0)); 2107 } 2108 if (str) { 2109 SourceLocation kwLoc = Tok.getLocation(); 2110 return ExprError(Diag(AtLoc, diag::err_unexpected_at) << 2111 FixItHint::CreateReplacement(kwLoc, str)); 2112 } 2113 else 2114 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2115 } 2116 } 2117 } 2118 } 2119 2120 /// \brirg Parse the receiver of an Objective-C++ message send. 2121 /// 2122 /// This routine parses the receiver of a message send in 2123 /// Objective-C++ either as a type or as an expression. Note that this 2124 /// routine must not be called to parse a send to 'super', since it 2125 /// has no way to return such a result. 2126 /// 2127 /// \param IsExpr Whether the receiver was parsed as an expression. 2128 /// 2129 /// \param TypeOrExpr If the receiver was parsed as an expression (\c 2130 /// IsExpr is true), the parsed expression. If the receiver was parsed 2131 /// as a type (\c IsExpr is false), the parsed type. 2132 /// 2133 /// \returns True if an error occurred during parsing or semantic 2134 /// analysis, in which case the arguments do not have valid 2135 /// values. Otherwise, returns false for a successful parse. 2136 /// 2137 /// objc-receiver: [C++] 2138 /// 'super' [not parsed here] 2139 /// expression 2140 /// simple-type-specifier 2141 /// typename-specifier 2142 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { 2143 InMessageExpressionRAIIObject InMessage(*this, true); 2144 2145 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 2146 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)) 2147 TryAnnotateTypeOrScopeToken(); 2148 2149 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) { 2150 // objc-receiver: 2151 // expression 2152 ExprResult Receiver = ParseExpression(); 2153 if (Receiver.isInvalid()) 2154 return true; 2155 2156 IsExpr = true; 2157 TypeOrExpr = Receiver.take(); 2158 return false; 2159 } 2160 2161 // objc-receiver: 2162 // typename-specifier 2163 // simple-type-specifier 2164 // expression (that starts with one of the above) 2165 DeclSpec DS(AttrFactory); 2166 ParseCXXSimpleTypeSpecifier(DS); 2167 2168 if (Tok.is(tok::l_paren)) { 2169 // If we see an opening parentheses at this point, we are 2170 // actually parsing an expression that starts with a 2171 // function-style cast, e.g., 2172 // 2173 // postfix-expression: 2174 // simple-type-specifier ( expression-list [opt] ) 2175 // typename-specifier ( expression-list [opt] ) 2176 // 2177 // Parse the remainder of this case, then the (optional) 2178 // postfix-expression suffix, followed by the (optional) 2179 // right-hand side of the binary expression. We have an 2180 // instance method. 2181 ExprResult Receiver = ParseCXXTypeConstructExpression(DS); 2182 if (!Receiver.isInvalid()) 2183 Receiver = ParsePostfixExpressionSuffix(Receiver.take()); 2184 if (!Receiver.isInvalid()) 2185 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma); 2186 if (Receiver.isInvalid()) 2187 return true; 2188 2189 IsExpr = true; 2190 TypeOrExpr = Receiver.take(); 2191 return false; 2192 } 2193 2194 // We have a class message. Turn the simple-type-specifier or 2195 // typename-specifier we parsed into a type and parse the 2196 // remainder of the class message. 2197 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2198 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2199 if (Type.isInvalid()) 2200 return true; 2201 2202 IsExpr = false; 2203 TypeOrExpr = Type.get().getAsOpaquePtr(); 2204 return false; 2205 } 2206 2207 /// \brief Determine whether the parser is currently referring to a an 2208 /// Objective-C message send, using a simplified heuristic to avoid overhead. 2209 /// 2210 /// This routine will only return true for a subset of valid message-send 2211 /// expressions. 2212 bool Parser::isSimpleObjCMessageExpression() { 2213 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 && 2214 "Incorrect start for isSimpleObjCMessageExpression"); 2215 return GetLookAheadToken(1).is(tok::identifier) && 2216 GetLookAheadToken(2).is(tok::identifier); 2217 } 2218 2219 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { 2220 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || 2221 InMessageExpression) 2222 return false; 2223 2224 2225 ParsedType Type; 2226 2227 if (Tok.is(tok::annot_typename)) 2228 Type = getTypeAnnotation(Tok); 2229 else if (Tok.is(tok::identifier)) 2230 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), 2231 getCurScope()); 2232 else 2233 return false; 2234 2235 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { 2236 const Token &AfterNext = GetLookAheadToken(2); 2237 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) { 2238 if (Tok.is(tok::identifier)) 2239 TryAnnotateTypeOrScopeToken(); 2240 2241 return Tok.is(tok::annot_typename); 2242 } 2243 } 2244 2245 return false; 2246 } 2247 2248 /// objc-message-expr: 2249 /// '[' objc-receiver objc-message-args ']' 2250 /// 2251 /// objc-receiver: [C] 2252 /// 'super' 2253 /// expression 2254 /// class-name 2255 /// type-name 2256 /// 2257 ExprResult Parser::ParseObjCMessageExpression() { 2258 assert(Tok.is(tok::l_square) && "'[' expected"); 2259 SourceLocation LBracLoc = ConsumeBracket(); // consume '[' 2260 2261 if (Tok.is(tok::code_completion)) { 2262 Actions.CodeCompleteObjCMessageReceiver(getCurScope()); 2263 cutOffParsing(); 2264 return ExprError(); 2265 } 2266 2267 InMessageExpressionRAIIObject InMessage(*this, true); 2268 2269 if (getLangOpts().CPlusPlus) { 2270 // We completely separate the C and C++ cases because C++ requires 2271 // more complicated (read: slower) parsing. 2272 2273 // Handle send to super. 2274 // FIXME: This doesn't benefit from the same typo-correction we 2275 // get in Objective-C. 2276 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && 2277 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) 2278 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 2279 ParsedType(), 0); 2280 2281 // Parse the receiver, which is either a type or an expression. 2282 bool IsExpr; 2283 void *TypeOrExpr = NULL; 2284 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { 2285 SkipUntil(tok::r_square); 2286 return ExprError(); 2287 } 2288 2289 if (IsExpr) 2290 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2291 ParsedType(), 2292 static_cast<Expr*>(TypeOrExpr)); 2293 2294 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2295 ParsedType::getFromOpaquePtr(TypeOrExpr), 2296 0); 2297 } 2298 2299 if (Tok.is(tok::identifier)) { 2300 IdentifierInfo *Name = Tok.getIdentifierInfo(); 2301 SourceLocation NameLoc = Tok.getLocation(); 2302 ParsedType ReceiverType; 2303 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc, 2304 Name == Ident_super, 2305 NextToken().is(tok::period), 2306 ReceiverType)) { 2307 case Sema::ObjCSuperMessage: 2308 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 2309 ParsedType(), 0); 2310 2311 case Sema::ObjCClassMessage: 2312 if (!ReceiverType) { 2313 SkipUntil(tok::r_square); 2314 return ExprError(); 2315 } 2316 2317 ConsumeToken(); // the type name 2318 2319 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2320 ReceiverType, 0); 2321 2322 case Sema::ObjCInstanceMessage: 2323 // Fall through to parse an expression. 2324 break; 2325 } 2326 } 2327 2328 // Otherwise, an arbitrary expression can be the receiver of a send. 2329 ExprResult Res(ParseExpression()); 2330 if (Res.isInvalid()) { 2331 SkipUntil(tok::r_square); 2332 return move(Res); 2333 } 2334 2335 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2336 ParsedType(), Res.take()); 2337 } 2338 2339 /// \brief Parse the remainder of an Objective-C message following the 2340 /// '[' objc-receiver. 2341 /// 2342 /// This routine handles sends to super, class messages (sent to a 2343 /// class name), and instance messages (sent to an object), and the 2344 /// target is represented by \p SuperLoc, \p ReceiverType, or \p 2345 /// ReceiverExpr, respectively. Only one of these parameters may have 2346 /// a valid value. 2347 /// 2348 /// \param LBracLoc The location of the opening '['. 2349 /// 2350 /// \param SuperLoc If this is a send to 'super', the location of the 2351 /// 'super' keyword that indicates a send to the superclass. 2352 /// 2353 /// \param ReceiverType If this is a class message, the type of the 2354 /// class we are sending a message to. 2355 /// 2356 /// \param ReceiverExpr If this is an instance message, the expression 2357 /// used to compute the receiver object. 2358 /// 2359 /// objc-message-args: 2360 /// objc-selector 2361 /// objc-keywordarg-list 2362 /// 2363 /// objc-keywordarg-list: 2364 /// objc-keywordarg 2365 /// objc-keywordarg-list objc-keywordarg 2366 /// 2367 /// objc-keywordarg: 2368 /// selector-name[opt] ':' objc-keywordexpr 2369 /// 2370 /// objc-keywordexpr: 2371 /// nonempty-expr-list 2372 /// 2373 /// nonempty-expr-list: 2374 /// assignment-expression 2375 /// nonempty-expr-list , assignment-expression 2376 /// 2377 ExprResult 2378 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, 2379 SourceLocation SuperLoc, 2380 ParsedType ReceiverType, 2381 ExprArg ReceiverExpr) { 2382 InMessageExpressionRAIIObject InMessage(*this, true); 2383 2384 if (Tok.is(tok::code_completion)) { 2385 if (SuperLoc.isValid()) 2386 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0, 2387 false); 2388 else if (ReceiverType) 2389 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0, 2390 false); 2391 else 2392 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2393 0, 0, false); 2394 cutOffParsing(); 2395 return ExprError(); 2396 } 2397 2398 // Parse objc-selector 2399 SourceLocation Loc; 2400 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); 2401 2402 SmallVector<IdentifierInfo *, 12> KeyIdents; 2403 SmallVector<SourceLocation, 12> KeyLocs; 2404 ExprVector KeyExprs(Actions); 2405 2406 if (Tok.is(tok::colon)) { 2407 while (1) { 2408 // Each iteration parses a single keyword argument. 2409 KeyIdents.push_back(selIdent); 2410 KeyLocs.push_back(Loc); 2411 2412 if (Tok.isNot(tok::colon)) { 2413 Diag(Tok, diag::err_expected_colon); 2414 // We must manually skip to a ']', otherwise the expression skipper will 2415 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2416 // the enclosing expression. 2417 SkipUntil(tok::r_square); 2418 return ExprError(); 2419 } 2420 2421 ConsumeToken(); // Eat the ':'. 2422 /// Parse the expression after ':' 2423 2424 if (Tok.is(tok::code_completion)) { 2425 if (SuperLoc.isValid()) 2426 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2427 KeyIdents.data(), 2428 KeyIdents.size(), 2429 /*AtArgumentEpression=*/true); 2430 else if (ReceiverType) 2431 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2432 KeyIdents.data(), 2433 KeyIdents.size(), 2434 /*AtArgumentEpression=*/true); 2435 else 2436 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2437 KeyIdents.data(), 2438 KeyIdents.size(), 2439 /*AtArgumentEpression=*/true); 2440 2441 cutOffParsing(); 2442 return ExprError(); 2443 } 2444 2445 ExprResult Res(ParseAssignmentExpression()); 2446 if (Res.isInvalid()) { 2447 // We must manually skip to a ']', otherwise the expression skipper will 2448 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2449 // the enclosing expression. 2450 SkipUntil(tok::r_square); 2451 return move(Res); 2452 } 2453 2454 // We have a valid expression. 2455 KeyExprs.push_back(Res.release()); 2456 2457 // Code completion after each argument. 2458 if (Tok.is(tok::code_completion)) { 2459 if (SuperLoc.isValid()) 2460 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2461 KeyIdents.data(), 2462 KeyIdents.size(), 2463 /*AtArgumentEpression=*/false); 2464 else if (ReceiverType) 2465 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2466 KeyIdents.data(), 2467 KeyIdents.size(), 2468 /*AtArgumentEpression=*/false); 2469 else 2470 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2471 KeyIdents.data(), 2472 KeyIdents.size(), 2473 /*AtArgumentEpression=*/false); 2474 cutOffParsing(); 2475 return ExprError(); 2476 } 2477 2478 // Check for another keyword selector. 2479 selIdent = ParseObjCSelectorPiece(Loc); 2480 if (!selIdent && Tok.isNot(tok::colon)) 2481 break; 2482 // We have a selector or a colon, continue parsing. 2483 } 2484 // Parse the, optional, argument list, comma separated. 2485 while (Tok.is(tok::comma)) { 2486 SourceLocation commaLoc = ConsumeToken(); // Eat the ','. 2487 /// Parse the expression after ',' 2488 ExprResult Res(ParseAssignmentExpression()); 2489 if (Res.isInvalid()) { 2490 if (Tok.is(tok::colon)) { 2491 Diag(commaLoc, diag::note_extra_comma_message_arg) << 2492 FixItHint::CreateRemoval(commaLoc); 2493 } 2494 // We must manually skip to a ']', otherwise the expression skipper will 2495 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2496 // the enclosing expression. 2497 SkipUntil(tok::r_square); 2498 return move(Res); 2499 } 2500 2501 // We have a valid expression. 2502 KeyExprs.push_back(Res.release()); 2503 } 2504 } else if (!selIdent) { 2505 Diag(Tok, diag::err_expected_ident); // missing selector name. 2506 2507 // We must manually skip to a ']', otherwise the expression skipper will 2508 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2509 // the enclosing expression. 2510 SkipUntil(tok::r_square); 2511 return ExprError(); 2512 } 2513 2514 if (Tok.isNot(tok::r_square)) { 2515 if (Tok.is(tok::identifier)) 2516 Diag(Tok, diag::err_expected_colon); 2517 else 2518 Diag(Tok, diag::err_expected_rsquare); 2519 // We must manually skip to a ']', otherwise the expression skipper will 2520 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2521 // the enclosing expression. 2522 SkipUntil(tok::r_square); 2523 return ExprError(); 2524 } 2525 2526 SourceLocation RBracLoc = ConsumeBracket(); // consume ']' 2527 2528 unsigned nKeys = KeyIdents.size(); 2529 if (nKeys == 0) { 2530 KeyIdents.push_back(selIdent); 2531 KeyLocs.push_back(Loc); 2532 } 2533 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]); 2534 2535 if (SuperLoc.isValid()) 2536 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel, 2537 LBracLoc, KeyLocs, RBracLoc, 2538 MultiExprArg(Actions, 2539 KeyExprs.take(), 2540 KeyExprs.size())); 2541 else if (ReceiverType) 2542 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel, 2543 LBracLoc, KeyLocs, RBracLoc, 2544 MultiExprArg(Actions, 2545 KeyExprs.take(), 2546 KeyExprs.size())); 2547 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel, 2548 LBracLoc, KeyLocs, RBracLoc, 2549 MultiExprArg(Actions, 2550 KeyExprs.take(), 2551 KeyExprs.size())); 2552 } 2553 2554 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { 2555 ExprResult Res(ParseStringLiteralExpression()); 2556 if (Res.isInvalid()) return move(Res); 2557 2558 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string 2559 // expressions. At this point, we know that the only valid thing that starts 2560 // with '@' is an @"". 2561 SmallVector<SourceLocation, 4> AtLocs; 2562 ExprVector AtStrings(Actions); 2563 AtLocs.push_back(AtLoc); 2564 AtStrings.push_back(Res.release()); 2565 2566 while (Tok.is(tok::at)) { 2567 AtLocs.push_back(ConsumeToken()); // eat the @. 2568 2569 // Invalid unless there is a string literal. 2570 if (!isTokenStringLiteral()) 2571 return ExprError(Diag(Tok, diag::err_objc_concat_string)); 2572 2573 ExprResult Lit(ParseStringLiteralExpression()); 2574 if (Lit.isInvalid()) 2575 return move(Lit); 2576 2577 AtStrings.push_back(Lit.release()); 2578 } 2579 2580 return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(), 2581 AtStrings.size())); 2582 } 2583 2584 /// ParseObjCBooleanLiteral - 2585 /// objc-scalar-literal : '@' boolean-keyword 2586 /// ; 2587 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no' 2588 /// ; 2589 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, 2590 bool ArgValue) { 2591 SourceLocation EndLoc = ConsumeToken(); // consume the keyword. 2592 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue); 2593 } 2594 2595 /// ParseObjCCharacterLiteral - 2596 /// objc-scalar-literal : '@' character-literal 2597 /// ; 2598 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) { 2599 ExprResult Lit(Actions.ActOnCharacterConstant(Tok)); 2600 if (Lit.isInvalid()) { 2601 return move(Lit); 2602 } 2603 ConsumeToken(); // Consume the literal token. 2604 return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take())); 2605 } 2606 2607 /// ParseObjCNumericLiteral - 2608 /// objc-scalar-literal : '@' scalar-literal 2609 /// ; 2610 /// scalar-literal : | numeric-constant /* any numeric constant. */ 2611 /// ; 2612 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) { 2613 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 2614 if (Lit.isInvalid()) { 2615 return move(Lit); 2616 } 2617 ConsumeToken(); // Consume the literal token. 2618 return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take())); 2619 } 2620 2621 /// ParseObjCBoxedExpr - 2622 /// objc-box-expression: 2623 /// @( assignment-expression ) 2624 ExprResult 2625 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) { 2626 if (Tok.isNot(tok::l_paren)) 2627 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@"); 2628 2629 BalancedDelimiterTracker T(*this, tok::l_paren); 2630 T.consumeOpen(); 2631 ExprResult ValueExpr(ParseAssignmentExpression()); 2632 if (T.consumeClose()) 2633 return ExprError(); 2634 2635 if (ValueExpr.isInvalid()) 2636 return ExprError(); 2637 2638 // Wrap the sub-expression in a parenthesized expression, to distinguish 2639 // a boxed expression from a literal. 2640 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation(); 2641 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take()); 2642 return Owned(Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc), 2643 ValueExpr.take())); 2644 } 2645 2646 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) { 2647 ExprVector ElementExprs(Actions); // array elements. 2648 ConsumeBracket(); // consume the l_square. 2649 2650 while (Tok.isNot(tok::r_square)) { 2651 // Parse list of array element expressions (all must be id types). 2652 ExprResult Res(ParseAssignmentExpression()); 2653 if (Res.isInvalid()) { 2654 // We must manually skip to a ']', otherwise the expression skipper will 2655 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2656 // the enclosing expression. 2657 SkipUntil(tok::r_square); 2658 return move(Res); 2659 } 2660 2661 // Parse the ellipsis that indicates a pack expansion. 2662 if (Tok.is(tok::ellipsis)) 2663 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); 2664 if (Res.isInvalid()) 2665 return true; 2666 2667 ElementExprs.push_back(Res.release()); 2668 2669 if (Tok.is(tok::comma)) 2670 ConsumeToken(); // Eat the ','. 2671 else if (Tok.isNot(tok::r_square)) 2672 return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma)); 2673 } 2674 SourceLocation EndLoc = ConsumeBracket(); // location of ']' 2675 MultiExprArg Args(Actions, ElementExprs.take(), ElementExprs.size()); 2676 return Owned(Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args)); 2677 } 2678 2679 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { 2680 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements. 2681 ConsumeBrace(); // consume the l_square. 2682 while (Tok.isNot(tok::r_brace)) { 2683 // Parse the comma separated key : value expressions. 2684 ExprResult KeyExpr; 2685 { 2686 ColonProtectionRAIIObject X(*this); 2687 KeyExpr = ParseAssignmentExpression(); 2688 if (KeyExpr.isInvalid()) { 2689 // We must manually skip to a '}', otherwise the expression skipper will 2690 // stop at the '}' when it skips to the ';'. We want it to skip beyond 2691 // the enclosing expression. 2692 SkipUntil(tok::r_brace); 2693 return move(KeyExpr); 2694 } 2695 } 2696 2697 if (Tok.is(tok::colon)) { 2698 ConsumeToken(); 2699 } else { 2700 return ExprError(Diag(Tok, diag::err_expected_colon)); 2701 } 2702 2703 ExprResult ValueExpr(ParseAssignmentExpression()); 2704 if (ValueExpr.isInvalid()) { 2705 // We must manually skip to a '}', otherwise the expression skipper will 2706 // stop at the '}' when it skips to the ';'. We want it to skip beyond 2707 // the enclosing expression. 2708 SkipUntil(tok::r_brace); 2709 return move(ValueExpr); 2710 } 2711 2712 // Parse the ellipsis that designates this as a pack expansion. 2713 SourceLocation EllipsisLoc; 2714 if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus) 2715 EllipsisLoc = ConsumeToken(); 2716 2717 // We have a valid expression. Collect it in a vector so we can 2718 // build the argument list. 2719 ObjCDictionaryElement Element = { 2720 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, llvm::Optional<unsigned>() 2721 }; 2722 Elements.push_back(Element); 2723 2724 if (Tok.is(tok::comma)) 2725 ConsumeToken(); // Eat the ','. 2726 else if (Tok.isNot(tok::r_brace)) 2727 return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma)); 2728 } 2729 SourceLocation EndLoc = ConsumeBrace(); 2730 2731 // Create the ObjCDictionaryLiteral. 2732 return Owned(Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc), 2733 Elements.data(), 2734 Elements.size())); 2735 } 2736 2737 /// objc-encode-expression: 2738 /// @encode ( type-name ) 2739 ExprResult 2740 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) { 2741 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!"); 2742 2743 SourceLocation EncLoc = ConsumeToken(); 2744 2745 if (Tok.isNot(tok::l_paren)) 2746 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode"); 2747 2748 BalancedDelimiterTracker T(*this, tok::l_paren); 2749 T.consumeOpen(); 2750 2751 TypeResult Ty = ParseTypeName(); 2752 2753 T.consumeClose(); 2754 2755 if (Ty.isInvalid()) 2756 return ExprError(); 2757 2758 return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, 2759 T.getOpenLocation(), Ty.get(), 2760 T.getCloseLocation())); 2761 } 2762 2763 /// objc-protocol-expression 2764 /// \@protocol ( protocol-name ) 2765 ExprResult 2766 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) { 2767 SourceLocation ProtoLoc = ConsumeToken(); 2768 2769 if (Tok.isNot(tok::l_paren)) 2770 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol"); 2771 2772 BalancedDelimiterTracker T(*this, tok::l_paren); 2773 T.consumeOpen(); 2774 2775 if (Tok.isNot(tok::identifier)) 2776 return ExprError(Diag(Tok, diag::err_expected_ident)); 2777 2778 IdentifierInfo *protocolId = Tok.getIdentifierInfo(); 2779 SourceLocation ProtoIdLoc = ConsumeToken(); 2780 2781 T.consumeClose(); 2782 2783 return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc, 2784 T.getOpenLocation(), 2785 ProtoIdLoc, 2786 T.getCloseLocation())); 2787 } 2788 2789 /// objc-selector-expression 2790 /// @selector '(' objc-keyword-selector ')' 2791 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { 2792 SourceLocation SelectorLoc = ConsumeToken(); 2793 2794 if (Tok.isNot(tok::l_paren)) 2795 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector"); 2796 2797 SmallVector<IdentifierInfo *, 12> KeyIdents; 2798 SourceLocation sLoc; 2799 2800 BalancedDelimiterTracker T(*this, tok::l_paren); 2801 T.consumeOpen(); 2802 2803 if (Tok.is(tok::code_completion)) { 2804 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(), 2805 KeyIdents.size()); 2806 cutOffParsing(); 2807 return ExprError(); 2808 } 2809 2810 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); 2811 if (!SelIdent && // missing selector name. 2812 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 2813 return ExprError(Diag(Tok, diag::err_expected_ident)); 2814 2815 KeyIdents.push_back(SelIdent); 2816 unsigned nColons = 0; 2817 if (Tok.isNot(tok::r_paren)) { 2818 while (1) { 2819 if (Tok.is(tok::coloncolon)) { // Handle :: in C++. 2820 ++nColons; 2821 KeyIdents.push_back(0); 2822 } else if (Tok.isNot(tok::colon)) 2823 return ExprError(Diag(Tok, diag::err_expected_colon)); 2824 2825 ++nColons; 2826 ConsumeToken(); // Eat the ':' or '::'. 2827 if (Tok.is(tok::r_paren)) 2828 break; 2829 2830 if (Tok.is(tok::code_completion)) { 2831 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(), 2832 KeyIdents.size()); 2833 cutOffParsing(); 2834 return ExprError(); 2835 } 2836 2837 // Check for another keyword selector. 2838 SourceLocation Loc; 2839 SelIdent = ParseObjCSelectorPiece(Loc); 2840 KeyIdents.push_back(SelIdent); 2841 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 2842 break; 2843 } 2844 } 2845 T.consumeClose(); 2846 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]); 2847 return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc, 2848 T.getOpenLocation(), 2849 T.getCloseLocation())); 2850 } 2851 2852 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { 2853 // MCDecl might be null due to error in method or c-function prototype, etc. 2854 Decl *MCDecl = LM.D; 2855 bool skip = MCDecl && 2856 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) || 2857 (!parseMethod && Actions.isObjCMethodDecl(MCDecl))); 2858 if (skip) 2859 return; 2860 2861 // Save the current token position. 2862 SourceLocation OrigLoc = Tok.getLocation(); 2863 2864 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!"); 2865 // Append the current token at the end of the new token stream so that it 2866 // doesn't get lost. 2867 LM.Toks.push_back(Tok); 2868 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false); 2869 2870 // Consume the previously pushed token. 2871 ConsumeAnyToken(); 2872 2873 assert(Tok.is(tok::l_brace) && "Inline objective-c method not starting with '{'"); 2874 SourceLocation BraceLoc = Tok.getLocation(); 2875 // Enter a scope for the method or c-fucntion body. 2876 ParseScope BodyScope(this, 2877 parseMethod 2878 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope 2879 : Scope::FnScope|Scope::DeclScope); 2880 2881 // Tell the actions module that we have entered a method or c-function definition 2882 // with the specified Declarator for the method/function. 2883 Actions.ActOnStartOfObjCMethodOrCFunctionDef(getCurScope(), MCDecl, parseMethod); 2884 2885 if (SkipFunctionBodies && trySkippingFunctionBody()) { 2886 BodyScope.Exit(); 2887 (void)Actions.ActOnFinishFunctionBody(MCDecl, 0); 2888 return; 2889 } 2890 2891 StmtResult FnBody(ParseCompoundStatementBody()); 2892 2893 // If the function body could not be parsed, make a bogus compoundstmt. 2894 if (FnBody.isInvalid()) { 2895 Sema::CompoundScopeRAII CompoundScope(Actions); 2896 FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc, 2897 MultiStmtArg(Actions), false); 2898 } 2899 2900 // Leave the function body scope. 2901 BodyScope.Exit(); 2902 2903 (void)Actions.ActOnFinishFunctionBody(MCDecl, FnBody.take()); 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