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