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