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