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 Decl *Parser::ParseObjCAtDirectives() { 33 SourceLocation AtLoc = ConsumeToken(); // the "@" 34 35 if (Tok.is(tok::code_completion)) { 36 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, false); 37 ConsumeCodeCompletionToken(); 38 } 39 40 switch (Tok.getObjCKeywordID()) { 41 case tok::objc_class: 42 return ParseObjCAtClassDeclaration(AtLoc); 43 case tok::objc_interface: 44 return ParseObjCAtInterfaceDeclaration(AtLoc); 45 case tok::objc_protocol: 46 return ParseObjCAtProtocolDeclaration(AtLoc); 47 case tok::objc_implementation: 48 return ParseObjCAtImplementationDeclaration(AtLoc); 49 case tok::objc_end: 50 return ParseObjCAtEndDeclaration(AtLoc); 51 case tok::objc_compatibility_alias: 52 return ParseObjCAtAliasDeclaration(AtLoc); 53 case tok::objc_synthesize: 54 return ParseObjCPropertySynthesize(AtLoc); 55 case tok::objc_dynamic: 56 return ParseObjCPropertyDynamic(AtLoc); 57 default: 58 Diag(AtLoc, diag::err_unexpected_at); 59 SkipUntil(tok::semi); 60 return 0; 61 } 62 } 63 64 /// 65 /// objc-class-declaration: 66 /// '@' 'class' identifier-list ';' 67 /// 68 Decl *Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { 69 ConsumeToken(); // the identifier "class" 70 llvm::SmallVector<IdentifierInfo *, 8> ClassNames; 71 llvm::SmallVector<SourceLocation, 8> ClassLocs; 72 73 74 while (1) { 75 if (Tok.isNot(tok::identifier)) { 76 Diag(Tok, diag::err_expected_ident); 77 SkipUntil(tok::semi); 78 return 0; 79 } 80 ClassNames.push_back(Tok.getIdentifierInfo()); 81 ClassLocs.push_back(Tok.getLocation()); 82 ConsumeToken(); 83 84 if (Tok.isNot(tok::comma)) 85 break; 86 87 ConsumeToken(); 88 } 89 90 // Consume the ';'. 91 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class")) 92 return 0; 93 94 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(), 95 ClassLocs.data(), 96 ClassNames.size()); 97 } 98 99 /// 100 /// objc-interface: 101 /// objc-class-interface-attributes[opt] objc-class-interface 102 /// objc-category-interface 103 /// 104 /// objc-class-interface: 105 /// '@' 'interface' identifier objc-superclass[opt] 106 /// objc-protocol-refs[opt] 107 /// objc-class-instance-variables[opt] 108 /// objc-interface-decl-list 109 /// @end 110 /// 111 /// objc-category-interface: 112 /// '@' 'interface' identifier '(' identifier[opt] ')' 113 /// objc-protocol-refs[opt] 114 /// objc-interface-decl-list 115 /// @end 116 /// 117 /// objc-superclass: 118 /// ':' identifier 119 /// 120 /// objc-class-interface-attributes: 121 /// __attribute__((visibility("default"))) 122 /// __attribute__((visibility("hidden"))) 123 /// __attribute__((deprecated)) 124 /// __attribute__((unavailable)) 125 /// __attribute__((objc_exception)) - used by NSException on 64-bit 126 /// 127 Decl *Parser::ParseObjCAtInterfaceDeclaration( 128 SourceLocation atLoc, AttributeList *attrList) { 129 assert(Tok.isObjCAtKeyword(tok::objc_interface) && 130 "ParseObjCAtInterfaceDeclaration(): Expected @interface"); 131 ConsumeToken(); // the "interface" identifier 132 133 // Code completion after '@interface'. 134 if (Tok.is(tok::code_completion)) { 135 Actions.CodeCompleteObjCInterfaceDecl(getCurScope()); 136 ConsumeCodeCompletionToken(); 137 } 138 139 if (Tok.isNot(tok::identifier)) { 140 Diag(Tok, diag::err_expected_ident); // missing class or category name. 141 return 0; 142 } 143 144 // We have a class or category name - consume it. 145 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 146 SourceLocation nameLoc = ConsumeToken(); 147 if (Tok.is(tok::l_paren) && 148 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. 149 SourceLocation lparenLoc = ConsumeParen(); 150 SourceLocation categoryLoc, rparenLoc; 151 IdentifierInfo *categoryId = 0; 152 if (Tok.is(tok::code_completion)) { 153 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc); 154 ConsumeCodeCompletionToken(); 155 } 156 157 // For ObjC2, the category name is optional (not an error). 158 if (Tok.is(tok::identifier)) { 159 categoryId = Tok.getIdentifierInfo(); 160 categoryLoc = ConsumeToken(); 161 } 162 else if (!getLang().ObjC2) { 163 Diag(Tok, diag::err_expected_ident); // missing category name. 164 return 0; 165 } 166 if (Tok.isNot(tok::r_paren)) { 167 Diag(Tok, diag::err_expected_rparen); 168 SkipUntil(tok::r_paren, false); // don't stop at ';' 169 return 0; 170 } 171 rparenLoc = ConsumeParen(); 172 // Next, we need to check for any protocol references. 173 SourceLocation LAngleLoc, EndProtoLoc; 174 llvm::SmallVector<Decl *, 8> ProtocolRefs; 175 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 176 if (Tok.is(tok::less) && 177 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, 178 LAngleLoc, EndProtoLoc)) 179 return 0; 180 181 if (attrList) // categories don't support attributes. 182 Diag(Tok, diag::err_objc_no_attributes_on_category); 183 184 Decl *CategoryType = 185 Actions.ActOnStartCategoryInterface(atLoc, 186 nameId, nameLoc, 187 categoryId, categoryLoc, 188 ProtocolRefs.data(), 189 ProtocolRefs.size(), 190 ProtocolLocs.data(), 191 EndProtoLoc); 192 if (Tok.is(tok::l_brace)) 193 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, 194 atLoc); 195 196 ParseObjCInterfaceDeclList(CategoryType, tok::objc_not_keyword); 197 return CategoryType; 198 } 199 // Parse a class interface. 200 IdentifierInfo *superClassId = 0; 201 SourceLocation superClassLoc; 202 203 if (Tok.is(tok::colon)) { // a super class is specified. 204 ConsumeToken(); 205 206 // Code completion of superclass names. 207 if (Tok.is(tok::code_completion)) { 208 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc); 209 ConsumeCodeCompletionToken(); 210 } 211 212 if (Tok.isNot(tok::identifier)) { 213 Diag(Tok, diag::err_expected_ident); // missing super class name. 214 return 0; 215 } 216 superClassId = Tok.getIdentifierInfo(); 217 superClassLoc = ConsumeToken(); 218 } 219 // Next, we need to check for any protocol references. 220 llvm::SmallVector<Decl *, 8> ProtocolRefs; 221 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 222 SourceLocation LAngleLoc, EndProtoLoc; 223 if (Tok.is(tok::less) && 224 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, 225 LAngleLoc, EndProtoLoc)) 226 return 0; 227 228 Decl *ClsType = 229 Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc, 230 superClassId, superClassLoc, 231 ProtocolRefs.data(), ProtocolRefs.size(), 232 ProtocolLocs.data(), 233 EndProtoLoc, attrList); 234 235 if (Tok.is(tok::l_brace)) 236 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, atLoc); 237 238 ParseObjCInterfaceDeclList(ClsType, tok::objc_interface); 239 return ClsType; 240 } 241 242 /// The Objective-C property callback. This should be defined where 243 /// it's used, but instead it's been lifted to here to support VS2005. 244 struct Parser::ObjCPropertyCallback : FieldCallback { 245 Parser &P; 246 Decl *IDecl; 247 llvm::SmallVectorImpl<Decl *> &Props; 248 ObjCDeclSpec &OCDS; 249 SourceLocation AtLoc; 250 tok::ObjCKeywordKind MethodImplKind; 251 252 ObjCPropertyCallback(Parser &P, Decl *IDecl, 253 llvm::SmallVectorImpl<Decl *> &Props, 254 ObjCDeclSpec &OCDS, SourceLocation AtLoc, 255 tok::ObjCKeywordKind MethodImplKind) : 256 P(P), IDecl(IDecl), Props(Props), OCDS(OCDS), AtLoc(AtLoc), 257 MethodImplKind(MethodImplKind) { 258 } 259 260 Decl *invoke(FieldDeclarator &FD) { 261 if (FD.D.getIdentifier() == 0) { 262 P.Diag(AtLoc, diag::err_objc_property_requires_field_name) 263 << FD.D.getSourceRange(); 264 return 0; 265 } 266 if (FD.BitfieldSize) { 267 P.Diag(AtLoc, diag::err_objc_property_bitfield) 268 << FD.D.getSourceRange(); 269 return 0; 270 } 271 272 // Install the property declarator into interfaceDecl. 273 IdentifierInfo *SelName = 274 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier(); 275 276 Selector GetterSel = 277 P.PP.getSelectorTable().getNullarySelector(SelName); 278 IdentifierInfo *SetterName = OCDS.getSetterName(); 279 Selector SetterSel; 280 if (SetterName) 281 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName); 282 else 283 SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(), 284 P.PP.getSelectorTable(), 285 FD.D.getIdentifier()); 286 bool isOverridingProperty = false; 287 Decl *Property = 288 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, FD, OCDS, 289 GetterSel, SetterSel, IDecl, 290 &isOverridingProperty, 291 MethodImplKind); 292 if (!isOverridingProperty) 293 Props.push_back(Property); 294 295 return Property; 296 } 297 }; 298 299 /// objc-interface-decl-list: 300 /// empty 301 /// objc-interface-decl-list objc-property-decl [OBJC2] 302 /// objc-interface-decl-list objc-method-requirement [OBJC2] 303 /// objc-interface-decl-list objc-method-proto ';' 304 /// objc-interface-decl-list declaration 305 /// objc-interface-decl-list ';' 306 /// 307 /// objc-method-requirement: [OBJC2] 308 /// @required 309 /// @optional 310 /// 311 void Parser::ParseObjCInterfaceDeclList(Decl *interfaceDecl, 312 tok::ObjCKeywordKind contextKey) { 313 llvm::SmallVector<Decl *, 32> allMethods; 314 llvm::SmallVector<Decl *, 16> allProperties; 315 llvm::SmallVector<DeclGroupPtrTy, 8> allTUVariables; 316 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; 317 318 SourceRange AtEnd; 319 320 while (1) { 321 // If this is a method prototype, parse it. 322 if (Tok.is(tok::minus) || Tok.is(tok::plus)) { 323 Decl *methodPrototype = 324 ParseObjCMethodPrototype(interfaceDecl, MethodImplKind); 325 allMethods.push_back(methodPrototype); 326 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for 327 // method definitions. 328 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_method_proto, 329 "", tok::semi); 330 continue; 331 } 332 if (Tok.is(tok::l_paren)) { 333 Diag(Tok, diag::err_expected_minus_or_plus); 334 ParseObjCMethodDecl(Tok.getLocation(), 335 tok::minus, 336 interfaceDecl, 337 MethodImplKind); 338 continue; 339 } 340 // Ignore excess semicolons. 341 if (Tok.is(tok::semi)) { 342 ConsumeToken(); 343 continue; 344 } 345 346 // If we got to the end of the file, exit the loop. 347 if (Tok.is(tok::eof)) 348 break; 349 350 // Code completion within an Objective-C interface. 351 if (Tok.is(tok::code_completion)) { 352 Actions.CodeCompleteOrdinaryName(getCurScope(), 353 ObjCImpDecl? Sema::PCC_ObjCImplementation 354 : Sema::PCC_ObjCInterface); 355 ConsumeCodeCompletionToken(); 356 } 357 358 // If we don't have an @ directive, parse it as a function definition. 359 if (Tok.isNot(tok::at)) { 360 // The code below does not consume '}'s because it is afraid of eating the 361 // end of a namespace. Because of the way this code is structured, an 362 // erroneous r_brace would cause an infinite loop if not handled here. 363 if (Tok.is(tok::r_brace)) 364 break; 365 366 // FIXME: as the name implies, this rule allows function definitions. 367 // We could pass a flag or check for functions during semantic analysis. 368 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(0)); 369 continue; 370 } 371 372 // Otherwise, we have an @ directive, eat the @. 373 SourceLocation AtLoc = ConsumeToken(); // the "@" 374 if (Tok.is(tok::code_completion)) { 375 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, true); 376 ConsumeCodeCompletionToken(); 377 break; 378 } 379 380 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID(); 381 382 if (DirectiveKind == tok::objc_end) { // @end -> terminate list 383 AtEnd.setBegin(AtLoc); 384 AtEnd.setEnd(Tok.getLocation()); 385 break; 386 } else if (DirectiveKind == tok::objc_not_keyword) { 387 Diag(Tok, diag::err_objc_unknown_at); 388 SkipUntil(tok::semi); 389 continue; 390 } 391 392 // Eat the identifier. 393 ConsumeToken(); 394 395 switch (DirectiveKind) { 396 default: 397 // FIXME: If someone forgets an @end on a protocol, this loop will 398 // continue to eat up tons of stuff and spew lots of nonsense errors. It 399 // would probably be better to bail out if we saw an @class or @interface 400 // or something like that. 401 Diag(AtLoc, diag::err_objc_illegal_interface_qual); 402 // Skip until we see an '@' or '}' or ';'. 403 SkipUntil(tok::r_brace, tok::at); 404 break; 405 406 case tok::objc_implementation: 407 case tok::objc_interface: 408 Diag(Tok, diag::err_objc_missing_end); 409 ConsumeToken(); 410 break; 411 412 case tok::objc_required: 413 case tok::objc_optional: 414 // This is only valid on protocols. 415 // FIXME: Should this check for ObjC2 being enabled? 416 if (contextKey != tok::objc_protocol) 417 Diag(AtLoc, diag::err_objc_directive_only_in_protocol); 418 else 419 MethodImplKind = DirectiveKind; 420 break; 421 422 case tok::objc_property: 423 if (!getLang().ObjC2) 424 Diag(AtLoc, diag::err_objc_properties_require_objc2); 425 426 ObjCDeclSpec OCDS; 427 // Parse property attribute list, if any. 428 if (Tok.is(tok::l_paren)) 429 ParseObjCPropertyAttribute(OCDS, interfaceDecl, 430 allMethods.data(), allMethods.size()); 431 432 ObjCPropertyCallback Callback(*this, interfaceDecl, allProperties, 433 OCDS, AtLoc, MethodImplKind); 434 435 // Parse all the comma separated declarators. 436 DeclSpec DS; 437 ParseStructDeclaration(DS, Callback); 438 439 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list, "", 440 tok::at); 441 break; 442 } 443 } 444 445 // We break out of the big loop in two cases: when we see @end or when we see 446 // EOF. In the former case, eat the @end. In the later case, emit an error. 447 if (Tok.is(tok::code_completion)) { 448 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, true); 449 ConsumeCodeCompletionToken(); 450 } else if (Tok.isObjCAtKeyword(tok::objc_end)) 451 ConsumeToken(); // the "end" identifier 452 else 453 Diag(Tok, diag::err_objc_missing_end); 454 455 // Insert collected methods declarations into the @interface object. 456 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit. 457 Actions.ActOnAtEnd(getCurScope(), AtEnd, interfaceDecl, 458 allMethods.data(), allMethods.size(), 459 allProperties.data(), allProperties.size(), 460 allTUVariables.data(), allTUVariables.size()); 461 } 462 463 /// Parse property attribute declarations. 464 /// 465 /// property-attr-decl: '(' property-attrlist ')' 466 /// property-attrlist: 467 /// property-attribute 468 /// property-attrlist ',' property-attribute 469 /// property-attribute: 470 /// getter '=' identifier 471 /// setter '=' identifier ':' 472 /// readonly 473 /// readwrite 474 /// assign 475 /// retain 476 /// copy 477 /// nonatomic 478 /// 479 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS, Decl *ClassDecl, 480 Decl **Methods, 481 unsigned NumMethods) { 482 assert(Tok.getKind() == tok::l_paren); 483 SourceLocation LHSLoc = ConsumeParen(); // consume '(' 484 485 while (1) { 486 if (Tok.is(tok::code_completion)) { 487 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS); 488 ConsumeCodeCompletionToken(); 489 } 490 const IdentifierInfo *II = Tok.getIdentifierInfo(); 491 492 // If this is not an identifier at all, bail out early. 493 if (II == 0) { 494 MatchRHSPunctuation(tok::r_paren, LHSLoc); 495 return; 496 } 497 498 SourceLocation AttrName = ConsumeToken(); // consume last attribute name 499 500 if (II->isStr("readonly")) 501 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly); 502 else if (II->isStr("assign")) 503 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign); 504 else if (II->isStr("readwrite")) 505 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite); 506 else if (II->isStr("retain")) 507 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain); 508 else if (II->isStr("copy")) 509 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy); 510 else if (II->isStr("nonatomic")) 511 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic); 512 else if (II->isStr("getter") || II->isStr("setter")) { 513 bool IsSetter = II->getNameStart()[0] == 's'; 514 515 // getter/setter require extra treatment. 516 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter : 517 diag::err_objc_expected_equal_for_getter; 518 519 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren)) 520 return; 521 522 if (Tok.is(tok::code_completion)) { 523 if (IsSetter) 524 Actions.CodeCompleteObjCPropertySetter(getCurScope(), ClassDecl, 525 Methods, NumMethods); 526 else 527 Actions.CodeCompleteObjCPropertyGetter(getCurScope(), ClassDecl, 528 Methods, NumMethods); 529 ConsumeCodeCompletionToken(); 530 } 531 532 533 SourceLocation SelLoc; 534 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc); 535 536 if (!SelIdent) { 537 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter) 538 << IsSetter; 539 SkipUntil(tok::r_paren); 540 return; 541 } 542 543 if (IsSetter) { 544 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter); 545 DS.setSetterName(SelIdent); 546 547 if (ExpectAndConsume(tok::colon, 548 diag::err_expected_colon_after_setter_name, "", 549 tok::r_paren)) 550 return; 551 } else { 552 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter); 553 DS.setGetterName(SelIdent); 554 } 555 } else { 556 Diag(AttrName, diag::err_objc_expected_property_attr) << II; 557 SkipUntil(tok::r_paren); 558 return; 559 } 560 561 if (Tok.isNot(tok::comma)) 562 break; 563 564 ConsumeToken(); 565 } 566 567 MatchRHSPunctuation(tok::r_paren, LHSLoc); 568 } 569 570 /// objc-method-proto: 571 /// objc-instance-method objc-method-decl objc-method-attributes[opt] 572 /// objc-class-method objc-method-decl objc-method-attributes[opt] 573 /// 574 /// objc-instance-method: '-' 575 /// objc-class-method: '+' 576 /// 577 /// objc-method-attributes: [OBJC2] 578 /// __attribute__((deprecated)) 579 /// 580 Decl *Parser::ParseObjCMethodPrototype(Decl *IDecl, 581 tok::ObjCKeywordKind MethodImplKind) { 582 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-"); 583 584 tok::TokenKind methodType = Tok.getKind(); 585 SourceLocation mLoc = ConsumeToken(); 586 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, IDecl,MethodImplKind); 587 // Since this rule is used for both method declarations and definitions, 588 // the caller is (optionally) responsible for consuming the ';'. 589 return MDecl; 590 } 591 592 /// objc-selector: 593 /// identifier 594 /// one of 595 /// enum struct union if else while do for switch case default 596 /// break continue return goto asm sizeof typeof __alignof 597 /// unsigned long const short volatile signed restrict _Complex 598 /// in out inout bycopy byref oneway int char float double void _Bool 599 /// 600 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) { 601 602 switch (Tok.getKind()) { 603 default: 604 return 0; 605 case tok::ampamp: 606 case tok::ampequal: 607 case tok::amp: 608 case tok::pipe: 609 case tok::tilde: 610 case tok::exclaim: 611 case tok::exclaimequal: 612 case tok::pipepipe: 613 case tok::pipeequal: 614 case tok::caret: 615 case tok::caretequal: { 616 std::string ThisTok(PP.getSpelling(Tok)); 617 if (isalpha(ThisTok[0])) { 618 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data()); 619 Tok.setKind(tok::identifier); 620 SelectorLoc = ConsumeToken(); 621 return II; 622 } 623 return 0; 624 } 625 626 case tok::identifier: 627 case tok::kw_asm: 628 case tok::kw_auto: 629 case tok::kw_bool: 630 case tok::kw_break: 631 case tok::kw_case: 632 case tok::kw_catch: 633 case tok::kw_char: 634 case tok::kw_class: 635 case tok::kw_const: 636 case tok::kw_const_cast: 637 case tok::kw_continue: 638 case tok::kw_default: 639 case tok::kw_delete: 640 case tok::kw_do: 641 case tok::kw_double: 642 case tok::kw_dynamic_cast: 643 case tok::kw_else: 644 case tok::kw_enum: 645 case tok::kw_explicit: 646 case tok::kw_export: 647 case tok::kw_extern: 648 case tok::kw_false: 649 case tok::kw_float: 650 case tok::kw_for: 651 case tok::kw_friend: 652 case tok::kw_goto: 653 case tok::kw_if: 654 case tok::kw_inline: 655 case tok::kw_int: 656 case tok::kw_long: 657 case tok::kw_mutable: 658 case tok::kw_namespace: 659 case tok::kw_new: 660 case tok::kw_operator: 661 case tok::kw_private: 662 case tok::kw_protected: 663 case tok::kw_public: 664 case tok::kw_register: 665 case tok::kw_reinterpret_cast: 666 case tok::kw_restrict: 667 case tok::kw_return: 668 case tok::kw_short: 669 case tok::kw_signed: 670 case tok::kw_sizeof: 671 case tok::kw_static: 672 case tok::kw_static_cast: 673 case tok::kw_struct: 674 case tok::kw_switch: 675 case tok::kw_template: 676 case tok::kw_this: 677 case tok::kw_throw: 678 case tok::kw_true: 679 case tok::kw_try: 680 case tok::kw_typedef: 681 case tok::kw_typeid: 682 case tok::kw_typename: 683 case tok::kw_typeof: 684 case tok::kw_union: 685 case tok::kw_unsigned: 686 case tok::kw_using: 687 case tok::kw_virtual: 688 case tok::kw_void: 689 case tok::kw_volatile: 690 case tok::kw_wchar_t: 691 case tok::kw_while: 692 case tok::kw__Bool: 693 case tok::kw__Complex: 694 case tok::kw___alignof: 695 IdentifierInfo *II = Tok.getIdentifierInfo(); 696 SelectorLoc = ConsumeToken(); 697 return II; 698 } 699 } 700 701 /// objc-for-collection-in: 'in' 702 /// 703 bool Parser::isTokIdentifier_in() const { 704 // FIXME: May have to do additional look-ahead to only allow for 705 // valid tokens following an 'in'; such as an identifier, unary operators, 706 // '[' etc. 707 return (getLang().ObjC2 && Tok.is(tok::identifier) && 708 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]); 709 } 710 711 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type 712 /// qualifier list and builds their bitmask representation in the input 713 /// argument. 714 /// 715 /// objc-type-qualifiers: 716 /// objc-type-qualifier 717 /// objc-type-qualifiers objc-type-qualifier 718 /// 719 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, bool IsParameter) { 720 while (1) { 721 if (Tok.is(tok::code_completion)) { 722 Actions.CodeCompleteObjCPassingType(getCurScope(), DS); 723 ConsumeCodeCompletionToken(); 724 } 725 726 if (Tok.isNot(tok::identifier)) 727 return; 728 729 const IdentifierInfo *II = Tok.getIdentifierInfo(); 730 for (unsigned i = 0; i != objc_NumQuals; ++i) { 731 if (II != ObjCTypeQuals[i]) 732 continue; 733 734 ObjCDeclSpec::ObjCDeclQualifier Qual; 735 switch (i) { 736 default: assert(0 && "Unknown decl qualifier"); 737 case objc_in: Qual = ObjCDeclSpec::DQ_In; break; 738 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break; 739 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break; 740 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break; 741 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break; 742 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break; 743 } 744 DS.setObjCDeclQualifier(Qual); 745 ConsumeToken(); 746 II = 0; 747 break; 748 } 749 750 // If this wasn't a recognized qualifier, bail out. 751 if (II) return; 752 } 753 } 754 755 /// objc-type-name: 756 /// '(' objc-type-qualifiers[opt] type-name ')' 757 /// '(' objc-type-qualifiers[opt] ')' 758 /// 759 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, bool IsParameter) { 760 assert(Tok.is(tok::l_paren) && "expected ("); 761 762 SourceLocation LParenLoc = ConsumeParen(); 763 SourceLocation TypeStartLoc = Tok.getLocation(); 764 765 // Parse type qualifiers, in, inout, etc. 766 ParseObjCTypeQualifierList(DS, IsParameter); 767 768 ParsedType Ty; 769 if (isTypeSpecifierQualifier()) { 770 TypeResult TypeSpec = ParseTypeName(); 771 if (!TypeSpec.isInvalid()) 772 Ty = TypeSpec.get(); 773 } 774 775 if (Tok.is(tok::r_paren)) 776 ConsumeParen(); 777 else if (Tok.getLocation() == TypeStartLoc) { 778 // If we didn't eat any tokens, then this isn't a type. 779 Diag(Tok, diag::err_expected_type); 780 SkipUntil(tok::r_paren); 781 } else { 782 // Otherwise, we found *something*, but didn't get a ')' in the right 783 // place. Emit an error then return what we have as the type. 784 MatchRHSPunctuation(tok::r_paren, LParenLoc); 785 } 786 return Ty; 787 } 788 789 /// objc-method-decl: 790 /// objc-selector 791 /// objc-keyword-selector objc-parmlist[opt] 792 /// objc-type-name objc-selector 793 /// objc-type-name objc-keyword-selector objc-parmlist[opt] 794 /// 795 /// objc-keyword-selector: 796 /// objc-keyword-decl 797 /// objc-keyword-selector objc-keyword-decl 798 /// 799 /// objc-keyword-decl: 800 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier 801 /// objc-selector ':' objc-keyword-attributes[opt] identifier 802 /// ':' objc-type-name objc-keyword-attributes[opt] identifier 803 /// ':' objc-keyword-attributes[opt] identifier 804 /// 805 /// objc-parmlist: 806 /// objc-parms objc-ellipsis[opt] 807 /// 808 /// objc-parms: 809 /// objc-parms , parameter-declaration 810 /// 811 /// objc-ellipsis: 812 /// , ... 813 /// 814 /// objc-keyword-attributes: [OBJC2] 815 /// __attribute__((unused)) 816 /// 817 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, 818 tok::TokenKind mType, 819 Decl *IDecl, 820 tok::ObjCKeywordKind MethodImplKind) { 821 ParsingDeclRAIIObject PD(*this); 822 823 if (Tok.is(tok::code_completion)) { 824 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 825 /*ReturnType=*/ ParsedType(), IDecl); 826 ConsumeCodeCompletionToken(); 827 } 828 829 // Parse the return type if present. 830 ParsedType ReturnType; 831 ObjCDeclSpec DSRet; 832 if (Tok.is(tok::l_paren)) 833 ReturnType = ParseObjCTypeName(DSRet, false); 834 835 // If attributes exist before the method, parse them. 836 AttributeList *MethodAttrs = 0; 837 if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) 838 MethodAttrs = ParseGNUAttributes(); 839 840 if (Tok.is(tok::code_completion)) { 841 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 842 ReturnType, IDecl); 843 ConsumeCodeCompletionToken(); 844 } 845 846 // Now parse the selector. 847 SourceLocation selLoc; 848 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc); 849 850 // An unnamed colon is valid. 851 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name. 852 Diag(Tok, diag::err_expected_selector_for_method) 853 << SourceRange(mLoc, Tok.getLocation()); 854 // Skip until we get a ; or {}. 855 SkipUntil(tok::r_brace); 856 return 0; 857 } 858 859 llvm::SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo; 860 if (Tok.isNot(tok::colon)) { 861 // If attributes exist after the method, parse them. 862 if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) 863 MethodAttrs = addAttributeLists(MethodAttrs, ParseGNUAttributes()); 864 865 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent); 866 Decl *Result 867 = Actions.ActOnMethodDeclaration(mLoc, Tok.getLocation(), 868 mType, IDecl, DSRet, ReturnType, Sel, 869 0, 870 CParamInfo.data(), CParamInfo.size(), 871 MethodAttrs, MethodImplKind); 872 PD.complete(Result); 873 return Result; 874 } 875 876 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents; 877 llvm::SmallVector<Sema::ObjCArgInfo, 12> ArgInfos; 878 879 while (1) { 880 Sema::ObjCArgInfo ArgInfo; 881 882 // Each iteration parses a single keyword argument. 883 if (Tok.isNot(tok::colon)) { 884 Diag(Tok, diag::err_expected_colon); 885 break; 886 } 887 ConsumeToken(); // Eat the ':'. 888 889 ArgInfo.Type = ParsedType(); 890 if (Tok.is(tok::l_paren)) // Parse the argument type if present. 891 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, true); 892 893 // If attributes exist before the argument name, parse them. 894 ArgInfo.ArgAttrs = 0; 895 if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) 896 ArgInfo.ArgAttrs = ParseGNUAttributes(); 897 898 // Code completion for the next piece of the selector. 899 if (Tok.is(tok::code_completion)) { 900 ConsumeCodeCompletionToken(); 901 KeyIdents.push_back(SelIdent); 902 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 903 mType == tok::minus, 904 /*AtParameterName=*/true, 905 ReturnType, 906 KeyIdents.data(), 907 KeyIdents.size()); 908 KeyIdents.pop_back(); 909 break; 910 } 911 912 if (Tok.isNot(tok::identifier)) { 913 Diag(Tok, diag::err_expected_ident); // missing argument name. 914 break; 915 } 916 917 ArgInfo.Name = Tok.getIdentifierInfo(); 918 ArgInfo.NameLoc = Tok.getLocation(); 919 ConsumeToken(); // Eat the identifier. 920 921 ArgInfos.push_back(ArgInfo); 922 KeyIdents.push_back(SelIdent); 923 924 // Code completion for the next piece of the selector. 925 if (Tok.is(tok::code_completion)) { 926 ConsumeCodeCompletionToken(); 927 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 928 mType == tok::minus, 929 /*AtParameterName=*/false, 930 ReturnType, 931 KeyIdents.data(), 932 KeyIdents.size()); 933 break; 934 } 935 936 // Check for another keyword selector. 937 SourceLocation Loc; 938 SelIdent = ParseObjCSelectorPiece(Loc); 939 if (!SelIdent && Tok.isNot(tok::colon)) 940 break; 941 // We have a selector or a colon, continue parsing. 942 } 943 944 bool isVariadic = false; 945 946 // Parse the (optional) parameter list. 947 while (Tok.is(tok::comma)) { 948 ConsumeToken(); 949 if (Tok.is(tok::ellipsis)) { 950 isVariadic = true; 951 ConsumeToken(); 952 break; 953 } 954 DeclSpec DS; 955 ParseDeclarationSpecifiers(DS); 956 // Parse the declarator. 957 Declarator ParmDecl(DS, Declarator::PrototypeContext); 958 ParseDeclarator(ParmDecl); 959 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 960 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 961 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 962 ParmDecl.getIdentifierLoc(), 963 Param, 964 0)); 965 966 } 967 968 // FIXME: Add support for optional parameter list... 969 // If attributes exist after the method, parse them. 970 if (getLang().ObjC2 && Tok.is(tok::kw___attribute)) 971 MethodAttrs = addAttributeLists(MethodAttrs, ParseGNUAttributes()); 972 973 if (KeyIdents.size() == 0) 974 return 0; 975 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(), 976 &KeyIdents[0]); 977 Decl *Result 978 = Actions.ActOnMethodDeclaration(mLoc, Tok.getLocation(), 979 mType, IDecl, DSRet, ReturnType, Sel, 980 &ArgInfos[0], 981 CParamInfo.data(), CParamInfo.size(), 982 MethodAttrs, 983 MethodImplKind, isVariadic); 984 PD.complete(Result); 985 return Result; 986 } 987 988 /// objc-protocol-refs: 989 /// '<' identifier-list '>' 990 /// 991 bool Parser:: 992 ParseObjCProtocolReferences(llvm::SmallVectorImpl<Decl *> &Protocols, 993 llvm::SmallVectorImpl<SourceLocation> &ProtocolLocs, 994 bool WarnOnDeclarations, 995 SourceLocation &LAngleLoc, SourceLocation &EndLoc) { 996 assert(Tok.is(tok::less) && "expected <"); 997 998 LAngleLoc = ConsumeToken(); // the "<" 999 1000 llvm::SmallVector<IdentifierLocPair, 8> ProtocolIdents; 1001 1002 while (1) { 1003 if (Tok.is(tok::code_completion)) { 1004 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(), 1005 ProtocolIdents.size()); 1006 ConsumeCodeCompletionToken(); 1007 } 1008 1009 if (Tok.isNot(tok::identifier)) { 1010 Diag(Tok, diag::err_expected_ident); 1011 SkipUntil(tok::greater); 1012 return true; 1013 } 1014 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(), 1015 Tok.getLocation())); 1016 ProtocolLocs.push_back(Tok.getLocation()); 1017 ConsumeToken(); 1018 1019 if (Tok.isNot(tok::comma)) 1020 break; 1021 ConsumeToken(); 1022 } 1023 1024 // Consume the '>'. 1025 if (Tok.isNot(tok::greater)) { 1026 Diag(Tok, diag::err_expected_greater); 1027 return true; 1028 } 1029 1030 EndLoc = ConsumeAnyToken(); 1031 1032 // Convert the list of protocols identifiers into a list of protocol decls. 1033 Actions.FindProtocolDeclaration(WarnOnDeclarations, 1034 &ProtocolIdents[0], ProtocolIdents.size(), 1035 Protocols); 1036 return false; 1037 } 1038 1039 /// \brief Parse the Objective-C protocol qualifiers that follow a typename 1040 /// in a decl-specifier-seq, starting at the '<'. 1041 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) { 1042 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'"); 1043 assert(getLang().ObjC1 && "Protocol qualifiers only exist in Objective-C"); 1044 SourceLocation LAngleLoc, EndProtoLoc; 1045 llvm::SmallVector<Decl *, 8> ProtocolDecl; 1046 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1047 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1048 LAngleLoc, EndProtoLoc); 1049 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1050 ProtocolLocs.data(), LAngleLoc); 1051 if (EndProtoLoc.isValid()) 1052 DS.SetRangeEnd(EndProtoLoc); 1053 return Result; 1054 } 1055 1056 1057 /// objc-class-instance-variables: 1058 /// '{' objc-instance-variable-decl-list[opt] '}' 1059 /// 1060 /// objc-instance-variable-decl-list: 1061 /// objc-visibility-spec 1062 /// objc-instance-variable-decl ';' 1063 /// ';' 1064 /// objc-instance-variable-decl-list objc-visibility-spec 1065 /// objc-instance-variable-decl-list objc-instance-variable-decl ';' 1066 /// objc-instance-variable-decl-list ';' 1067 /// 1068 /// objc-visibility-spec: 1069 /// @private 1070 /// @protected 1071 /// @public 1072 /// @package [OBJC2] 1073 /// 1074 /// objc-instance-variable-decl: 1075 /// struct-declaration 1076 /// 1077 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, 1078 tok::ObjCKeywordKind visibility, 1079 SourceLocation atLoc) { 1080 assert(Tok.is(tok::l_brace) && "expected {"); 1081 llvm::SmallVector<Decl *, 32> AllIvarDecls; 1082 1083 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); 1084 1085 SourceLocation LBraceLoc = ConsumeBrace(); // the "{" 1086 1087 // While we still have something to read, read the instance variables. 1088 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1089 // Each iteration of this loop reads one objc-instance-variable-decl. 1090 1091 // Check for extraneous top-level semicolon. 1092 if (Tok.is(tok::semi)) { 1093 Diag(Tok, diag::ext_extra_ivar_semi) 1094 << FixItHint::CreateRemoval(Tok.getLocation()); 1095 ConsumeToken(); 1096 continue; 1097 } 1098 1099 // Set the default visibility to private. 1100 if (Tok.is(tok::at)) { // parse objc-visibility-spec 1101 ConsumeToken(); // eat the @ sign 1102 1103 if (Tok.is(tok::code_completion)) { 1104 Actions.CodeCompleteObjCAtVisibility(getCurScope()); 1105 ConsumeCodeCompletionToken(); 1106 } 1107 1108 switch (Tok.getObjCKeywordID()) { 1109 case tok::objc_private: 1110 case tok::objc_public: 1111 case tok::objc_protected: 1112 case tok::objc_package: 1113 visibility = Tok.getObjCKeywordID(); 1114 ConsumeToken(); 1115 continue; 1116 default: 1117 Diag(Tok, diag::err_objc_illegal_visibility_spec); 1118 continue; 1119 } 1120 } 1121 1122 if (Tok.is(tok::code_completion)) { 1123 Actions.CodeCompleteOrdinaryName(getCurScope(), 1124 Sema::PCC_ObjCInstanceVariableList); 1125 ConsumeCodeCompletionToken(); 1126 } 1127 1128 struct ObjCIvarCallback : FieldCallback { 1129 Parser &P; 1130 Decl *IDecl; 1131 tok::ObjCKeywordKind visibility; 1132 llvm::SmallVectorImpl<Decl *> &AllIvarDecls; 1133 1134 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V, 1135 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) : 1136 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) { 1137 } 1138 1139 Decl *invoke(FieldDeclarator &FD) { 1140 // Install the declarator into the interface decl. 1141 Decl *Field 1142 = P.Actions.ActOnIvar(P.getCurScope(), 1143 FD.D.getDeclSpec().getSourceRange().getBegin(), 1144 IDecl, FD.D, FD.BitfieldSize, visibility); 1145 if (Field) 1146 AllIvarDecls.push_back(Field); 1147 return Field; 1148 } 1149 } Callback(*this, interfaceDecl, visibility, AllIvarDecls); 1150 1151 // Parse all the comma separated declarators. 1152 DeclSpec DS; 1153 ParseStructDeclaration(DS, Callback); 1154 1155 if (Tok.is(tok::semi)) { 1156 ConsumeToken(); 1157 } else { 1158 Diag(Tok, diag::err_expected_semi_decl_list); 1159 // Skip to end of block or statement 1160 SkipUntil(tok::r_brace, true, true); 1161 } 1162 } 1163 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1164 Actions.ActOnLastBitfield(RBraceLoc, interfaceDecl, AllIvarDecls); 1165 // Call ActOnFields() even if we don't have any decls. This is useful 1166 // for code rewriting tools that need to be aware of the empty list. 1167 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, 1168 AllIvarDecls.data(), AllIvarDecls.size(), 1169 LBraceLoc, RBraceLoc, 0); 1170 return; 1171 } 1172 1173 /// objc-protocol-declaration: 1174 /// objc-protocol-definition 1175 /// objc-protocol-forward-reference 1176 /// 1177 /// objc-protocol-definition: 1178 /// @protocol identifier 1179 /// objc-protocol-refs[opt] 1180 /// objc-interface-decl-list 1181 /// @end 1182 /// 1183 /// objc-protocol-forward-reference: 1184 /// @protocol identifier-list ';' 1185 /// 1186 /// "@protocol identifier ;" should be resolved as "@protocol 1187 /// identifier-list ;": objc-interface-decl-list may not start with a 1188 /// semicolon in the first alternative if objc-protocol-refs are omitted. 1189 Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, 1190 AttributeList *attrList) { 1191 assert(Tok.isObjCAtKeyword(tok::objc_protocol) && 1192 "ParseObjCAtProtocolDeclaration(): Expected @protocol"); 1193 ConsumeToken(); // the "protocol" identifier 1194 1195 if (Tok.is(tok::code_completion)) { 1196 Actions.CodeCompleteObjCProtocolDecl(getCurScope()); 1197 ConsumeCodeCompletionToken(); 1198 } 1199 1200 if (Tok.isNot(tok::identifier)) { 1201 Diag(Tok, diag::err_expected_ident); // missing protocol name. 1202 return 0; 1203 } 1204 // Save the protocol name, then consume it. 1205 IdentifierInfo *protocolName = Tok.getIdentifierInfo(); 1206 SourceLocation nameLoc = ConsumeToken(); 1207 1208 if (Tok.is(tok::semi)) { // forward declaration of one protocol. 1209 IdentifierLocPair ProtoInfo(protocolName, nameLoc); 1210 ConsumeToken(); 1211 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1, 1212 attrList); 1213 } 1214 1215 if (Tok.is(tok::comma)) { // list of forward declarations. 1216 llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs; 1217 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc)); 1218 1219 // Parse the list of forward declarations. 1220 while (1) { 1221 ConsumeToken(); // the ',' 1222 if (Tok.isNot(tok::identifier)) { 1223 Diag(Tok, diag::err_expected_ident); 1224 SkipUntil(tok::semi); 1225 return 0; 1226 } 1227 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(), 1228 Tok.getLocation())); 1229 ConsumeToken(); // the identifier 1230 1231 if (Tok.isNot(tok::comma)) 1232 break; 1233 } 1234 // Consume the ';'. 1235 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol")) 1236 return 0; 1237 1238 return Actions.ActOnForwardProtocolDeclaration(AtLoc, 1239 &ProtocolRefs[0], 1240 ProtocolRefs.size(), 1241 attrList); 1242 } 1243 1244 // Last, and definitely not least, parse a protocol declaration. 1245 SourceLocation LAngleLoc, EndProtoLoc; 1246 1247 llvm::SmallVector<Decl *, 8> ProtocolRefs; 1248 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1249 if (Tok.is(tok::less) && 1250 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, 1251 LAngleLoc, EndProtoLoc)) 1252 return 0; 1253 1254 Decl *ProtoType = 1255 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc, 1256 ProtocolRefs.data(), 1257 ProtocolRefs.size(), 1258 ProtocolLocs.data(), 1259 EndProtoLoc, attrList); 1260 ParseObjCInterfaceDeclList(ProtoType, tok::objc_protocol); 1261 return ProtoType; 1262 } 1263 1264 /// objc-implementation: 1265 /// objc-class-implementation-prologue 1266 /// objc-category-implementation-prologue 1267 /// 1268 /// objc-class-implementation-prologue: 1269 /// @implementation identifier objc-superclass[opt] 1270 /// objc-class-instance-variables[opt] 1271 /// 1272 /// objc-category-implementation-prologue: 1273 /// @implementation identifier ( identifier ) 1274 Decl *Parser::ParseObjCAtImplementationDeclaration( 1275 SourceLocation atLoc) { 1276 assert(Tok.isObjCAtKeyword(tok::objc_implementation) && 1277 "ParseObjCAtImplementationDeclaration(): Expected @implementation"); 1278 ConsumeToken(); // the "implementation" identifier 1279 1280 // Code completion after '@implementation'. 1281 if (Tok.is(tok::code_completion)) { 1282 Actions.CodeCompleteObjCImplementationDecl(getCurScope()); 1283 ConsumeCodeCompletionToken(); 1284 } 1285 1286 if (Tok.isNot(tok::identifier)) { 1287 Diag(Tok, diag::err_expected_ident); // missing class or category name. 1288 return 0; 1289 } 1290 // We have a class or category name - consume it. 1291 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 1292 SourceLocation nameLoc = ConsumeToken(); // consume class or category name 1293 1294 if (Tok.is(tok::l_paren)) { 1295 // we have a category implementation. 1296 SourceLocation lparenLoc = ConsumeParen(); 1297 SourceLocation categoryLoc, rparenLoc; 1298 IdentifierInfo *categoryId = 0; 1299 1300 if (Tok.is(tok::code_completion)) { 1301 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc); 1302 ConsumeCodeCompletionToken(); 1303 } 1304 1305 if (Tok.is(tok::identifier)) { 1306 categoryId = Tok.getIdentifierInfo(); 1307 categoryLoc = ConsumeToken(); 1308 } else { 1309 Diag(Tok, diag::err_expected_ident); // missing category name. 1310 return 0; 1311 } 1312 if (Tok.isNot(tok::r_paren)) { 1313 Diag(Tok, diag::err_expected_rparen); 1314 SkipUntil(tok::r_paren, false); // don't stop at ';' 1315 return 0; 1316 } 1317 rparenLoc = ConsumeParen(); 1318 Decl *ImplCatType = Actions.ActOnStartCategoryImplementation( 1319 atLoc, nameId, nameLoc, categoryId, 1320 categoryLoc); 1321 ObjCImpDecl = ImplCatType; 1322 PendingObjCImpDecl.push_back(ObjCImpDecl); 1323 return 0; 1324 } 1325 // We have a class implementation 1326 SourceLocation superClassLoc; 1327 IdentifierInfo *superClassId = 0; 1328 if (Tok.is(tok::colon)) { 1329 // We have a super class 1330 ConsumeToken(); 1331 if (Tok.isNot(tok::identifier)) { 1332 Diag(Tok, diag::err_expected_ident); // missing super class name. 1333 return 0; 1334 } 1335 superClassId = Tok.getIdentifierInfo(); 1336 superClassLoc = ConsumeToken(); // Consume super class name 1337 } 1338 Decl *ImplClsType = Actions.ActOnStartClassImplementation( 1339 atLoc, nameId, nameLoc, 1340 superClassId, superClassLoc); 1341 1342 if (Tok.is(tok::l_brace)) // we have ivars 1343 ParseObjCClassInstanceVariables(ImplClsType/*FIXME*/, 1344 tok::objc_private, atLoc); 1345 ObjCImpDecl = ImplClsType; 1346 PendingObjCImpDecl.push_back(ObjCImpDecl); 1347 1348 return 0; 1349 } 1350 1351 Decl *Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) { 1352 assert(Tok.isObjCAtKeyword(tok::objc_end) && 1353 "ParseObjCAtEndDeclaration(): Expected @end"); 1354 Decl *Result = ObjCImpDecl; 1355 ConsumeToken(); // the "end" identifier 1356 if (ObjCImpDecl) { 1357 Actions.ActOnAtEnd(getCurScope(), atEnd, ObjCImpDecl); 1358 ObjCImpDecl = 0; 1359 PendingObjCImpDecl.pop_back(); 1360 } 1361 else { 1362 // missing @implementation 1363 Diag(atEnd.getBegin(), diag::warn_expected_implementation); 1364 } 1365 return Result; 1366 } 1367 1368 Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() { 1369 Actions.DiagnoseUseOfUnimplementedSelectors(); 1370 if (PendingObjCImpDecl.empty()) 1371 return Actions.ConvertDeclToDeclGroup(0); 1372 Decl *ImpDecl = PendingObjCImpDecl.pop_back_val(); 1373 Actions.ActOnAtEnd(getCurScope(), SourceRange(), ImpDecl); 1374 return Actions.ConvertDeclToDeclGroup(ImpDecl); 1375 } 1376 1377 /// compatibility-alias-decl: 1378 /// @compatibility_alias alias-name class-name ';' 1379 /// 1380 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) { 1381 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) && 1382 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias"); 1383 ConsumeToken(); // consume compatibility_alias 1384 if (Tok.isNot(tok::identifier)) { 1385 Diag(Tok, diag::err_expected_ident); 1386 return 0; 1387 } 1388 IdentifierInfo *aliasId = Tok.getIdentifierInfo(); 1389 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name 1390 if (Tok.isNot(tok::identifier)) { 1391 Diag(Tok, diag::err_expected_ident); 1392 return 0; 1393 } 1394 IdentifierInfo *classId = Tok.getIdentifierInfo(); 1395 SourceLocation classLoc = ConsumeToken(); // consume class-name; 1396 if (Tok.isNot(tok::semi)) { 1397 Diag(Tok, diag::err_expected_semi_after) << "@compatibility_alias"; 1398 return 0; 1399 } 1400 return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc, 1401 classId, classLoc); 1402 } 1403 1404 /// property-synthesis: 1405 /// @synthesize property-ivar-list ';' 1406 /// 1407 /// property-ivar-list: 1408 /// property-ivar 1409 /// property-ivar-list ',' property-ivar 1410 /// 1411 /// property-ivar: 1412 /// identifier 1413 /// identifier '=' identifier 1414 /// 1415 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { 1416 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) && 1417 "ParseObjCPropertyDynamic(): Expected '@synthesize'"); 1418 SourceLocation loc = ConsumeToken(); // consume synthesize 1419 1420 while (true) { 1421 if (Tok.is(tok::code_completion)) { 1422 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl); 1423 ConsumeCodeCompletionToken(); 1424 } 1425 1426 if (Tok.isNot(tok::identifier)) { 1427 Diag(Tok, diag::err_synthesized_property_name); 1428 SkipUntil(tok::semi); 1429 return 0; 1430 } 1431 1432 IdentifierInfo *propertyIvar = 0; 1433 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1434 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1435 SourceLocation propertyIvarLoc; 1436 if (Tok.is(tok::equal)) { 1437 // property '=' ivar-name 1438 ConsumeToken(); // consume '=' 1439 1440 if (Tok.is(tok::code_completion)) { 1441 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId, 1442 ObjCImpDecl); 1443 ConsumeCodeCompletionToken(); 1444 } 1445 1446 if (Tok.isNot(tok::identifier)) { 1447 Diag(Tok, diag::err_expected_ident); 1448 break; 1449 } 1450 propertyIvar = Tok.getIdentifierInfo(); 1451 propertyIvarLoc = ConsumeToken(); // consume ivar-name 1452 } 1453 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, ObjCImpDecl, 1454 propertyId, propertyIvar, propertyIvarLoc); 1455 if (Tok.isNot(tok::comma)) 1456 break; 1457 ConsumeToken(); // consume ',' 1458 } 1459 if (Tok.isNot(tok::semi)) { 1460 Diag(Tok, diag::err_expected_semi_after) << "@synthesize"; 1461 SkipUntil(tok::semi); 1462 } 1463 else 1464 ConsumeToken(); // consume ';' 1465 return 0; 1466 } 1467 1468 /// property-dynamic: 1469 /// @dynamic property-list 1470 /// 1471 /// property-list: 1472 /// identifier 1473 /// property-list ',' identifier 1474 /// 1475 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { 1476 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) && 1477 "ParseObjCPropertyDynamic(): Expected '@dynamic'"); 1478 SourceLocation loc = ConsumeToken(); // consume dynamic 1479 while (true) { 1480 if (Tok.is(tok::code_completion)) { 1481 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl); 1482 ConsumeCodeCompletionToken(); 1483 } 1484 1485 if (Tok.isNot(tok::identifier)) { 1486 Diag(Tok, diag::err_expected_ident); 1487 SkipUntil(tok::semi); 1488 return 0; 1489 } 1490 1491 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1492 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1493 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, ObjCImpDecl, 1494 propertyId, 0, SourceLocation()); 1495 1496 if (Tok.isNot(tok::comma)) 1497 break; 1498 ConsumeToken(); // consume ',' 1499 } 1500 if (Tok.isNot(tok::semi)) { 1501 Diag(Tok, diag::err_expected_semi_after) << "@dynamic"; 1502 SkipUntil(tok::semi); 1503 } 1504 else 1505 ConsumeToken(); // consume ';' 1506 return 0; 1507 } 1508 1509 /// objc-throw-statement: 1510 /// throw expression[opt]; 1511 /// 1512 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) { 1513 ExprResult Res; 1514 ConsumeToken(); // consume throw 1515 if (Tok.isNot(tok::semi)) { 1516 Res = ParseExpression(); 1517 if (Res.isInvalid()) { 1518 SkipUntil(tok::semi); 1519 return StmtError(); 1520 } 1521 } 1522 // consume ';' 1523 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw"); 1524 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope()); 1525 } 1526 1527 /// objc-synchronized-statement: 1528 /// @synchronized '(' expression ')' compound-statement 1529 /// 1530 StmtResult 1531 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) { 1532 ConsumeToken(); // consume synchronized 1533 if (Tok.isNot(tok::l_paren)) { 1534 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized"; 1535 return StmtError(); 1536 } 1537 ConsumeParen(); // '(' 1538 ExprResult Res(ParseExpression()); 1539 if (Res.isInvalid()) { 1540 SkipUntil(tok::semi); 1541 return StmtError(); 1542 } 1543 if (Tok.isNot(tok::r_paren)) { 1544 Diag(Tok, diag::err_expected_lbrace); 1545 return StmtError(); 1546 } 1547 ConsumeParen(); // ')' 1548 if (Tok.isNot(tok::l_brace)) { 1549 Diag(Tok, diag::err_expected_lbrace); 1550 return StmtError(); 1551 } 1552 // Enter a scope to hold everything within the compound stmt. Compound 1553 // statements can always hold declarations. 1554 ParseScope BodyScope(this, Scope::DeclScope); 1555 1556 StmtResult SynchBody(ParseCompoundStatementBody()); 1557 1558 BodyScope.Exit(); 1559 if (SynchBody.isInvalid()) 1560 SynchBody = Actions.ActOnNullStmt(Tok.getLocation()); 1561 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, Res.take(), SynchBody.take()); 1562 } 1563 1564 /// objc-try-catch-statement: 1565 /// @try compound-statement objc-catch-list[opt] 1566 /// @try compound-statement objc-catch-list[opt] @finally compound-statement 1567 /// 1568 /// objc-catch-list: 1569 /// @catch ( parameter-declaration ) compound-statement 1570 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement 1571 /// catch-parameter-declaration: 1572 /// parameter-declaration 1573 /// '...' [OBJC2] 1574 /// 1575 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { 1576 bool catch_or_finally_seen = false; 1577 1578 ConsumeToken(); // consume try 1579 if (Tok.isNot(tok::l_brace)) { 1580 Diag(Tok, diag::err_expected_lbrace); 1581 return StmtError(); 1582 } 1583 StmtVector CatchStmts(Actions); 1584 StmtResult FinallyStmt; 1585 ParseScope TryScope(this, Scope::DeclScope); 1586 StmtResult TryBody(ParseCompoundStatementBody()); 1587 TryScope.Exit(); 1588 if (TryBody.isInvalid()) 1589 TryBody = Actions.ActOnNullStmt(Tok.getLocation()); 1590 1591 while (Tok.is(tok::at)) { 1592 // At this point, we need to lookahead to determine if this @ is the start 1593 // of an @catch or @finally. We don't want to consume the @ token if this 1594 // is an @try or @encode or something else. 1595 Token AfterAt = GetLookAheadToken(1); 1596 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) && 1597 !AfterAt.isObjCAtKeyword(tok::objc_finally)) 1598 break; 1599 1600 SourceLocation AtCatchFinallyLoc = ConsumeToken(); 1601 if (Tok.isObjCAtKeyword(tok::objc_catch)) { 1602 Decl *FirstPart = 0; 1603 ConsumeToken(); // consume catch 1604 if (Tok.is(tok::l_paren)) { 1605 ConsumeParen(); 1606 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope); 1607 if (Tok.isNot(tok::ellipsis)) { 1608 DeclSpec DS; 1609 ParseDeclarationSpecifiers(DS); 1610 // For some odd reason, the name of the exception variable is 1611 // optional. As a result, we need to use "PrototypeContext", because 1612 // we must accept either 'declarator' or 'abstract-declarator' here. 1613 Declarator ParmDecl(DS, Declarator::PrototypeContext); 1614 ParseDeclarator(ParmDecl); 1615 1616 // Inform the actions module about the declarator, so it 1617 // gets added to the current scope. 1618 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl); 1619 } else 1620 ConsumeToken(); // consume '...' 1621 1622 SourceLocation RParenLoc; 1623 1624 if (Tok.is(tok::r_paren)) 1625 RParenLoc = ConsumeParen(); 1626 else // Skip over garbage, until we get to ')'. Eat the ')'. 1627 SkipUntil(tok::r_paren, true, false); 1628 1629 StmtResult CatchBody(true); 1630 if (Tok.is(tok::l_brace)) 1631 CatchBody = ParseCompoundStatementBody(); 1632 else 1633 Diag(Tok, diag::err_expected_lbrace); 1634 if (CatchBody.isInvalid()) 1635 CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); 1636 1637 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, 1638 RParenLoc, 1639 FirstPart, 1640 CatchBody.take()); 1641 if (!Catch.isInvalid()) 1642 CatchStmts.push_back(Catch.release()); 1643 1644 } else { 1645 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) 1646 << "@catch clause"; 1647 return StmtError(); 1648 } 1649 catch_or_finally_seen = true; 1650 } else { 1651 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?"); 1652 ConsumeToken(); // consume finally 1653 ParseScope FinallyScope(this, Scope::DeclScope); 1654 1655 StmtResult FinallyBody(true); 1656 if (Tok.is(tok::l_brace)) 1657 FinallyBody = ParseCompoundStatementBody(); 1658 else 1659 Diag(Tok, diag::err_expected_lbrace); 1660 if (FinallyBody.isInvalid()) 1661 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation()); 1662 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc, 1663 FinallyBody.take()); 1664 catch_or_finally_seen = true; 1665 break; 1666 } 1667 } 1668 if (!catch_or_finally_seen) { 1669 Diag(atLoc, diag::err_missing_catch_finally); 1670 return StmtError(); 1671 } 1672 1673 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(), 1674 move_arg(CatchStmts), 1675 FinallyStmt.take()); 1676 } 1677 1678 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}' 1679 /// 1680 Decl *Parser::ParseObjCMethodDefinition() { 1681 Decl *MDecl = ParseObjCMethodPrototype(ObjCImpDecl); 1682 1683 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(), 1684 "parsing Objective-C method"); 1685 1686 // parse optional ';' 1687 if (Tok.is(tok::semi)) { 1688 if (ObjCImpDecl) { 1689 Diag(Tok, diag::warn_semicolon_before_method_body) 1690 << FixItHint::CreateRemoval(Tok.getLocation()); 1691 } 1692 ConsumeToken(); 1693 } 1694 1695 // We should have an opening brace now. 1696 if (Tok.isNot(tok::l_brace)) { 1697 Diag(Tok, diag::err_expected_method_body); 1698 1699 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1700 SkipUntil(tok::l_brace, true, true); 1701 1702 // If we didn't find the '{', bail out. 1703 if (Tok.isNot(tok::l_brace)) 1704 return 0; 1705 } 1706 SourceLocation BraceLoc = Tok.getLocation(); 1707 1708 // Enter a scope for the method body. 1709 ParseScope BodyScope(this, 1710 Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope); 1711 1712 // Tell the actions module that we have entered a method definition with the 1713 // specified Declarator for the method. 1714 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl); 1715 1716 StmtResult FnBody(ParseCompoundStatementBody()); 1717 1718 // If the function body could not be parsed, make a bogus compoundstmt. 1719 if (FnBody.isInvalid()) 1720 FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc, 1721 MultiStmtArg(Actions), false); 1722 1723 // TODO: Pass argument information. 1724 Actions.ActOnFinishFunctionBody(MDecl, FnBody.take()); 1725 1726 // Leave the function body scope. 1727 BodyScope.Exit(); 1728 1729 return MDecl; 1730 } 1731 1732 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { 1733 if (Tok.is(tok::code_completion)) { 1734 Actions.CodeCompleteObjCAtStatement(getCurScope()); 1735 ConsumeCodeCompletionToken(); 1736 return StmtError(); 1737 } 1738 1739 if (Tok.isObjCAtKeyword(tok::objc_try)) 1740 return ParseObjCTryStmt(AtLoc); 1741 1742 if (Tok.isObjCAtKeyword(tok::objc_throw)) 1743 return ParseObjCThrowStmt(AtLoc); 1744 1745 if (Tok.isObjCAtKeyword(tok::objc_synchronized)) 1746 return ParseObjCSynchronizedStmt(AtLoc); 1747 1748 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc)); 1749 if (Res.isInvalid()) { 1750 // If the expression is invalid, skip ahead to the next semicolon. Not 1751 // doing this opens us up to the possibility of infinite loops if 1752 // ParseExpression does not consume any tokens. 1753 SkipUntil(tok::semi); 1754 return StmtError(); 1755 } 1756 1757 // Otherwise, eat the semicolon. 1758 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 1759 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take())); 1760 } 1761 1762 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { 1763 switch (Tok.getKind()) { 1764 case tok::code_completion: 1765 Actions.CodeCompleteObjCAtExpression(getCurScope()); 1766 ConsumeCodeCompletionToken(); 1767 return ExprError(); 1768 1769 case tok::string_literal: // primary-expression: string-literal 1770 case tok::wide_string_literal: 1771 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc)); 1772 default: 1773 if (Tok.getIdentifierInfo() == 0) 1774 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 1775 1776 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) { 1777 case tok::objc_encode: 1778 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc)); 1779 case tok::objc_protocol: 1780 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc)); 1781 case tok::objc_selector: 1782 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc)); 1783 default: 1784 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 1785 } 1786 } 1787 } 1788 1789 /// \brirg Parse the receiver of an Objective-C++ message send. 1790 /// 1791 /// This routine parses the receiver of a message send in 1792 /// Objective-C++ either as a type or as an expression. Note that this 1793 /// routine must not be called to parse a send to 'super', since it 1794 /// has no way to return such a result. 1795 /// 1796 /// \param IsExpr Whether the receiver was parsed as an expression. 1797 /// 1798 /// \param TypeOrExpr If the receiver was parsed as an expression (\c 1799 /// IsExpr is true), the parsed expression. If the receiver was parsed 1800 /// as a type (\c IsExpr is false), the parsed type. 1801 /// 1802 /// \returns True if an error occurred during parsing or semantic 1803 /// analysis, in which case the arguments do not have valid 1804 /// values. Otherwise, returns false for a successful parse. 1805 /// 1806 /// objc-receiver: [C++] 1807 /// 'super' [not parsed here] 1808 /// expression 1809 /// simple-type-specifier 1810 /// typename-specifier 1811 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { 1812 InMessageExpressionRAIIObject InMessage(*this, true); 1813 1814 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1815 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)) 1816 TryAnnotateTypeOrScopeToken(); 1817 1818 if (!isCXXSimpleTypeSpecifier()) { 1819 // objc-receiver: 1820 // expression 1821 ExprResult Receiver = ParseExpression(); 1822 if (Receiver.isInvalid()) 1823 return true; 1824 1825 IsExpr = true; 1826 TypeOrExpr = Receiver.take(); 1827 return false; 1828 } 1829 1830 // objc-receiver: 1831 // typename-specifier 1832 // simple-type-specifier 1833 // expression (that starts with one of the above) 1834 DeclSpec DS; 1835 ParseCXXSimpleTypeSpecifier(DS); 1836 1837 if (Tok.is(tok::l_paren)) { 1838 // If we see an opening parentheses at this point, we are 1839 // actually parsing an expression that starts with a 1840 // function-style cast, e.g., 1841 // 1842 // postfix-expression: 1843 // simple-type-specifier ( expression-list [opt] ) 1844 // typename-specifier ( expression-list [opt] ) 1845 // 1846 // Parse the remainder of this case, then the (optional) 1847 // postfix-expression suffix, followed by the (optional) 1848 // right-hand side of the binary expression. We have an 1849 // instance method. 1850 ExprResult Receiver = ParseCXXTypeConstructExpression(DS); 1851 if (!Receiver.isInvalid()) 1852 Receiver = ParsePostfixExpressionSuffix(Receiver.take()); 1853 if (!Receiver.isInvalid()) 1854 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma); 1855 if (Receiver.isInvalid()) 1856 return true; 1857 1858 IsExpr = true; 1859 TypeOrExpr = Receiver.take(); 1860 return false; 1861 } 1862 1863 // We have a class message. Turn the simple-type-specifier or 1864 // typename-specifier we parsed into a type and parse the 1865 // remainder of the class message. 1866 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 1867 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 1868 if (Type.isInvalid()) 1869 return true; 1870 1871 IsExpr = false; 1872 TypeOrExpr = Type.get().getAsOpaquePtr(); 1873 return false; 1874 } 1875 1876 /// \brief Determine whether the parser is currently referring to a an 1877 /// Objective-C message send, using a simplified heuristic to avoid overhead. 1878 /// 1879 /// This routine will only return true for a subset of valid message-send 1880 /// expressions. 1881 bool Parser::isSimpleObjCMessageExpression() { 1882 assert(Tok.is(tok::l_square) && getLang().ObjC1 && 1883 "Incorrect start for isSimpleObjCMessageExpression"); 1884 return GetLookAheadToken(1).is(tok::identifier) && 1885 GetLookAheadToken(2).is(tok::identifier); 1886 } 1887 1888 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { 1889 if (!getLang().ObjC1 || !NextToken().is(tok::identifier) || 1890 InMessageExpression) 1891 return false; 1892 1893 1894 ParsedType Type; 1895 1896 if (Tok.is(tok::annot_typename)) 1897 Type = getTypeAnnotation(Tok); 1898 else if (Tok.is(tok::identifier)) 1899 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), 1900 getCurScope()); 1901 else 1902 return false; 1903 1904 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { 1905 const Token &AfterNext = GetLookAheadToken(2); 1906 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) { 1907 if (Tok.is(tok::identifier)) 1908 TryAnnotateTypeOrScopeToken(); 1909 1910 return Tok.is(tok::annot_typename); 1911 } 1912 } 1913 1914 return false; 1915 } 1916 1917 /// objc-message-expr: 1918 /// '[' objc-receiver objc-message-args ']' 1919 /// 1920 /// objc-receiver: [C] 1921 /// 'super' 1922 /// expression 1923 /// class-name 1924 /// type-name 1925 /// 1926 ExprResult Parser::ParseObjCMessageExpression() { 1927 assert(Tok.is(tok::l_square) && "'[' expected"); 1928 SourceLocation LBracLoc = ConsumeBracket(); // consume '[' 1929 1930 if (Tok.is(tok::code_completion)) { 1931 Actions.CodeCompleteObjCMessageReceiver(getCurScope()); 1932 ConsumeCodeCompletionToken(); 1933 SkipUntil(tok::r_square); 1934 return ExprError(); 1935 } 1936 1937 InMessageExpressionRAIIObject InMessage(*this, true); 1938 1939 if (getLang().CPlusPlus) { 1940 // We completely separate the C and C++ cases because C++ requires 1941 // more complicated (read: slower) parsing. 1942 1943 // Handle send to super. 1944 // FIXME: This doesn't benefit from the same typo-correction we 1945 // get in Objective-C. 1946 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && 1947 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) 1948 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 1949 ParsedType(), 0); 1950 1951 // Parse the receiver, which is either a type or an expression. 1952 bool IsExpr; 1953 void *TypeOrExpr = NULL; 1954 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { 1955 SkipUntil(tok::r_square); 1956 return ExprError(); 1957 } 1958 1959 if (IsExpr) 1960 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 1961 ParsedType(), 1962 static_cast<Expr*>(TypeOrExpr)); 1963 1964 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 1965 ParsedType::getFromOpaquePtr(TypeOrExpr), 1966 0); 1967 } 1968 1969 if (Tok.is(tok::identifier)) { 1970 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1971 SourceLocation NameLoc = Tok.getLocation(); 1972 ParsedType ReceiverType; 1973 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc, 1974 Name == Ident_super, 1975 NextToken().is(tok::period), 1976 ReceiverType)) { 1977 case Sema::ObjCSuperMessage: 1978 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 1979 ParsedType(), 0); 1980 1981 case Sema::ObjCClassMessage: 1982 if (!ReceiverType) { 1983 SkipUntil(tok::r_square); 1984 return ExprError(); 1985 } 1986 1987 ConsumeToken(); // the type name 1988 1989 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 1990 ReceiverType, 0); 1991 1992 case Sema::ObjCInstanceMessage: 1993 // Fall through to parse an expression. 1994 break; 1995 } 1996 } 1997 1998 // Otherwise, an arbitrary expression can be the receiver of a send. 1999 ExprResult Res(ParseExpression()); 2000 if (Res.isInvalid()) { 2001 SkipUntil(tok::r_square); 2002 return move(Res); 2003 } 2004 2005 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2006 ParsedType(), Res.take()); 2007 } 2008 2009 /// \brief Parse the remainder of an Objective-C message following the 2010 /// '[' objc-receiver. 2011 /// 2012 /// This routine handles sends to super, class messages (sent to a 2013 /// class name), and instance messages (sent to an object), and the 2014 /// target is represented by \p SuperLoc, \p ReceiverType, or \p 2015 /// ReceiverExpr, respectively. Only one of these parameters may have 2016 /// a valid value. 2017 /// 2018 /// \param LBracLoc The location of the opening '['. 2019 /// 2020 /// \param SuperLoc If this is a send to 'super', the location of the 2021 /// 'super' keyword that indicates a send to the superclass. 2022 /// 2023 /// \param ReceiverType If this is a class message, the type of the 2024 /// class we are sending a message to. 2025 /// 2026 /// \param ReceiverExpr If this is an instance message, the expression 2027 /// used to compute the receiver object. 2028 /// 2029 /// objc-message-args: 2030 /// objc-selector 2031 /// objc-keywordarg-list 2032 /// 2033 /// objc-keywordarg-list: 2034 /// objc-keywordarg 2035 /// objc-keywordarg-list objc-keywordarg 2036 /// 2037 /// objc-keywordarg: 2038 /// selector-name[opt] ':' objc-keywordexpr 2039 /// 2040 /// objc-keywordexpr: 2041 /// nonempty-expr-list 2042 /// 2043 /// nonempty-expr-list: 2044 /// assignment-expression 2045 /// nonempty-expr-list , assignment-expression 2046 /// 2047 ExprResult 2048 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, 2049 SourceLocation SuperLoc, 2050 ParsedType ReceiverType, 2051 ExprArg ReceiverExpr) { 2052 InMessageExpressionRAIIObject InMessage(*this, true); 2053 2054 if (Tok.is(tok::code_completion)) { 2055 if (SuperLoc.isValid()) 2056 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0, 2057 false); 2058 else if (ReceiverType) 2059 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0, 2060 false); 2061 else 2062 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2063 0, 0, false); 2064 ConsumeCodeCompletionToken(); 2065 } 2066 2067 // Parse objc-selector 2068 SourceLocation Loc; 2069 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); 2070 2071 SourceLocation SelectorLoc = Loc; 2072 2073 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents; 2074 ExprVector KeyExprs(Actions); 2075 2076 if (Tok.is(tok::colon)) { 2077 while (1) { 2078 // Each iteration parses a single keyword argument. 2079 KeyIdents.push_back(selIdent); 2080 2081 if (Tok.isNot(tok::colon)) { 2082 Diag(Tok, diag::err_expected_colon); 2083 // We must manually skip to a ']', otherwise the expression skipper will 2084 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2085 // the enclosing expression. 2086 SkipUntil(tok::r_square); 2087 return ExprError(); 2088 } 2089 2090 ConsumeToken(); // Eat the ':'. 2091 /// Parse the expression after ':' 2092 2093 if (Tok.is(tok::code_completion)) { 2094 if (SuperLoc.isValid()) 2095 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2096 KeyIdents.data(), 2097 KeyIdents.size(), 2098 /*AtArgumentEpression=*/true); 2099 else if (ReceiverType) 2100 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2101 KeyIdents.data(), 2102 KeyIdents.size(), 2103 /*AtArgumentEpression=*/true); 2104 else 2105 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2106 KeyIdents.data(), 2107 KeyIdents.size(), 2108 /*AtArgumentEpression=*/true); 2109 2110 ConsumeCodeCompletionToken(); 2111 SkipUntil(tok::r_square); 2112 return ExprError(); 2113 } 2114 2115 ExprResult Res(ParseAssignmentExpression()); 2116 if (Res.isInvalid()) { 2117 // We must manually skip to a ']', otherwise the expression skipper will 2118 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2119 // the enclosing expression. 2120 SkipUntil(tok::r_square); 2121 return move(Res); 2122 } 2123 2124 // We have a valid expression. 2125 KeyExprs.push_back(Res.release()); 2126 2127 // Code completion after each argument. 2128 if (Tok.is(tok::code_completion)) { 2129 if (SuperLoc.isValid()) 2130 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2131 KeyIdents.data(), 2132 KeyIdents.size(), 2133 /*AtArgumentEpression=*/false); 2134 else if (ReceiverType) 2135 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2136 KeyIdents.data(), 2137 KeyIdents.size(), 2138 /*AtArgumentEpression=*/false); 2139 else 2140 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2141 KeyIdents.data(), 2142 KeyIdents.size(), 2143 /*AtArgumentEpression=*/false); 2144 ConsumeCodeCompletionToken(); 2145 SkipUntil(tok::r_square); 2146 return ExprError(); 2147 } 2148 2149 // Check for another keyword selector. 2150 selIdent = ParseObjCSelectorPiece(Loc); 2151 if (!selIdent && Tok.isNot(tok::colon)) 2152 break; 2153 // We have a selector or a colon, continue parsing. 2154 } 2155 // Parse the, optional, argument list, comma separated. 2156 while (Tok.is(tok::comma)) { 2157 ConsumeToken(); // Eat the ','. 2158 /// Parse the expression after ',' 2159 ExprResult Res(ParseAssignmentExpression()); 2160 if (Res.isInvalid()) { 2161 // We must manually skip to a ']', otherwise the expression skipper will 2162 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2163 // the enclosing expression. 2164 SkipUntil(tok::r_square); 2165 return move(Res); 2166 } 2167 2168 // We have a valid expression. 2169 KeyExprs.push_back(Res.release()); 2170 } 2171 } else if (!selIdent) { 2172 Diag(Tok, diag::err_expected_ident); // missing selector name. 2173 2174 // We must manually skip to a ']', otherwise the expression skipper will 2175 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2176 // the enclosing expression. 2177 SkipUntil(tok::r_square); 2178 return ExprError(); 2179 } 2180 2181 if (Tok.isNot(tok::r_square)) { 2182 if (Tok.is(tok::identifier)) 2183 Diag(Tok, diag::err_expected_colon); 2184 else 2185 Diag(Tok, diag::err_expected_rsquare); 2186 // We must manually skip to a ']', otherwise the expression skipper will 2187 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2188 // the enclosing expression. 2189 SkipUntil(tok::r_square); 2190 return ExprError(); 2191 } 2192 2193 SourceLocation RBracLoc = ConsumeBracket(); // consume ']' 2194 2195 unsigned nKeys = KeyIdents.size(); 2196 if (nKeys == 0) 2197 KeyIdents.push_back(selIdent); 2198 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]); 2199 2200 if (SuperLoc.isValid()) 2201 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel, 2202 LBracLoc, SelectorLoc, RBracLoc, 2203 MultiExprArg(Actions, 2204 KeyExprs.take(), 2205 KeyExprs.size())); 2206 else if (ReceiverType) 2207 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel, 2208 LBracLoc, SelectorLoc, RBracLoc, 2209 MultiExprArg(Actions, 2210 KeyExprs.take(), 2211 KeyExprs.size())); 2212 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel, 2213 LBracLoc, SelectorLoc, RBracLoc, 2214 MultiExprArg(Actions, 2215 KeyExprs.take(), 2216 KeyExprs.size())); 2217 } 2218 2219 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { 2220 ExprResult Res(ParseStringLiteralExpression()); 2221 if (Res.isInvalid()) return move(Res); 2222 2223 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string 2224 // expressions. At this point, we know that the only valid thing that starts 2225 // with '@' is an @"". 2226 llvm::SmallVector<SourceLocation, 4> AtLocs; 2227 ExprVector AtStrings(Actions); 2228 AtLocs.push_back(AtLoc); 2229 AtStrings.push_back(Res.release()); 2230 2231 while (Tok.is(tok::at)) { 2232 AtLocs.push_back(ConsumeToken()); // eat the @. 2233 2234 // Invalid unless there is a string literal. 2235 if (!isTokenStringLiteral()) 2236 return ExprError(Diag(Tok, diag::err_objc_concat_string)); 2237 2238 ExprResult Lit(ParseStringLiteralExpression()); 2239 if (Lit.isInvalid()) 2240 return move(Lit); 2241 2242 AtStrings.push_back(Lit.release()); 2243 } 2244 2245 return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(), 2246 AtStrings.size())); 2247 } 2248 2249 /// objc-encode-expression: 2250 /// @encode ( type-name ) 2251 ExprResult 2252 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) { 2253 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!"); 2254 2255 SourceLocation EncLoc = ConsumeToken(); 2256 2257 if (Tok.isNot(tok::l_paren)) 2258 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode"); 2259 2260 SourceLocation LParenLoc = ConsumeParen(); 2261 2262 TypeResult Ty = ParseTypeName(); 2263 2264 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2265 2266 if (Ty.isInvalid()) 2267 return ExprError(); 2268 2269 return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc, 2270 Ty.get(), RParenLoc)); 2271 } 2272 2273 /// objc-protocol-expression 2274 /// @protocol ( protocol-name ) 2275 ExprResult 2276 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) { 2277 SourceLocation ProtoLoc = ConsumeToken(); 2278 2279 if (Tok.isNot(tok::l_paren)) 2280 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol"); 2281 2282 SourceLocation LParenLoc = ConsumeParen(); 2283 2284 if (Tok.isNot(tok::identifier)) 2285 return ExprError(Diag(Tok, diag::err_expected_ident)); 2286 2287 IdentifierInfo *protocolId = Tok.getIdentifierInfo(); 2288 ConsumeToken(); 2289 2290 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2291 2292 return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc, 2293 LParenLoc, RParenLoc)); 2294 } 2295 2296 /// objc-selector-expression 2297 /// @selector '(' objc-keyword-selector ')' 2298 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { 2299 SourceLocation SelectorLoc = ConsumeToken(); 2300 2301 if (Tok.isNot(tok::l_paren)) 2302 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector"); 2303 2304 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents; 2305 SourceLocation LParenLoc = ConsumeParen(); 2306 SourceLocation sLoc; 2307 2308 if (Tok.is(tok::code_completion)) { 2309 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(), 2310 KeyIdents.size()); 2311 ConsumeCodeCompletionToken(); 2312 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2313 return ExprError(); 2314 } 2315 2316 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); 2317 if (!SelIdent && // missing selector name. 2318 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 2319 return ExprError(Diag(Tok, diag::err_expected_ident)); 2320 2321 KeyIdents.push_back(SelIdent); 2322 unsigned nColons = 0; 2323 if (Tok.isNot(tok::r_paren)) { 2324 while (1) { 2325 if (Tok.is(tok::coloncolon)) { // Handle :: in C++. 2326 ++nColons; 2327 KeyIdents.push_back(0); 2328 } else if (Tok.isNot(tok::colon)) 2329 return ExprError(Diag(Tok, diag::err_expected_colon)); 2330 2331 ++nColons; 2332 ConsumeToken(); // Eat the ':'. 2333 if (Tok.is(tok::r_paren)) 2334 break; 2335 2336 if (Tok.is(tok::code_completion)) { 2337 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(), 2338 KeyIdents.size()); 2339 ConsumeCodeCompletionToken(); 2340 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2341 return ExprError(); 2342 } 2343 2344 // Check for another keyword selector. 2345 SourceLocation Loc; 2346 SelIdent = ParseObjCSelectorPiece(Loc); 2347 KeyIdents.push_back(SelIdent); 2348 if (!SelIdent && Tok.isNot(tok::colon)) 2349 break; 2350 } 2351 } 2352 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2353 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]); 2354 return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc, 2355 LParenLoc, RParenLoc)); 2356 } 2357