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