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