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