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