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/Parser.h" 15 #include "RAIIObjectsForParser.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/Basic/CharInfo.h" 18 #include "clang/Parse/ParseDiagnostic.h" 19 #include "clang/Sema/DeclSpec.h" 20 #include "clang/Sema/PrettyDeclStackTrace.h" 21 #include "clang/Sema/Scope.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringExtras.h" 24 using namespace clang; 25 26 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic. 27 void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) { 28 ParsedAttributes attrs(AttrFactory); 29 if (Tok.is(tok::kw___attribute)) { 30 if (Kind == tok::objc_interface || Kind == tok::objc_protocol) 31 Diag(Tok, diag::err_objc_postfix_attribute_hint) 32 << (Kind == tok::objc_protocol); 33 else 34 Diag(Tok, diag::err_objc_postfix_attribute); 35 ParseGNUAttributes(attrs); 36 } 37 } 38 39 /// ParseObjCAtDirectives - Handle parts of the external-declaration production: 40 /// external-declaration: [C99 6.9] 41 /// [OBJC] objc-class-definition 42 /// [OBJC] objc-class-declaration 43 /// [OBJC] objc-alias-declaration 44 /// [OBJC] objc-protocol-definition 45 /// [OBJC] objc-method-definition 46 /// [OBJC] '@' 'end' 47 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() { 48 SourceLocation AtLoc = ConsumeToken(); // the "@" 49 50 if (Tok.is(tok::code_completion)) { 51 Actions.CodeCompleteObjCAtDirective(getCurScope()); 52 cutOffParsing(); 53 return DeclGroupPtrTy(); 54 } 55 56 Decl *SingleDecl = nullptr; 57 switch (Tok.getObjCKeywordID()) { 58 case tok::objc_class: 59 return ParseObjCAtClassDeclaration(AtLoc); 60 case tok::objc_interface: { 61 ParsedAttributes attrs(AttrFactory); 62 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs); 63 break; 64 } 65 case tok::objc_protocol: { 66 ParsedAttributes attrs(AttrFactory); 67 return ParseObjCAtProtocolDeclaration(AtLoc, attrs); 68 } 69 case tok::objc_implementation: 70 return ParseObjCAtImplementationDeclaration(AtLoc); 71 case tok::objc_end: 72 return ParseObjCAtEndDeclaration(AtLoc); 73 case tok::objc_compatibility_alias: 74 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc); 75 break; 76 case tok::objc_synthesize: 77 SingleDecl = ParseObjCPropertySynthesize(AtLoc); 78 break; 79 case tok::objc_dynamic: 80 SingleDecl = ParseObjCPropertyDynamic(AtLoc); 81 break; 82 case tok::objc_import: 83 if (getLangOpts().Modules || getLangOpts().DebuggerSupport) 84 return ParseModuleImport(AtLoc); 85 Diag(AtLoc, diag::err_atimport); 86 SkipUntil(tok::semi); 87 return Actions.ConvertDeclToDeclGroup(nullptr); 88 default: 89 Diag(AtLoc, diag::err_unexpected_at); 90 SkipUntil(tok::semi); 91 SingleDecl = nullptr; 92 break; 93 } 94 return Actions.ConvertDeclToDeclGroup(SingleDecl); 95 } 96 97 /// 98 /// objc-class-declaration: 99 /// '@' 'class' identifier-list ';' 100 /// 101 Parser::DeclGroupPtrTy 102 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { 103 ConsumeToken(); // the identifier "class" 104 SmallVector<IdentifierInfo *, 8> ClassNames; 105 SmallVector<SourceLocation, 8> ClassLocs; 106 107 108 while (1) { 109 MaybeSkipAttributes(tok::objc_class); 110 if (Tok.isNot(tok::identifier)) { 111 Diag(Tok, diag::err_expected) << tok::identifier; 112 SkipUntil(tok::semi); 113 return Actions.ConvertDeclToDeclGroup(nullptr); 114 } 115 ClassNames.push_back(Tok.getIdentifierInfo()); 116 ClassLocs.push_back(Tok.getLocation()); 117 ConsumeToken(); 118 119 if (!TryConsumeToken(tok::comma)) 120 break; 121 } 122 123 // Consume the ';'. 124 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class")) 125 return Actions.ConvertDeclToDeclGroup(nullptr); 126 127 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(), 128 ClassLocs.data(), 129 ClassNames.size()); 130 } 131 132 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc) 133 { 134 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind(); 135 if (ock == Sema::OCK_None) 136 return; 137 138 Decl *Decl = Actions.getObjCDeclContext(); 139 if (CurParsedObjCImpl) { 140 CurParsedObjCImpl->finish(AtLoc); 141 } else { 142 Actions.ActOnAtEnd(getCurScope(), AtLoc); 143 } 144 Diag(AtLoc, diag::err_objc_missing_end) 145 << FixItHint::CreateInsertion(AtLoc, "@end\n"); 146 if (Decl) 147 Diag(Decl->getLocStart(), diag::note_objc_container_start) 148 << (int) ock; 149 } 150 151 /// 152 /// objc-interface: 153 /// objc-class-interface-attributes[opt] objc-class-interface 154 /// objc-category-interface 155 /// 156 /// objc-class-interface: 157 /// '@' 'interface' identifier objc-superclass[opt] 158 /// objc-protocol-refs[opt] 159 /// objc-class-instance-variables[opt] 160 /// objc-interface-decl-list 161 /// @end 162 /// 163 /// objc-category-interface: 164 /// '@' 'interface' identifier '(' identifier[opt] ')' 165 /// objc-protocol-refs[opt] 166 /// objc-interface-decl-list 167 /// @end 168 /// 169 /// objc-superclass: 170 /// ':' identifier 171 /// 172 /// objc-class-interface-attributes: 173 /// __attribute__((visibility("default"))) 174 /// __attribute__((visibility("hidden"))) 175 /// __attribute__((deprecated)) 176 /// __attribute__((unavailable)) 177 /// __attribute__((objc_exception)) - used by NSException on 64-bit 178 /// __attribute__((objc_root_class)) 179 /// 180 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, 181 ParsedAttributes &attrs) { 182 assert(Tok.isObjCAtKeyword(tok::objc_interface) && 183 "ParseObjCAtInterfaceDeclaration(): Expected @interface"); 184 CheckNestedObjCContexts(AtLoc); 185 ConsumeToken(); // the "interface" identifier 186 187 // Code completion after '@interface'. 188 if (Tok.is(tok::code_completion)) { 189 Actions.CodeCompleteObjCInterfaceDecl(getCurScope()); 190 cutOffParsing(); 191 return nullptr; 192 } 193 194 MaybeSkipAttributes(tok::objc_interface); 195 196 if (Tok.isNot(tok::identifier)) { 197 Diag(Tok, diag::err_expected) 198 << tok::identifier; // missing class or category name. 199 return nullptr; 200 } 201 202 // We have a class or category name - consume it. 203 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 204 SourceLocation nameLoc = ConsumeToken(); 205 if (Tok.is(tok::l_paren) && 206 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. 207 208 BalancedDelimiterTracker T(*this, tok::l_paren); 209 T.consumeOpen(); 210 211 SourceLocation categoryLoc; 212 IdentifierInfo *categoryId = nullptr; 213 if (Tok.is(tok::code_completion)) { 214 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc); 215 cutOffParsing(); 216 return nullptr; 217 } 218 219 // For ObjC2, the category name is optional (not an error). 220 if (Tok.is(tok::identifier)) { 221 categoryId = Tok.getIdentifierInfo(); 222 categoryLoc = ConsumeToken(); 223 } 224 else if (!getLangOpts().ObjC2) { 225 Diag(Tok, diag::err_expected) 226 << tok::identifier; // missing category name. 227 return nullptr; 228 } 229 230 T.consumeClose(); 231 if (T.getCloseLocation().isInvalid()) 232 return nullptr; 233 234 if (!attrs.empty()) { // categories don't support attributes. 235 Diag(nameLoc, diag::err_objc_no_attributes_on_category); 236 attrs.clear(); 237 } 238 239 // Next, we need to check for any protocol references. 240 SourceLocation LAngleLoc, EndProtoLoc; 241 SmallVector<Decl *, 8> ProtocolRefs; 242 SmallVector<SourceLocation, 8> ProtocolLocs; 243 if (Tok.is(tok::less) && 244 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true, 245 LAngleLoc, EndProtoLoc)) 246 return nullptr; 247 248 Decl *CategoryType = 249 Actions.ActOnStartCategoryInterface(AtLoc, 250 nameId, nameLoc, 251 categoryId, categoryLoc, 252 ProtocolRefs.data(), 253 ProtocolRefs.size(), 254 ProtocolLocs.data(), 255 EndProtoLoc); 256 257 if (Tok.is(tok::l_brace)) 258 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc); 259 260 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType); 261 return CategoryType; 262 } 263 // Parse a class interface. 264 IdentifierInfo *superClassId = nullptr; 265 SourceLocation superClassLoc; 266 267 if (Tok.is(tok::colon)) { // a super class is specified. 268 ConsumeToken(); 269 270 // Code completion of superclass names. 271 if (Tok.is(tok::code_completion)) { 272 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc); 273 cutOffParsing(); 274 return nullptr; 275 } 276 277 if (Tok.isNot(tok::identifier)) { 278 Diag(Tok, diag::err_expected) 279 << tok::identifier; // missing super class name. 280 return nullptr; 281 } 282 superClassId = Tok.getIdentifierInfo(); 283 superClassLoc = ConsumeToken(); 284 } 285 // Next, we need to check for any protocol references. 286 SmallVector<Decl *, 8> ProtocolRefs; 287 SmallVector<SourceLocation, 8> ProtocolLocs; 288 SourceLocation LAngleLoc, EndProtoLoc; 289 if (Tok.is(tok::less) && 290 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true, 291 LAngleLoc, EndProtoLoc)) 292 return nullptr; 293 294 if (Tok.isNot(tok::less)) 295 Actions.ActOnTypedefedProtocols(ProtocolRefs, superClassId, superClassLoc); 296 297 Decl *ClsType = 298 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc, 299 superClassId, superClassLoc, 300 ProtocolRefs.data(), ProtocolRefs.size(), 301 ProtocolLocs.data(), 302 EndProtoLoc, attrs.getList()); 303 304 if (Tok.is(tok::l_brace)) 305 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc); 306 307 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType); 308 return ClsType; 309 } 310 311 /// Add an attribute for a context-sensitive type nullability to the given 312 /// declarator. 313 static void addContextSensitiveTypeNullability(Parser &P, 314 Declarator &D, 315 NullabilityKind nullability, 316 SourceLocation nullabilityLoc, 317 bool &addedToDeclSpec) { 318 // Create the attribute. 319 auto getNullabilityAttr = [&]() -> AttributeList * { 320 return D.getAttributePool().create( 321 P.getNullabilityKeyword(nullability), 322 SourceRange(nullabilityLoc), 323 nullptr, SourceLocation(), 324 nullptr, 0, 325 AttributeList::AS_ContextSensitiveKeyword); 326 }; 327 328 if (D.getNumTypeObjects() > 0) { 329 // Add the attribute to the declarator chunk nearest the declarator. 330 auto nullabilityAttr = getNullabilityAttr(); 331 DeclaratorChunk &chunk = D.getTypeObject(0); 332 nullabilityAttr->setNext(chunk.getAttrListRef()); 333 chunk.getAttrListRef() = nullabilityAttr; 334 } else if (!addedToDeclSpec) { 335 // Otherwise, just put it on the declaration specifiers (if one 336 // isn't there already). 337 D.getMutableDeclSpec().addAttributes(getNullabilityAttr()); 338 addedToDeclSpec = true; 339 } 340 } 341 342 /// objc-interface-decl-list: 343 /// empty 344 /// objc-interface-decl-list objc-property-decl [OBJC2] 345 /// objc-interface-decl-list objc-method-requirement [OBJC2] 346 /// objc-interface-decl-list objc-method-proto ';' 347 /// objc-interface-decl-list declaration 348 /// objc-interface-decl-list ';' 349 /// 350 /// objc-method-requirement: [OBJC2] 351 /// @required 352 /// @optional 353 /// 354 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, 355 Decl *CDecl) { 356 SmallVector<Decl *, 32> allMethods; 357 SmallVector<Decl *, 16> allProperties; 358 SmallVector<DeclGroupPtrTy, 8> allTUVariables; 359 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; 360 361 SourceRange AtEnd; 362 363 while (1) { 364 // If this is a method prototype, parse it. 365 if (Tok.isOneOf(tok::minus, tok::plus)) { 366 if (Decl *methodPrototype = 367 ParseObjCMethodPrototype(MethodImplKind, false)) 368 allMethods.push_back(methodPrototype); 369 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for 370 // method definitions. 371 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) { 372 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'. 373 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch); 374 if (Tok.is(tok::semi)) 375 ConsumeToken(); 376 } 377 continue; 378 } 379 if (Tok.is(tok::l_paren)) { 380 Diag(Tok, diag::err_expected_minus_or_plus); 381 ParseObjCMethodDecl(Tok.getLocation(), 382 tok::minus, 383 MethodImplKind, false); 384 continue; 385 } 386 // Ignore excess semicolons. 387 if (Tok.is(tok::semi)) { 388 ConsumeToken(); 389 continue; 390 } 391 392 // If we got to the end of the file, exit the loop. 393 if (isEofOrEom()) 394 break; 395 396 // Code completion within an Objective-C interface. 397 if (Tok.is(tok::code_completion)) { 398 Actions.CodeCompleteOrdinaryName(getCurScope(), 399 CurParsedObjCImpl? Sema::PCC_ObjCImplementation 400 : Sema::PCC_ObjCInterface); 401 return cutOffParsing(); 402 } 403 404 // If we don't have an @ directive, parse it as a function definition. 405 if (Tok.isNot(tok::at)) { 406 // The code below does not consume '}'s because it is afraid of eating the 407 // end of a namespace. Because of the way this code is structured, an 408 // erroneous r_brace would cause an infinite loop if not handled here. 409 if (Tok.is(tok::r_brace)) 410 break; 411 ParsedAttributesWithRange attrs(AttrFactory); 412 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs)); 413 continue; 414 } 415 416 // Otherwise, we have an @ directive, eat the @. 417 SourceLocation AtLoc = ConsumeToken(); // the "@" 418 if (Tok.is(tok::code_completion)) { 419 Actions.CodeCompleteObjCAtDirective(getCurScope()); 420 return cutOffParsing(); 421 } 422 423 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID(); 424 425 if (DirectiveKind == tok::objc_end) { // @end -> terminate list 426 AtEnd.setBegin(AtLoc); 427 AtEnd.setEnd(Tok.getLocation()); 428 break; 429 } else if (DirectiveKind == tok::objc_not_keyword) { 430 Diag(Tok, diag::err_objc_unknown_at); 431 SkipUntil(tok::semi); 432 continue; 433 } 434 435 // Eat the identifier. 436 ConsumeToken(); 437 438 switch (DirectiveKind) { 439 default: 440 // FIXME: If someone forgets an @end on a protocol, this loop will 441 // continue to eat up tons of stuff and spew lots of nonsense errors. It 442 // would probably be better to bail out if we saw an @class or @interface 443 // or something like that. 444 Diag(AtLoc, diag::err_objc_illegal_interface_qual); 445 // Skip until we see an '@' or '}' or ';'. 446 SkipUntil(tok::r_brace, tok::at, StopAtSemi); 447 break; 448 449 case tok::objc_implementation: 450 case tok::objc_interface: 451 Diag(AtLoc, diag::err_objc_missing_end) 452 << FixItHint::CreateInsertion(AtLoc, "@end\n"); 453 Diag(CDecl->getLocStart(), diag::note_objc_container_start) 454 << (int) Actions.getObjCContainerKind(); 455 ConsumeToken(); 456 break; 457 458 case tok::objc_required: 459 case tok::objc_optional: 460 // This is only valid on protocols. 461 // FIXME: Should this check for ObjC2 being enabled? 462 if (contextKey != tok::objc_protocol) 463 Diag(AtLoc, diag::err_objc_directive_only_in_protocol); 464 else 465 MethodImplKind = DirectiveKind; 466 break; 467 468 case tok::objc_property: 469 if (!getLangOpts().ObjC2) 470 Diag(AtLoc, diag::err_objc_properties_require_objc2); 471 472 ObjCDeclSpec OCDS; 473 SourceLocation LParenLoc; 474 // Parse property attribute list, if any. 475 if (Tok.is(tok::l_paren)) { 476 LParenLoc = Tok.getLocation(); 477 ParseObjCPropertyAttribute(OCDS); 478 } 479 480 bool addedToDeclSpec = false; 481 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) { 482 if (FD.D.getIdentifier() == nullptr) { 483 Diag(AtLoc, diag::err_objc_property_requires_field_name) 484 << FD.D.getSourceRange(); 485 return; 486 } 487 if (FD.BitfieldSize) { 488 Diag(AtLoc, diag::err_objc_property_bitfield) 489 << FD.D.getSourceRange(); 490 return; 491 } 492 493 // Map a nullability property attribute to a context-sensitive keyword 494 // attribute. 495 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 496 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(), 497 OCDS.getNullabilityLoc(), 498 addedToDeclSpec); 499 500 // Install the property declarator into interfaceDecl. 501 IdentifierInfo *SelName = 502 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier(); 503 504 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName); 505 IdentifierInfo *SetterName = OCDS.getSetterName(); 506 Selector SetterSel; 507 if (SetterName) 508 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName); 509 else 510 SetterSel = SelectorTable::constructSetterSelector( 511 PP.getIdentifierTable(), PP.getSelectorTable(), 512 FD.D.getIdentifier()); 513 bool isOverridingProperty = false; 514 Decl *Property = Actions.ActOnProperty( 515 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel, 516 &isOverridingProperty, MethodImplKind); 517 if (!isOverridingProperty) 518 allProperties.push_back(Property); 519 520 FD.complete(Property); 521 }; 522 523 // Parse all the comma separated declarators. 524 ParsingDeclSpec DS(*this); 525 ParseStructDeclaration(DS, ObjCPropertyCallback); 526 527 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 528 break; 529 } 530 } 531 532 // We break out of the big loop in two cases: when we see @end or when we see 533 // EOF. In the former case, eat the @end. In the later case, emit an error. 534 if (Tok.is(tok::code_completion)) { 535 Actions.CodeCompleteObjCAtDirective(getCurScope()); 536 return cutOffParsing(); 537 } else if (Tok.isObjCAtKeyword(tok::objc_end)) { 538 ConsumeToken(); // the "end" identifier 539 } else { 540 Diag(Tok, diag::err_objc_missing_end) 541 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n"); 542 Diag(CDecl->getLocStart(), diag::note_objc_container_start) 543 << (int) Actions.getObjCContainerKind(); 544 AtEnd.setBegin(Tok.getLocation()); 545 AtEnd.setEnd(Tok.getLocation()); 546 } 547 548 // Insert collected methods declarations into the @interface object. 549 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit. 550 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables); 551 } 552 553 /// Diagnose redundant or conflicting nullability information. 554 static void diagnoseRedundantPropertyNullability(Parser &P, 555 ObjCDeclSpec &DS, 556 NullabilityKind nullability, 557 SourceLocation nullabilityLoc){ 558 if (DS.getNullability() == nullability) { 559 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate) 560 << static_cast<unsigned>(nullability) << true 561 << SourceRange(DS.getNullabilityLoc()); 562 return; 563 } 564 565 P.Diag(nullabilityLoc, diag::err_nullability_conflicting) 566 << static_cast<unsigned>(nullability) << true 567 << static_cast<unsigned>(DS.getNullability()) << true 568 << SourceRange(DS.getNullabilityLoc()); 569 } 570 571 /// Parse property attribute declarations. 572 /// 573 /// property-attr-decl: '(' property-attrlist ')' 574 /// property-attrlist: 575 /// property-attribute 576 /// property-attrlist ',' property-attribute 577 /// property-attribute: 578 /// getter '=' identifier 579 /// setter '=' identifier ':' 580 /// readonly 581 /// readwrite 582 /// assign 583 /// retain 584 /// copy 585 /// nonatomic 586 /// atomic 587 /// strong 588 /// weak 589 /// unsafe_unretained 590 /// nonnull 591 /// nullable 592 /// null_unspecified 593 /// null_resettable 594 /// 595 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { 596 assert(Tok.getKind() == tok::l_paren); 597 BalancedDelimiterTracker T(*this, tok::l_paren); 598 T.consumeOpen(); 599 600 while (1) { 601 if (Tok.is(tok::code_completion)) { 602 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS); 603 return cutOffParsing(); 604 } 605 const IdentifierInfo *II = Tok.getIdentifierInfo(); 606 607 // If this is not an identifier at all, bail out early. 608 if (!II) { 609 T.consumeClose(); 610 return; 611 } 612 613 SourceLocation AttrName = ConsumeToken(); // consume last attribute name 614 615 if (II->isStr("readonly")) 616 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly); 617 else if (II->isStr("assign")) 618 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign); 619 else if (II->isStr("unsafe_unretained")) 620 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained); 621 else if (II->isStr("readwrite")) 622 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite); 623 else if (II->isStr("retain")) 624 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain); 625 else if (II->isStr("strong")) 626 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong); 627 else if (II->isStr("copy")) 628 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy); 629 else if (II->isStr("nonatomic")) 630 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic); 631 else if (II->isStr("atomic")) 632 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic); 633 else if (II->isStr("weak")) 634 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak); 635 else if (II->isStr("getter") || II->isStr("setter")) { 636 bool IsSetter = II->getNameStart()[0] == 's'; 637 638 // getter/setter require extra treatment. 639 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter : 640 diag::err_objc_expected_equal_for_getter; 641 642 if (ExpectAndConsume(tok::equal, DiagID)) { 643 SkipUntil(tok::r_paren, StopAtSemi); 644 return; 645 } 646 647 if (Tok.is(tok::code_completion)) { 648 if (IsSetter) 649 Actions.CodeCompleteObjCPropertySetter(getCurScope()); 650 else 651 Actions.CodeCompleteObjCPropertyGetter(getCurScope()); 652 return cutOffParsing(); 653 } 654 655 656 SourceLocation SelLoc; 657 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc); 658 659 if (!SelIdent) { 660 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter) 661 << IsSetter; 662 SkipUntil(tok::r_paren, StopAtSemi); 663 return; 664 } 665 666 if (IsSetter) { 667 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter); 668 DS.setSetterName(SelIdent); 669 670 if (ExpectAndConsume(tok::colon, 671 diag::err_expected_colon_after_setter_name)) { 672 SkipUntil(tok::r_paren, StopAtSemi); 673 return; 674 } 675 } else { 676 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter); 677 DS.setGetterName(SelIdent); 678 } 679 } else if (II->isStr("nonnull")) { 680 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 681 diagnoseRedundantPropertyNullability(*this, DS, 682 NullabilityKind::NonNull, 683 Tok.getLocation()); 684 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 685 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull); 686 } else if (II->isStr("nullable")) { 687 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 688 diagnoseRedundantPropertyNullability(*this, DS, 689 NullabilityKind::Nullable, 690 Tok.getLocation()); 691 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 692 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable); 693 } else if (II->isStr("null_unspecified")) { 694 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 695 diagnoseRedundantPropertyNullability(*this, DS, 696 NullabilityKind::Unspecified, 697 Tok.getLocation()); 698 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 699 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified); 700 } else if (II->isStr("null_resettable")) { 701 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) 702 diagnoseRedundantPropertyNullability(*this, DS, 703 NullabilityKind::Unspecified, 704 Tok.getLocation()); 705 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); 706 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified); 707 708 // Also set the null_resettable bit. 709 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable); 710 } else { 711 Diag(AttrName, diag::err_objc_expected_property_attr) << II; 712 SkipUntil(tok::r_paren, StopAtSemi); 713 return; 714 } 715 716 if (Tok.isNot(tok::comma)) 717 break; 718 719 ConsumeToken(); 720 } 721 722 T.consumeClose(); 723 } 724 725 /// objc-method-proto: 726 /// objc-instance-method objc-method-decl objc-method-attributes[opt] 727 /// objc-class-method objc-method-decl objc-method-attributes[opt] 728 /// 729 /// objc-instance-method: '-' 730 /// objc-class-method: '+' 731 /// 732 /// objc-method-attributes: [OBJC2] 733 /// __attribute__((deprecated)) 734 /// 735 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind, 736 bool MethodDefinition) { 737 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-"); 738 739 tok::TokenKind methodType = Tok.getKind(); 740 SourceLocation mLoc = ConsumeToken(); 741 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind, 742 MethodDefinition); 743 // Since this rule is used for both method declarations and definitions, 744 // the caller is (optionally) responsible for consuming the ';'. 745 return MDecl; 746 } 747 748 /// objc-selector: 749 /// identifier 750 /// one of 751 /// enum struct union if else while do for switch case default 752 /// break continue return goto asm sizeof typeof __alignof 753 /// unsigned long const short volatile signed restrict _Complex 754 /// in out inout bycopy byref oneway int char float double void _Bool 755 /// 756 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) { 757 758 switch (Tok.getKind()) { 759 default: 760 return nullptr; 761 case tok::ampamp: 762 case tok::ampequal: 763 case tok::amp: 764 case tok::pipe: 765 case tok::tilde: 766 case tok::exclaim: 767 case tok::exclaimequal: 768 case tok::pipepipe: 769 case tok::pipeequal: 770 case tok::caret: 771 case tok::caretequal: { 772 std::string ThisTok(PP.getSpelling(Tok)); 773 if (isLetter(ThisTok[0])) { 774 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data()); 775 Tok.setKind(tok::identifier); 776 SelectorLoc = ConsumeToken(); 777 return II; 778 } 779 return nullptr; 780 } 781 782 case tok::identifier: 783 case tok::kw_asm: 784 case tok::kw_auto: 785 case tok::kw_bool: 786 case tok::kw_break: 787 case tok::kw_case: 788 case tok::kw_catch: 789 case tok::kw_char: 790 case tok::kw_class: 791 case tok::kw_const: 792 case tok::kw_const_cast: 793 case tok::kw_continue: 794 case tok::kw_default: 795 case tok::kw_delete: 796 case tok::kw_do: 797 case tok::kw_double: 798 case tok::kw_dynamic_cast: 799 case tok::kw_else: 800 case tok::kw_enum: 801 case tok::kw_explicit: 802 case tok::kw_export: 803 case tok::kw_extern: 804 case tok::kw_false: 805 case tok::kw_float: 806 case tok::kw_for: 807 case tok::kw_friend: 808 case tok::kw_goto: 809 case tok::kw_if: 810 case tok::kw_inline: 811 case tok::kw_int: 812 case tok::kw_long: 813 case tok::kw_mutable: 814 case tok::kw_namespace: 815 case tok::kw_new: 816 case tok::kw_operator: 817 case tok::kw_private: 818 case tok::kw_protected: 819 case tok::kw_public: 820 case tok::kw_register: 821 case tok::kw_reinterpret_cast: 822 case tok::kw_restrict: 823 case tok::kw_return: 824 case tok::kw_short: 825 case tok::kw_signed: 826 case tok::kw_sizeof: 827 case tok::kw_static: 828 case tok::kw_static_cast: 829 case tok::kw_struct: 830 case tok::kw_switch: 831 case tok::kw_template: 832 case tok::kw_this: 833 case tok::kw_throw: 834 case tok::kw_true: 835 case tok::kw_try: 836 case tok::kw_typedef: 837 case tok::kw_typeid: 838 case tok::kw_typename: 839 case tok::kw_typeof: 840 case tok::kw_union: 841 case tok::kw_unsigned: 842 case tok::kw_using: 843 case tok::kw_virtual: 844 case tok::kw_void: 845 case tok::kw_volatile: 846 case tok::kw_wchar_t: 847 case tok::kw_while: 848 case tok::kw__Bool: 849 case tok::kw__Complex: 850 case tok::kw___alignof: 851 IdentifierInfo *II = Tok.getIdentifierInfo(); 852 SelectorLoc = ConsumeToken(); 853 return II; 854 } 855 } 856 857 /// objc-for-collection-in: 'in' 858 /// 859 bool Parser::isTokIdentifier_in() const { 860 // FIXME: May have to do additional look-ahead to only allow for 861 // valid tokens following an 'in'; such as an identifier, unary operators, 862 // '[' etc. 863 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) && 864 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]); 865 } 866 867 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type 868 /// qualifier list and builds their bitmask representation in the input 869 /// argument. 870 /// 871 /// objc-type-qualifiers: 872 /// objc-type-qualifier 873 /// objc-type-qualifiers objc-type-qualifier 874 /// 875 /// objc-type-qualifier: 876 /// 'in' 877 /// 'out' 878 /// 'inout' 879 /// 'oneway' 880 /// 'bycopy' 881 /// 'byref' 882 /// 'nonnull' 883 /// 'nullable' 884 /// 'null_unspecified' 885 /// 886 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, 887 Declarator::TheContext Context) { 888 assert(Context == Declarator::ObjCParameterContext || 889 Context == Declarator::ObjCResultContext); 890 891 while (1) { 892 if (Tok.is(tok::code_completion)) { 893 Actions.CodeCompleteObjCPassingType(getCurScope(), DS, 894 Context == Declarator::ObjCParameterContext); 895 return cutOffParsing(); 896 } 897 898 if (Tok.isNot(tok::identifier)) 899 return; 900 901 const IdentifierInfo *II = Tok.getIdentifierInfo(); 902 for (unsigned i = 0; i != objc_NumQuals; ++i) { 903 if (II != ObjCTypeQuals[i] || 904 NextToken().is(tok::less) || 905 NextToken().is(tok::coloncolon)) 906 continue; 907 908 ObjCDeclSpec::ObjCDeclQualifier Qual; 909 NullabilityKind Nullability; 910 switch (i) { 911 default: llvm_unreachable("Unknown decl qualifier"); 912 case objc_in: Qual = ObjCDeclSpec::DQ_In; break; 913 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break; 914 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break; 915 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break; 916 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break; 917 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break; 918 919 case objc_nonnull: 920 Qual = ObjCDeclSpec::DQ_CSNullability; 921 Nullability = NullabilityKind::NonNull; 922 break; 923 924 case objc_nullable: 925 Qual = ObjCDeclSpec::DQ_CSNullability; 926 Nullability = NullabilityKind::Nullable; 927 break; 928 929 case objc_null_unspecified: 930 Qual = ObjCDeclSpec::DQ_CSNullability; 931 Nullability = NullabilityKind::Unspecified; 932 break; 933 } 934 935 // FIXME: Diagnose redundant specifiers. 936 DS.setObjCDeclQualifier(Qual); 937 if (Qual == ObjCDeclSpec::DQ_CSNullability) 938 DS.setNullability(Tok.getLocation(), Nullability); 939 940 ConsumeToken(); 941 II = nullptr; 942 break; 943 } 944 945 // If this wasn't a recognized qualifier, bail out. 946 if (II) return; 947 } 948 } 949 950 /// Take all the decl attributes out of the given list and add 951 /// them to the given attribute set. 952 static void takeDeclAttributes(ParsedAttributes &attrs, 953 AttributeList *list) { 954 while (list) { 955 AttributeList *cur = list; 956 list = cur->getNext(); 957 958 if (!cur->isUsedAsTypeAttr()) { 959 // Clear out the next pointer. We're really completely 960 // destroying the internal invariants of the declarator here, 961 // but it doesn't matter because we're done with it. 962 cur->setNext(nullptr); 963 attrs.add(cur); 964 } 965 } 966 } 967 968 /// takeDeclAttributes - Take all the decl attributes from the given 969 /// declarator and add them to the given list. 970 static void takeDeclAttributes(ParsedAttributes &attrs, 971 Declarator &D) { 972 // First, take ownership of all attributes. 973 attrs.getPool().takeAllFrom(D.getAttributePool()); 974 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool()); 975 976 // Now actually move the attributes over. 977 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList()); 978 takeDeclAttributes(attrs, D.getAttributes()); 979 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 980 takeDeclAttributes(attrs, 981 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs())); 982 } 983 984 /// objc-type-name: 985 /// '(' objc-type-qualifiers[opt] type-name ')' 986 /// '(' objc-type-qualifiers[opt] ')' 987 /// 988 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, 989 Declarator::TheContext context, 990 ParsedAttributes *paramAttrs) { 991 assert(context == Declarator::ObjCParameterContext || 992 context == Declarator::ObjCResultContext); 993 assert((paramAttrs != nullptr) == 994 (context == Declarator::ObjCParameterContext)); 995 996 assert(Tok.is(tok::l_paren) && "expected ("); 997 998 BalancedDelimiterTracker T(*this, tok::l_paren); 999 T.consumeOpen(); 1000 1001 SourceLocation TypeStartLoc = Tok.getLocation(); 1002 ObjCDeclContextSwitch ObjCDC(*this); 1003 1004 // Parse type qualifiers, in, inout, etc. 1005 ParseObjCTypeQualifierList(DS, context); 1006 1007 ParsedType Ty; 1008 if (isTypeSpecifierQualifier()) { 1009 // Parse an abstract declarator. 1010 DeclSpec declSpec(AttrFactory); 1011 declSpec.setObjCQualifiers(&DS); 1012 ParseSpecifierQualifierList(declSpec); 1013 declSpec.SetRangeEnd(Tok.getLocation()); 1014 Declarator declarator(declSpec, context); 1015 ParseDeclarator(declarator); 1016 1017 // If that's not invalid, extract a type. 1018 if (!declarator.isInvalidType()) { 1019 // Map a nullability specifier to a context-sensitive keyword attribute. 1020 bool addedToDeclSpec = false; 1021 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) 1022 addContextSensitiveTypeNullability(*this, declarator, 1023 DS.getNullability(), 1024 DS.getNullabilityLoc(), 1025 addedToDeclSpec); 1026 1027 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator); 1028 if (!type.isInvalid()) 1029 Ty = type.get(); 1030 1031 // If we're parsing a parameter, steal all the decl attributes 1032 // and add them to the decl spec. 1033 if (context == Declarator::ObjCParameterContext) 1034 takeDeclAttributes(*paramAttrs, declarator); 1035 } 1036 } else if (context == Declarator::ObjCResultContext && 1037 Tok.is(tok::identifier)) { 1038 if (!Ident_instancetype) 1039 Ident_instancetype = PP.getIdentifierInfo("instancetype"); 1040 1041 if (Tok.getIdentifierInfo() == Ident_instancetype) { 1042 SourceLocation loc = ConsumeToken(); 1043 Ty = Actions.ActOnObjCInstanceType(loc); 1044 1045 // Synthesize an abstract declarator so we can use Sema::ActOnTypeName. 1046 bool addedToDeclSpec = false; 1047 const char *prevSpec; 1048 unsigned diagID; 1049 DeclSpec declSpec(AttrFactory); 1050 declSpec.setObjCQualifiers(&DS); 1051 declSpec.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID, 1052 Ty, 1053 Actions.getASTContext().getPrintingPolicy()); 1054 declSpec.SetRangeEnd(loc); 1055 Declarator declarator(declSpec, context); 1056 1057 // Map a nullability specifier to a context-sensitive keyword attribute. 1058 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) 1059 addContextSensitiveTypeNullability(*this, declarator, 1060 DS.getNullability(), 1061 DS.getNullabilityLoc(), 1062 addedToDeclSpec); 1063 1064 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator); 1065 if (!type.isInvalid()) 1066 Ty = type.get(); 1067 } 1068 } 1069 1070 if (Tok.is(tok::r_paren)) 1071 T.consumeClose(); 1072 else if (Tok.getLocation() == TypeStartLoc) { 1073 // If we didn't eat any tokens, then this isn't a type. 1074 Diag(Tok, diag::err_expected_type); 1075 SkipUntil(tok::r_paren, StopAtSemi); 1076 } else { 1077 // Otherwise, we found *something*, but didn't get a ')' in the right 1078 // place. Emit an error then return what we have as the type. 1079 T.consumeClose(); 1080 } 1081 return Ty; 1082 } 1083 1084 /// objc-method-decl: 1085 /// objc-selector 1086 /// objc-keyword-selector objc-parmlist[opt] 1087 /// objc-type-name objc-selector 1088 /// objc-type-name objc-keyword-selector objc-parmlist[opt] 1089 /// 1090 /// objc-keyword-selector: 1091 /// objc-keyword-decl 1092 /// objc-keyword-selector objc-keyword-decl 1093 /// 1094 /// objc-keyword-decl: 1095 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier 1096 /// objc-selector ':' objc-keyword-attributes[opt] identifier 1097 /// ':' objc-type-name objc-keyword-attributes[opt] identifier 1098 /// ':' objc-keyword-attributes[opt] identifier 1099 /// 1100 /// objc-parmlist: 1101 /// objc-parms objc-ellipsis[opt] 1102 /// 1103 /// objc-parms: 1104 /// objc-parms , parameter-declaration 1105 /// 1106 /// objc-ellipsis: 1107 /// , ... 1108 /// 1109 /// objc-keyword-attributes: [OBJC2] 1110 /// __attribute__((unused)) 1111 /// 1112 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, 1113 tok::TokenKind mType, 1114 tok::ObjCKeywordKind MethodImplKind, 1115 bool MethodDefinition) { 1116 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 1117 1118 if (Tok.is(tok::code_completion)) { 1119 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 1120 /*ReturnType=*/ ParsedType()); 1121 cutOffParsing(); 1122 return nullptr; 1123 } 1124 1125 // Parse the return type if present. 1126 ParsedType ReturnType; 1127 ObjCDeclSpec DSRet; 1128 if (Tok.is(tok::l_paren)) 1129 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 1130 nullptr); 1131 1132 // If attributes exist before the method, parse them. 1133 ParsedAttributes methodAttrs(AttrFactory); 1134 if (getLangOpts().ObjC2) 1135 MaybeParseGNUAttributes(methodAttrs); 1136 1137 if (Tok.is(tok::code_completion)) { 1138 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 1139 ReturnType); 1140 cutOffParsing(); 1141 return nullptr; 1142 } 1143 1144 // Now parse the selector. 1145 SourceLocation selLoc; 1146 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc); 1147 1148 // An unnamed colon is valid. 1149 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name. 1150 Diag(Tok, diag::err_expected_selector_for_method) 1151 << SourceRange(mLoc, Tok.getLocation()); 1152 // Skip until we get a ; or @. 1153 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch); 1154 return nullptr; 1155 } 1156 1157 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo; 1158 if (Tok.isNot(tok::colon)) { 1159 // If attributes exist after the method, parse them. 1160 if (getLangOpts().ObjC2) 1161 MaybeParseGNUAttributes(methodAttrs); 1162 1163 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent); 1164 Decl *Result 1165 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), 1166 mType, DSRet, ReturnType, 1167 selLoc, Sel, nullptr, 1168 CParamInfo.data(), CParamInfo.size(), 1169 methodAttrs.getList(), MethodImplKind, 1170 false, MethodDefinition); 1171 PD.complete(Result); 1172 return Result; 1173 } 1174 1175 SmallVector<IdentifierInfo *, 12> KeyIdents; 1176 SmallVector<SourceLocation, 12> KeyLocs; 1177 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos; 1178 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 1179 Scope::FunctionDeclarationScope | Scope::DeclScope); 1180 1181 AttributePool allParamAttrs(AttrFactory); 1182 while (1) { 1183 ParsedAttributes paramAttrs(AttrFactory); 1184 Sema::ObjCArgInfo ArgInfo; 1185 1186 // Each iteration parses a single keyword argument. 1187 if (ExpectAndConsume(tok::colon)) 1188 break; 1189 1190 ArgInfo.Type = ParsedType(); 1191 if (Tok.is(tok::l_paren)) // Parse the argument type if present. 1192 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, 1193 Declarator::ObjCParameterContext, 1194 ¶mAttrs); 1195 1196 // If attributes exist before the argument name, parse them. 1197 // Regardless, collect all the attributes we've parsed so far. 1198 ArgInfo.ArgAttrs = nullptr; 1199 if (getLangOpts().ObjC2) { 1200 MaybeParseGNUAttributes(paramAttrs); 1201 ArgInfo.ArgAttrs = paramAttrs.getList(); 1202 } 1203 1204 // Code completion for the next piece of the selector. 1205 if (Tok.is(tok::code_completion)) { 1206 KeyIdents.push_back(SelIdent); 1207 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1208 mType == tok::minus, 1209 /*AtParameterName=*/true, 1210 ReturnType, KeyIdents); 1211 cutOffParsing(); 1212 return nullptr; 1213 } 1214 1215 if (Tok.isNot(tok::identifier)) { 1216 Diag(Tok, diag::err_expected) 1217 << tok::identifier; // missing argument name. 1218 break; 1219 } 1220 1221 ArgInfo.Name = Tok.getIdentifierInfo(); 1222 ArgInfo.NameLoc = Tok.getLocation(); 1223 ConsumeToken(); // Eat the identifier. 1224 1225 ArgInfos.push_back(ArgInfo); 1226 KeyIdents.push_back(SelIdent); 1227 KeyLocs.push_back(selLoc); 1228 1229 // Make sure the attributes persist. 1230 allParamAttrs.takeAllFrom(paramAttrs.getPool()); 1231 1232 // Code completion for the next piece of the selector. 1233 if (Tok.is(tok::code_completion)) { 1234 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 1235 mType == tok::minus, 1236 /*AtParameterName=*/false, 1237 ReturnType, KeyIdents); 1238 cutOffParsing(); 1239 return nullptr; 1240 } 1241 1242 // Check for another keyword selector. 1243 SelIdent = ParseObjCSelectorPiece(selLoc); 1244 if (!SelIdent && Tok.isNot(tok::colon)) 1245 break; 1246 if (!SelIdent) { 1247 SourceLocation ColonLoc = Tok.getLocation(); 1248 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) { 1249 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name; 1250 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name; 1251 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name; 1252 } 1253 } 1254 // We have a selector or a colon, continue parsing. 1255 } 1256 1257 bool isVariadic = false; 1258 bool cStyleParamWarned = false; 1259 // Parse the (optional) parameter list. 1260 while (Tok.is(tok::comma)) { 1261 ConsumeToken(); 1262 if (Tok.is(tok::ellipsis)) { 1263 isVariadic = true; 1264 ConsumeToken(); 1265 break; 1266 } 1267 if (!cStyleParamWarned) { 1268 Diag(Tok, diag::warn_cstyle_param); 1269 cStyleParamWarned = true; 1270 } 1271 DeclSpec DS(AttrFactory); 1272 ParseDeclarationSpecifiers(DS); 1273 // Parse the declarator. 1274 Declarator ParmDecl(DS, Declarator::PrototypeContext); 1275 ParseDeclarator(ParmDecl); 1276 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 1277 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 1278 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 1279 ParmDecl.getIdentifierLoc(), 1280 Param, 1281 nullptr)); 1282 } 1283 1284 // FIXME: Add support for optional parameter list... 1285 // If attributes exist after the method, parse them. 1286 if (getLangOpts().ObjC2) 1287 MaybeParseGNUAttributes(methodAttrs); 1288 1289 if (KeyIdents.size() == 0) 1290 return nullptr; 1291 1292 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(), 1293 &KeyIdents[0]); 1294 Decl *Result 1295 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), 1296 mType, DSRet, ReturnType, 1297 KeyLocs, Sel, &ArgInfos[0], 1298 CParamInfo.data(), CParamInfo.size(), 1299 methodAttrs.getList(), 1300 MethodImplKind, isVariadic, MethodDefinition); 1301 1302 PD.complete(Result); 1303 return Result; 1304 } 1305 1306 /// objc-protocol-refs: 1307 /// '<' identifier-list '>' 1308 /// 1309 bool Parser:: 1310 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols, 1311 SmallVectorImpl<SourceLocation> &ProtocolLocs, 1312 bool WarnOnDeclarations, bool ForObjCContainer, 1313 SourceLocation &LAngleLoc, SourceLocation &EndLoc) { 1314 assert(Tok.is(tok::less) && "expected <"); 1315 1316 LAngleLoc = ConsumeToken(); // the "<" 1317 1318 SmallVector<IdentifierLocPair, 8> ProtocolIdents; 1319 1320 while (1) { 1321 if (Tok.is(tok::code_completion)) { 1322 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(), 1323 ProtocolIdents.size()); 1324 cutOffParsing(); 1325 return true; 1326 } 1327 1328 if (Tok.isNot(tok::identifier)) { 1329 Diag(Tok, diag::err_expected) << tok::identifier; 1330 SkipUntil(tok::greater, StopAtSemi); 1331 return true; 1332 } 1333 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(), 1334 Tok.getLocation())); 1335 ProtocolLocs.push_back(Tok.getLocation()); 1336 ConsumeToken(); 1337 1338 if (!TryConsumeToken(tok::comma)) 1339 break; 1340 } 1341 1342 // Consume the '>'. 1343 if (ParseGreaterThanInTemplateList(EndLoc, /*ConsumeLastToken=*/true)) 1344 return true; 1345 1346 // Convert the list of protocols identifiers into a list of protocol decls. 1347 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer, 1348 &ProtocolIdents[0], ProtocolIdents.size(), 1349 Protocols); 1350 return false; 1351 } 1352 1353 /// \brief Parse the Objective-C protocol qualifiers that follow a typename 1354 /// in a decl-specifier-seq, starting at the '<'. 1355 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) { 1356 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'"); 1357 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C"); 1358 SourceLocation LAngleLoc, EndProtoLoc; 1359 SmallVector<Decl *, 8> ProtocolDecl; 1360 SmallVector<SourceLocation, 8> ProtocolLocs; 1361 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1362 false, 1363 LAngleLoc, EndProtoLoc); 1364 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1365 ProtocolLocs.data(), LAngleLoc); 1366 if (EndProtoLoc.isValid()) 1367 DS.SetRangeEnd(EndProtoLoc); 1368 return Result; 1369 } 1370 1371 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, 1372 BalancedDelimiterTracker &T, 1373 SmallVectorImpl<Decl *> &AllIvarDecls, 1374 bool RBraceMissing) { 1375 if (!RBraceMissing) 1376 T.consumeClose(); 1377 1378 Actions.ActOnObjCContainerStartDefinition(interfaceDecl); 1379 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls); 1380 Actions.ActOnObjCContainerFinishDefinition(); 1381 // Call ActOnFields() even if we don't have any decls. This is useful 1382 // for code rewriting tools that need to be aware of the empty list. 1383 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, 1384 AllIvarDecls, 1385 T.getOpenLocation(), T.getCloseLocation(), nullptr); 1386 } 1387 1388 /// objc-class-instance-variables: 1389 /// '{' objc-instance-variable-decl-list[opt] '}' 1390 /// 1391 /// objc-instance-variable-decl-list: 1392 /// objc-visibility-spec 1393 /// objc-instance-variable-decl ';' 1394 /// ';' 1395 /// objc-instance-variable-decl-list objc-visibility-spec 1396 /// objc-instance-variable-decl-list objc-instance-variable-decl ';' 1397 /// objc-instance-variable-decl-list ';' 1398 /// 1399 /// objc-visibility-spec: 1400 /// @private 1401 /// @protected 1402 /// @public 1403 /// @package [OBJC2] 1404 /// 1405 /// objc-instance-variable-decl: 1406 /// struct-declaration 1407 /// 1408 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, 1409 tok::ObjCKeywordKind visibility, 1410 SourceLocation atLoc) { 1411 assert(Tok.is(tok::l_brace) && "expected {"); 1412 SmallVector<Decl *, 32> AllIvarDecls; 1413 1414 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); 1415 ObjCDeclContextSwitch ObjCDC(*this); 1416 1417 BalancedDelimiterTracker T(*this, tok::l_brace); 1418 T.consumeOpen(); 1419 // While we still have something to read, read the instance variables. 1420 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 1421 // Each iteration of this loop reads one objc-instance-variable-decl. 1422 1423 // Check for extraneous top-level semicolon. 1424 if (Tok.is(tok::semi)) { 1425 ConsumeExtraSemi(InstanceVariableList); 1426 continue; 1427 } 1428 1429 // Set the default visibility to private. 1430 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec 1431 if (Tok.is(tok::code_completion)) { 1432 Actions.CodeCompleteObjCAtVisibility(getCurScope()); 1433 return cutOffParsing(); 1434 } 1435 1436 switch (Tok.getObjCKeywordID()) { 1437 case tok::objc_private: 1438 case tok::objc_public: 1439 case tok::objc_protected: 1440 case tok::objc_package: 1441 visibility = Tok.getObjCKeywordID(); 1442 ConsumeToken(); 1443 continue; 1444 1445 case tok::objc_end: 1446 Diag(Tok, diag::err_objc_unexpected_atend); 1447 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1)); 1448 Tok.setKind(tok::at); 1449 Tok.setLength(1); 1450 PP.EnterToken(Tok); 1451 HelperActionsForIvarDeclarations(interfaceDecl, atLoc, 1452 T, AllIvarDecls, true); 1453 return; 1454 1455 default: 1456 Diag(Tok, diag::err_objc_illegal_visibility_spec); 1457 continue; 1458 } 1459 } 1460 1461 if (Tok.is(tok::code_completion)) { 1462 Actions.CodeCompleteOrdinaryName(getCurScope(), 1463 Sema::PCC_ObjCInstanceVariableList); 1464 return cutOffParsing(); 1465 } 1466 1467 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) { 1468 Actions.ActOnObjCContainerStartDefinition(interfaceDecl); 1469 // Install the declarator into the interface decl. 1470 FD.D.setObjCIvar(true); 1471 Decl *Field = Actions.ActOnIvar( 1472 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D, 1473 FD.BitfieldSize, visibility); 1474 Actions.ActOnObjCContainerFinishDefinition(); 1475 if (Field) 1476 AllIvarDecls.push_back(Field); 1477 FD.complete(Field); 1478 }; 1479 1480 // Parse all the comma separated declarators. 1481 ParsingDeclSpec DS(*this); 1482 ParseStructDeclaration(DS, ObjCIvarCallback); 1483 1484 if (Tok.is(tok::semi)) { 1485 ConsumeToken(); 1486 } else { 1487 Diag(Tok, diag::err_expected_semi_decl_list); 1488 // Skip to end of block or statement 1489 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 1490 } 1491 } 1492 HelperActionsForIvarDeclarations(interfaceDecl, atLoc, 1493 T, AllIvarDecls, false); 1494 return; 1495 } 1496 1497 /// objc-protocol-declaration: 1498 /// objc-protocol-definition 1499 /// objc-protocol-forward-reference 1500 /// 1501 /// objc-protocol-definition: 1502 /// \@protocol identifier 1503 /// objc-protocol-refs[opt] 1504 /// objc-interface-decl-list 1505 /// \@end 1506 /// 1507 /// objc-protocol-forward-reference: 1508 /// \@protocol identifier-list ';' 1509 /// 1510 /// "\@protocol identifier ;" should be resolved as "\@protocol 1511 /// identifier-list ;": objc-interface-decl-list may not start with a 1512 /// semicolon in the first alternative if objc-protocol-refs are omitted. 1513 Parser::DeclGroupPtrTy 1514 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, 1515 ParsedAttributes &attrs) { 1516 assert(Tok.isObjCAtKeyword(tok::objc_protocol) && 1517 "ParseObjCAtProtocolDeclaration(): Expected @protocol"); 1518 ConsumeToken(); // the "protocol" identifier 1519 1520 if (Tok.is(tok::code_completion)) { 1521 Actions.CodeCompleteObjCProtocolDecl(getCurScope()); 1522 cutOffParsing(); 1523 return DeclGroupPtrTy(); 1524 } 1525 1526 MaybeSkipAttributes(tok::objc_protocol); 1527 1528 if (Tok.isNot(tok::identifier)) { 1529 Diag(Tok, diag::err_expected) << tok::identifier; // missing protocol name. 1530 return DeclGroupPtrTy(); 1531 } 1532 // Save the protocol name, then consume it. 1533 IdentifierInfo *protocolName = Tok.getIdentifierInfo(); 1534 SourceLocation nameLoc = ConsumeToken(); 1535 1536 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol. 1537 IdentifierLocPair ProtoInfo(protocolName, nameLoc); 1538 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1, 1539 attrs.getList()); 1540 } 1541 1542 CheckNestedObjCContexts(AtLoc); 1543 1544 if (Tok.is(tok::comma)) { // list of forward declarations. 1545 SmallVector<IdentifierLocPair, 8> ProtocolRefs; 1546 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc)); 1547 1548 // Parse the list of forward declarations. 1549 while (1) { 1550 ConsumeToken(); // the ',' 1551 if (Tok.isNot(tok::identifier)) { 1552 Diag(Tok, diag::err_expected) << tok::identifier; 1553 SkipUntil(tok::semi); 1554 return DeclGroupPtrTy(); 1555 } 1556 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(), 1557 Tok.getLocation())); 1558 ConsumeToken(); // the identifier 1559 1560 if (Tok.isNot(tok::comma)) 1561 break; 1562 } 1563 // Consume the ';'. 1564 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol")) 1565 return DeclGroupPtrTy(); 1566 1567 return Actions.ActOnForwardProtocolDeclaration(AtLoc, 1568 &ProtocolRefs[0], 1569 ProtocolRefs.size(), 1570 attrs.getList()); 1571 } 1572 1573 // Last, and definitely not least, parse a protocol declaration. 1574 SourceLocation LAngleLoc, EndProtoLoc; 1575 1576 SmallVector<Decl *, 8> ProtocolRefs; 1577 SmallVector<SourceLocation, 8> ProtocolLocs; 1578 if (Tok.is(tok::less) && 1579 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true, 1580 LAngleLoc, EndProtoLoc)) 1581 return DeclGroupPtrTy(); 1582 1583 Decl *ProtoType = 1584 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc, 1585 ProtocolRefs.data(), 1586 ProtocolRefs.size(), 1587 ProtocolLocs.data(), 1588 EndProtoLoc, attrs.getList()); 1589 1590 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType); 1591 return Actions.ConvertDeclToDeclGroup(ProtoType); 1592 } 1593 1594 /// objc-implementation: 1595 /// objc-class-implementation-prologue 1596 /// objc-category-implementation-prologue 1597 /// 1598 /// objc-class-implementation-prologue: 1599 /// @implementation identifier objc-superclass[opt] 1600 /// objc-class-instance-variables[opt] 1601 /// 1602 /// objc-category-implementation-prologue: 1603 /// @implementation identifier ( identifier ) 1604 Parser::DeclGroupPtrTy 1605 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { 1606 assert(Tok.isObjCAtKeyword(tok::objc_implementation) && 1607 "ParseObjCAtImplementationDeclaration(): Expected @implementation"); 1608 CheckNestedObjCContexts(AtLoc); 1609 ConsumeToken(); // the "implementation" identifier 1610 1611 // Code completion after '@implementation'. 1612 if (Tok.is(tok::code_completion)) { 1613 Actions.CodeCompleteObjCImplementationDecl(getCurScope()); 1614 cutOffParsing(); 1615 return DeclGroupPtrTy(); 1616 } 1617 1618 MaybeSkipAttributes(tok::objc_implementation); 1619 1620 if (Tok.isNot(tok::identifier)) { 1621 Diag(Tok, diag::err_expected) 1622 << tok::identifier; // missing class or category name. 1623 return DeclGroupPtrTy(); 1624 } 1625 // We have a class or category name - consume it. 1626 IdentifierInfo *nameId = Tok.getIdentifierInfo(); 1627 SourceLocation nameLoc = ConsumeToken(); // consume class or category name 1628 Decl *ObjCImpDecl = nullptr; 1629 1630 if (Tok.is(tok::l_paren)) { 1631 // we have a category implementation. 1632 ConsumeParen(); 1633 SourceLocation categoryLoc, rparenLoc; 1634 IdentifierInfo *categoryId = nullptr; 1635 1636 if (Tok.is(tok::code_completion)) { 1637 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc); 1638 cutOffParsing(); 1639 return DeclGroupPtrTy(); 1640 } 1641 1642 if (Tok.is(tok::identifier)) { 1643 categoryId = Tok.getIdentifierInfo(); 1644 categoryLoc = ConsumeToken(); 1645 } else { 1646 Diag(Tok, diag::err_expected) 1647 << tok::identifier; // missing category name. 1648 return DeclGroupPtrTy(); 1649 } 1650 if (Tok.isNot(tok::r_paren)) { 1651 Diag(Tok, diag::err_expected) << tok::r_paren; 1652 SkipUntil(tok::r_paren); // don't stop at ';' 1653 return DeclGroupPtrTy(); 1654 } 1655 rparenLoc = ConsumeParen(); 1656 if (Tok.is(tok::less)) { // we have illegal '<' try to recover 1657 Diag(Tok, diag::err_unexpected_protocol_qualifier); 1658 AttributeFactory attr; 1659 DeclSpec DS(attr); 1660 (void)ParseObjCProtocolQualifiers(DS); 1661 } 1662 ObjCImpDecl = Actions.ActOnStartCategoryImplementation( 1663 AtLoc, nameId, nameLoc, categoryId, 1664 categoryLoc); 1665 1666 } else { 1667 // We have a class implementation 1668 SourceLocation superClassLoc; 1669 IdentifierInfo *superClassId = nullptr; 1670 if (TryConsumeToken(tok::colon)) { 1671 // We have a super class 1672 if (Tok.isNot(tok::identifier)) { 1673 Diag(Tok, diag::err_expected) 1674 << tok::identifier; // missing super class name. 1675 return DeclGroupPtrTy(); 1676 } 1677 superClassId = Tok.getIdentifierInfo(); 1678 superClassLoc = ConsumeToken(); // Consume super class name 1679 } 1680 ObjCImpDecl = Actions.ActOnStartClassImplementation( 1681 AtLoc, nameId, nameLoc, 1682 superClassId, superClassLoc); 1683 1684 if (Tok.is(tok::l_brace)) // we have ivars 1685 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc); 1686 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover 1687 Diag(Tok, diag::err_unexpected_protocol_qualifier); 1688 // try to recover. 1689 AttributeFactory attr; 1690 DeclSpec DS(attr); 1691 (void)ParseObjCProtocolQualifiers(DS); 1692 } 1693 } 1694 assert(ObjCImpDecl); 1695 1696 SmallVector<Decl *, 8> DeclsInGroup; 1697 1698 { 1699 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl); 1700 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) { 1701 ParsedAttributesWithRange attrs(AttrFactory); 1702 MaybeParseCXX11Attributes(attrs); 1703 MaybeParseMicrosoftAttributes(attrs); 1704 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) { 1705 DeclGroupRef DG = DGP.get(); 1706 DeclsInGroup.append(DG.begin(), DG.end()); 1707 } 1708 } 1709 } 1710 1711 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup); 1712 } 1713 1714 Parser::DeclGroupPtrTy 1715 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) { 1716 assert(Tok.isObjCAtKeyword(tok::objc_end) && 1717 "ParseObjCAtEndDeclaration(): Expected @end"); 1718 ConsumeToken(); // the "end" identifier 1719 if (CurParsedObjCImpl) 1720 CurParsedObjCImpl->finish(atEnd); 1721 else 1722 // missing @implementation 1723 Diag(atEnd.getBegin(), diag::err_expected_objc_container); 1724 return DeclGroupPtrTy(); 1725 } 1726 1727 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() { 1728 if (!Finished) { 1729 finish(P.Tok.getLocation()); 1730 if (P.isEofOrEom()) { 1731 P.Diag(P.Tok, diag::err_objc_missing_end) 1732 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n"); 1733 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start) 1734 << Sema::OCK_Implementation; 1735 } 1736 } 1737 P.CurParsedObjCImpl = nullptr; 1738 assert(LateParsedObjCMethods.empty()); 1739 } 1740 1741 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) { 1742 assert(!Finished); 1743 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl); 1744 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 1745 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 1746 true/*Methods*/); 1747 1748 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd); 1749 1750 if (HasCFunction) 1751 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) 1752 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 1753 false/*c-functions*/); 1754 1755 /// \brief Clear and free the cached objc methods. 1756 for (LateParsedObjCMethodContainer::iterator 1757 I = LateParsedObjCMethods.begin(), 1758 E = LateParsedObjCMethods.end(); I != E; ++I) 1759 delete *I; 1760 LateParsedObjCMethods.clear(); 1761 1762 Finished = true; 1763 } 1764 1765 /// compatibility-alias-decl: 1766 /// @compatibility_alias alias-name class-name ';' 1767 /// 1768 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) { 1769 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) && 1770 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias"); 1771 ConsumeToken(); // consume compatibility_alias 1772 if (Tok.isNot(tok::identifier)) { 1773 Diag(Tok, diag::err_expected) << tok::identifier; 1774 return nullptr; 1775 } 1776 IdentifierInfo *aliasId = Tok.getIdentifierInfo(); 1777 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name 1778 if (Tok.isNot(tok::identifier)) { 1779 Diag(Tok, diag::err_expected) << tok::identifier; 1780 return nullptr; 1781 } 1782 IdentifierInfo *classId = Tok.getIdentifierInfo(); 1783 SourceLocation classLoc = ConsumeToken(); // consume class-name; 1784 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias"); 1785 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc, 1786 classId, classLoc); 1787 } 1788 1789 /// property-synthesis: 1790 /// @synthesize property-ivar-list ';' 1791 /// 1792 /// property-ivar-list: 1793 /// property-ivar 1794 /// property-ivar-list ',' property-ivar 1795 /// 1796 /// property-ivar: 1797 /// identifier 1798 /// identifier '=' identifier 1799 /// 1800 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { 1801 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) && 1802 "ParseObjCPropertySynthesize(): Expected '@synthesize'"); 1803 ConsumeToken(); // consume synthesize 1804 1805 while (true) { 1806 if (Tok.is(tok::code_completion)) { 1807 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 1808 cutOffParsing(); 1809 return nullptr; 1810 } 1811 1812 if (Tok.isNot(tok::identifier)) { 1813 Diag(Tok, diag::err_synthesized_property_name); 1814 SkipUntil(tok::semi); 1815 return nullptr; 1816 } 1817 1818 IdentifierInfo *propertyIvar = nullptr; 1819 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1820 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1821 SourceLocation propertyIvarLoc; 1822 if (TryConsumeToken(tok::equal)) { 1823 // property '=' ivar-name 1824 if (Tok.is(tok::code_completion)) { 1825 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId); 1826 cutOffParsing(); 1827 return nullptr; 1828 } 1829 1830 if (Tok.isNot(tok::identifier)) { 1831 Diag(Tok, diag::err_expected) << tok::identifier; 1832 break; 1833 } 1834 propertyIvar = Tok.getIdentifierInfo(); 1835 propertyIvarLoc = ConsumeToken(); // consume ivar-name 1836 } 1837 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, 1838 propertyId, propertyIvar, propertyIvarLoc); 1839 if (Tok.isNot(tok::comma)) 1840 break; 1841 ConsumeToken(); // consume ',' 1842 } 1843 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize"); 1844 return nullptr; 1845 } 1846 1847 /// property-dynamic: 1848 /// @dynamic property-list 1849 /// 1850 /// property-list: 1851 /// identifier 1852 /// property-list ',' identifier 1853 /// 1854 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { 1855 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) && 1856 "ParseObjCPropertyDynamic(): Expected '@dynamic'"); 1857 ConsumeToken(); // consume dynamic 1858 while (true) { 1859 if (Tok.is(tok::code_completion)) { 1860 Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); 1861 cutOffParsing(); 1862 return nullptr; 1863 } 1864 1865 if (Tok.isNot(tok::identifier)) { 1866 Diag(Tok, diag::err_expected) << tok::identifier; 1867 SkipUntil(tok::semi); 1868 return nullptr; 1869 } 1870 1871 IdentifierInfo *propertyId = Tok.getIdentifierInfo(); 1872 SourceLocation propertyLoc = ConsumeToken(); // consume property name 1873 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, 1874 propertyId, nullptr, SourceLocation()); 1875 1876 if (Tok.isNot(tok::comma)) 1877 break; 1878 ConsumeToken(); // consume ',' 1879 } 1880 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic"); 1881 return nullptr; 1882 } 1883 1884 /// objc-throw-statement: 1885 /// throw expression[opt]; 1886 /// 1887 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) { 1888 ExprResult Res; 1889 ConsumeToken(); // consume throw 1890 if (Tok.isNot(tok::semi)) { 1891 Res = ParseExpression(); 1892 if (Res.isInvalid()) { 1893 SkipUntil(tok::semi); 1894 return StmtError(); 1895 } 1896 } 1897 // consume ';' 1898 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw"); 1899 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope()); 1900 } 1901 1902 /// objc-synchronized-statement: 1903 /// @synchronized '(' expression ')' compound-statement 1904 /// 1905 StmtResult 1906 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) { 1907 ConsumeToken(); // consume synchronized 1908 if (Tok.isNot(tok::l_paren)) { 1909 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized"; 1910 return StmtError(); 1911 } 1912 1913 // The operand is surrounded with parentheses. 1914 ConsumeParen(); // '(' 1915 ExprResult operand(ParseExpression()); 1916 1917 if (Tok.is(tok::r_paren)) { 1918 ConsumeParen(); // ')' 1919 } else { 1920 if (!operand.isInvalid()) 1921 Diag(Tok, diag::err_expected) << tok::r_paren; 1922 1923 // Skip forward until we see a left brace, but don't consume it. 1924 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 1925 } 1926 1927 // Require a compound statement. 1928 if (Tok.isNot(tok::l_brace)) { 1929 if (!operand.isInvalid()) 1930 Diag(Tok, diag::err_expected) << tok::l_brace; 1931 return StmtError(); 1932 } 1933 1934 // Check the @synchronized operand now. 1935 if (!operand.isInvalid()) 1936 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get()); 1937 1938 // Parse the compound statement within a new scope. 1939 ParseScope bodyScope(this, Scope::DeclScope); 1940 StmtResult body(ParseCompoundStatementBody()); 1941 bodyScope.Exit(); 1942 1943 // If there was a semantic or parse error earlier with the 1944 // operand, fail now. 1945 if (operand.isInvalid()) 1946 return StmtError(); 1947 1948 if (body.isInvalid()) 1949 body = Actions.ActOnNullStmt(Tok.getLocation()); 1950 1951 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get()); 1952 } 1953 1954 /// objc-try-catch-statement: 1955 /// @try compound-statement objc-catch-list[opt] 1956 /// @try compound-statement objc-catch-list[opt] @finally compound-statement 1957 /// 1958 /// objc-catch-list: 1959 /// @catch ( parameter-declaration ) compound-statement 1960 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement 1961 /// catch-parameter-declaration: 1962 /// parameter-declaration 1963 /// '...' [OBJC2] 1964 /// 1965 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { 1966 bool catch_or_finally_seen = false; 1967 1968 ConsumeToken(); // consume try 1969 if (Tok.isNot(tok::l_brace)) { 1970 Diag(Tok, diag::err_expected) << tok::l_brace; 1971 return StmtError(); 1972 } 1973 StmtVector CatchStmts; 1974 StmtResult FinallyStmt; 1975 ParseScope TryScope(this, Scope::DeclScope); 1976 StmtResult TryBody(ParseCompoundStatementBody()); 1977 TryScope.Exit(); 1978 if (TryBody.isInvalid()) 1979 TryBody = Actions.ActOnNullStmt(Tok.getLocation()); 1980 1981 while (Tok.is(tok::at)) { 1982 // At this point, we need to lookahead to determine if this @ is the start 1983 // of an @catch or @finally. We don't want to consume the @ token if this 1984 // is an @try or @encode or something else. 1985 Token AfterAt = GetLookAheadToken(1); 1986 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) && 1987 !AfterAt.isObjCAtKeyword(tok::objc_finally)) 1988 break; 1989 1990 SourceLocation AtCatchFinallyLoc = ConsumeToken(); 1991 if (Tok.isObjCAtKeyword(tok::objc_catch)) { 1992 Decl *FirstPart = nullptr; 1993 ConsumeToken(); // consume catch 1994 if (Tok.is(tok::l_paren)) { 1995 ConsumeParen(); 1996 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope); 1997 if (Tok.isNot(tok::ellipsis)) { 1998 DeclSpec DS(AttrFactory); 1999 ParseDeclarationSpecifiers(DS); 2000 Declarator ParmDecl(DS, Declarator::ObjCCatchContext); 2001 ParseDeclarator(ParmDecl); 2002 2003 // Inform the actions module about the declarator, so it 2004 // gets added to the current scope. 2005 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl); 2006 } else 2007 ConsumeToken(); // consume '...' 2008 2009 SourceLocation RParenLoc; 2010 2011 if (Tok.is(tok::r_paren)) 2012 RParenLoc = ConsumeParen(); 2013 else // Skip over garbage, until we get to ')'. Eat the ')'. 2014 SkipUntil(tok::r_paren, StopAtSemi); 2015 2016 StmtResult CatchBody(true); 2017 if (Tok.is(tok::l_brace)) 2018 CatchBody = ParseCompoundStatementBody(); 2019 else 2020 Diag(Tok, diag::err_expected) << tok::l_brace; 2021 if (CatchBody.isInvalid()) 2022 CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); 2023 2024 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, 2025 RParenLoc, 2026 FirstPart, 2027 CatchBody.get()); 2028 if (!Catch.isInvalid()) 2029 CatchStmts.push_back(Catch.get()); 2030 2031 } else { 2032 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) 2033 << "@catch clause"; 2034 return StmtError(); 2035 } 2036 catch_or_finally_seen = true; 2037 } else { 2038 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?"); 2039 ConsumeToken(); // consume finally 2040 ParseScope FinallyScope(this, Scope::DeclScope); 2041 2042 StmtResult FinallyBody(true); 2043 if (Tok.is(tok::l_brace)) 2044 FinallyBody = ParseCompoundStatementBody(); 2045 else 2046 Diag(Tok, diag::err_expected) << tok::l_brace; 2047 if (FinallyBody.isInvalid()) 2048 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation()); 2049 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc, 2050 FinallyBody.get()); 2051 catch_or_finally_seen = true; 2052 break; 2053 } 2054 } 2055 if (!catch_or_finally_seen) { 2056 Diag(atLoc, diag::err_missing_catch_finally); 2057 return StmtError(); 2058 } 2059 2060 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), 2061 CatchStmts, 2062 FinallyStmt.get()); 2063 } 2064 2065 /// objc-autoreleasepool-statement: 2066 /// @autoreleasepool compound-statement 2067 /// 2068 StmtResult 2069 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) { 2070 ConsumeToken(); // consume autoreleasepool 2071 if (Tok.isNot(tok::l_brace)) { 2072 Diag(Tok, diag::err_expected) << tok::l_brace; 2073 return StmtError(); 2074 } 2075 // Enter a scope to hold everything within the compound stmt. Compound 2076 // statements can always hold declarations. 2077 ParseScope BodyScope(this, Scope::DeclScope); 2078 2079 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody()); 2080 2081 BodyScope.Exit(); 2082 if (AutoreleasePoolBody.isInvalid()) 2083 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation()); 2084 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, 2085 AutoreleasePoolBody.get()); 2086 } 2087 2088 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them 2089 /// for later parsing. 2090 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) { 2091 LexedMethod* LM = new LexedMethod(this, MDecl); 2092 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM); 2093 CachedTokens &Toks = LM->Toks; 2094 // Begin by storing the '{' or 'try' or ':' token. 2095 Toks.push_back(Tok); 2096 if (Tok.is(tok::kw_try)) { 2097 ConsumeToken(); 2098 if (Tok.is(tok::colon)) { 2099 Toks.push_back(Tok); 2100 ConsumeToken(); 2101 while (Tok.isNot(tok::l_brace)) { 2102 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); 2103 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 2104 } 2105 } 2106 Toks.push_back(Tok); // also store '{' 2107 } 2108 else if (Tok.is(tok::colon)) { 2109 ConsumeToken(); 2110 while (Tok.isNot(tok::l_brace)) { 2111 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); 2112 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 2113 } 2114 Toks.push_back(Tok); // also store '{' 2115 } 2116 ConsumeBrace(); 2117 // Consume everything up to (and including) the matching right brace. 2118 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 2119 while (Tok.is(tok::kw_catch)) { 2120 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); 2121 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 2122 } 2123 } 2124 2125 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}' 2126 /// 2127 Decl *Parser::ParseObjCMethodDefinition() { 2128 Decl *MDecl = ParseObjCMethodPrototype(); 2129 2130 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(), 2131 "parsing Objective-C method"); 2132 2133 // parse optional ';' 2134 if (Tok.is(tok::semi)) { 2135 if (CurParsedObjCImpl) { 2136 Diag(Tok, diag::warn_semicolon_before_method_body) 2137 << FixItHint::CreateRemoval(Tok.getLocation()); 2138 } 2139 ConsumeToken(); 2140 } 2141 2142 // We should have an opening brace now. 2143 if (Tok.isNot(tok::l_brace)) { 2144 Diag(Tok, diag::err_expected_method_body); 2145 2146 // Skip over garbage, until we get to '{'. Don't eat the '{'. 2147 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 2148 2149 // If we didn't find the '{', bail out. 2150 if (Tok.isNot(tok::l_brace)) 2151 return nullptr; 2152 } 2153 2154 if (!MDecl) { 2155 ConsumeBrace(); 2156 SkipUntil(tok::r_brace); 2157 return nullptr; 2158 } 2159 2160 // Allow the rest of sema to find private method decl implementations. 2161 Actions.AddAnyMethodToGlobalPool(MDecl); 2162 assert (CurParsedObjCImpl 2163 && "ParseObjCMethodDefinition - Method out of @implementation"); 2164 // Consume the tokens and store them for later parsing. 2165 StashAwayMethodOrFunctionBodyTokens(MDecl); 2166 return MDecl; 2167 } 2168 2169 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { 2170 if (Tok.is(tok::code_completion)) { 2171 Actions.CodeCompleteObjCAtStatement(getCurScope()); 2172 cutOffParsing(); 2173 return StmtError(); 2174 } 2175 2176 if (Tok.isObjCAtKeyword(tok::objc_try)) 2177 return ParseObjCTryStmt(AtLoc); 2178 2179 if (Tok.isObjCAtKeyword(tok::objc_throw)) 2180 return ParseObjCThrowStmt(AtLoc); 2181 2182 if (Tok.isObjCAtKeyword(tok::objc_synchronized)) 2183 return ParseObjCSynchronizedStmt(AtLoc); 2184 2185 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool)) 2186 return ParseObjCAutoreleasePoolStmt(AtLoc); 2187 2188 if (Tok.isObjCAtKeyword(tok::objc_import) && 2189 getLangOpts().DebuggerSupport) { 2190 SkipUntil(tok::semi); 2191 return Actions.ActOnNullStmt(Tok.getLocation()); 2192 } 2193 2194 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc)); 2195 if (Res.isInvalid()) { 2196 // If the expression is invalid, skip ahead to the next semicolon. Not 2197 // doing this opens us up to the possibility of infinite loops if 2198 // ParseExpression does not consume any tokens. 2199 SkipUntil(tok::semi); 2200 return StmtError(); 2201 } 2202 2203 // Otherwise, eat the semicolon. 2204 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 2205 return Actions.ActOnExprStmt(Res); 2206 } 2207 2208 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { 2209 switch (Tok.getKind()) { 2210 case tok::code_completion: 2211 Actions.CodeCompleteObjCAtExpression(getCurScope()); 2212 cutOffParsing(); 2213 return ExprError(); 2214 2215 case tok::minus: 2216 case tok::plus: { 2217 tok::TokenKind Kind = Tok.getKind(); 2218 SourceLocation OpLoc = ConsumeToken(); 2219 2220 if (!Tok.is(tok::numeric_constant)) { 2221 const char *Symbol = nullptr; 2222 switch (Kind) { 2223 case tok::minus: Symbol = "-"; break; 2224 case tok::plus: Symbol = "+"; break; 2225 default: llvm_unreachable("missing unary operator case"); 2226 } 2227 Diag(Tok, diag::err_nsnumber_nonliteral_unary) 2228 << Symbol; 2229 return ExprError(); 2230 } 2231 2232 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 2233 if (Lit.isInvalid()) { 2234 return Lit; 2235 } 2236 ConsumeToken(); // Consume the literal token. 2237 2238 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get()); 2239 if (Lit.isInvalid()) 2240 return Lit; 2241 2242 return ParsePostfixExpressionSuffix( 2243 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get())); 2244 } 2245 2246 case tok::string_literal: // primary-expression: string-literal 2247 case tok::wide_string_literal: 2248 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc)); 2249 2250 case tok::char_constant: 2251 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc)); 2252 2253 case tok::numeric_constant: 2254 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc)); 2255 2256 case tok::kw_true: // Objective-C++, etc. 2257 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes 2258 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true)); 2259 case tok::kw_false: // Objective-C++, etc. 2260 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no 2261 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false)); 2262 2263 case tok::l_square: 2264 // Objective-C array literal 2265 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc)); 2266 2267 case tok::l_brace: 2268 // Objective-C dictionary literal 2269 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc)); 2270 2271 case tok::l_paren: 2272 // Objective-C boxed expression 2273 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc)); 2274 2275 default: 2276 if (Tok.getIdentifierInfo() == nullptr) 2277 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2278 2279 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) { 2280 case tok::objc_encode: 2281 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc)); 2282 case tok::objc_protocol: 2283 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc)); 2284 case tok::objc_selector: 2285 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc)); 2286 default: { 2287 const char *str = nullptr; 2288 if (GetLookAheadToken(1).is(tok::l_brace)) { 2289 char ch = Tok.getIdentifierInfo()->getNameStart()[0]; 2290 str = 2291 ch == 't' ? "try" 2292 : (ch == 'f' ? "finally" 2293 : (ch == 'a' ? "autoreleasepool" : nullptr)); 2294 } 2295 if (str) { 2296 SourceLocation kwLoc = Tok.getLocation(); 2297 return ExprError(Diag(AtLoc, diag::err_unexpected_at) << 2298 FixItHint::CreateReplacement(kwLoc, str)); 2299 } 2300 else 2301 return ExprError(Diag(AtLoc, diag::err_unexpected_at)); 2302 } 2303 } 2304 } 2305 } 2306 2307 /// \brief Parse the receiver of an Objective-C++ message send. 2308 /// 2309 /// This routine parses the receiver of a message send in 2310 /// Objective-C++ either as a type or as an expression. Note that this 2311 /// routine must not be called to parse a send to 'super', since it 2312 /// has no way to return such a result. 2313 /// 2314 /// \param IsExpr Whether the receiver was parsed as an expression. 2315 /// 2316 /// \param TypeOrExpr If the receiver was parsed as an expression (\c 2317 /// IsExpr is true), the parsed expression. If the receiver was parsed 2318 /// as a type (\c IsExpr is false), the parsed type. 2319 /// 2320 /// \returns True if an error occurred during parsing or semantic 2321 /// analysis, in which case the arguments do not have valid 2322 /// values. Otherwise, returns false for a successful parse. 2323 /// 2324 /// objc-receiver: [C++] 2325 /// 'super' [not parsed here] 2326 /// expression 2327 /// simple-type-specifier 2328 /// typename-specifier 2329 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { 2330 InMessageExpressionRAIIObject InMessage(*this, true); 2331 2332 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename, 2333 tok::annot_cxxscope)) 2334 TryAnnotateTypeOrScopeToken(); 2335 2336 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) { 2337 // objc-receiver: 2338 // expression 2339 // Make sure any typos in the receiver are corrected or diagnosed, so that 2340 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to 2341 // only the things that are valid ObjC receivers? 2342 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression()); 2343 if (Receiver.isInvalid()) 2344 return true; 2345 2346 IsExpr = true; 2347 TypeOrExpr = Receiver.get(); 2348 return false; 2349 } 2350 2351 // objc-receiver: 2352 // typename-specifier 2353 // simple-type-specifier 2354 // expression (that starts with one of the above) 2355 DeclSpec DS(AttrFactory); 2356 ParseCXXSimpleTypeSpecifier(DS); 2357 2358 if (Tok.is(tok::l_paren)) { 2359 // If we see an opening parentheses at this point, we are 2360 // actually parsing an expression that starts with a 2361 // function-style cast, e.g., 2362 // 2363 // postfix-expression: 2364 // simple-type-specifier ( expression-list [opt] ) 2365 // typename-specifier ( expression-list [opt] ) 2366 // 2367 // Parse the remainder of this case, then the (optional) 2368 // postfix-expression suffix, followed by the (optional) 2369 // right-hand side of the binary expression. We have an 2370 // instance method. 2371 ExprResult Receiver = ParseCXXTypeConstructExpression(DS); 2372 if (!Receiver.isInvalid()) 2373 Receiver = ParsePostfixExpressionSuffix(Receiver.get()); 2374 if (!Receiver.isInvalid()) 2375 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma); 2376 if (Receiver.isInvalid()) 2377 return true; 2378 2379 IsExpr = true; 2380 TypeOrExpr = Receiver.get(); 2381 return false; 2382 } 2383 2384 // We have a class message. Turn the simple-type-specifier or 2385 // typename-specifier we parsed into a type and parse the 2386 // remainder of the class message. 2387 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2388 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2389 if (Type.isInvalid()) 2390 return true; 2391 2392 IsExpr = false; 2393 TypeOrExpr = Type.get().getAsOpaquePtr(); 2394 return false; 2395 } 2396 2397 /// \brief Determine whether the parser is currently referring to a an 2398 /// Objective-C message send, using a simplified heuristic to avoid overhead. 2399 /// 2400 /// This routine will only return true for a subset of valid message-send 2401 /// expressions. 2402 bool Parser::isSimpleObjCMessageExpression() { 2403 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 && 2404 "Incorrect start for isSimpleObjCMessageExpression"); 2405 return GetLookAheadToken(1).is(tok::identifier) && 2406 GetLookAheadToken(2).is(tok::identifier); 2407 } 2408 2409 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { 2410 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || 2411 InMessageExpression) 2412 return false; 2413 2414 2415 ParsedType Type; 2416 2417 if (Tok.is(tok::annot_typename)) 2418 Type = getTypeAnnotation(Tok); 2419 else if (Tok.is(tok::identifier)) 2420 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), 2421 getCurScope()); 2422 else 2423 return false; 2424 2425 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { 2426 const Token &AfterNext = GetLookAheadToken(2); 2427 if (AfterNext.isOneOf(tok::colon, tok::r_square)) { 2428 if (Tok.is(tok::identifier)) 2429 TryAnnotateTypeOrScopeToken(); 2430 2431 return Tok.is(tok::annot_typename); 2432 } 2433 } 2434 2435 return false; 2436 } 2437 2438 /// objc-message-expr: 2439 /// '[' objc-receiver objc-message-args ']' 2440 /// 2441 /// objc-receiver: [C] 2442 /// 'super' 2443 /// expression 2444 /// class-name 2445 /// type-name 2446 /// 2447 ExprResult Parser::ParseObjCMessageExpression() { 2448 assert(Tok.is(tok::l_square) && "'[' expected"); 2449 SourceLocation LBracLoc = ConsumeBracket(); // consume '[' 2450 2451 if (Tok.is(tok::code_completion)) { 2452 Actions.CodeCompleteObjCMessageReceiver(getCurScope()); 2453 cutOffParsing(); 2454 return ExprError(); 2455 } 2456 2457 InMessageExpressionRAIIObject InMessage(*this, true); 2458 2459 if (getLangOpts().CPlusPlus) { 2460 // We completely separate the C and C++ cases because C++ requires 2461 // more complicated (read: slower) parsing. 2462 2463 // Handle send to super. 2464 // FIXME: This doesn't benefit from the same typo-correction we 2465 // get in Objective-C. 2466 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && 2467 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) 2468 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 2469 ParsedType(), nullptr); 2470 2471 // Parse the receiver, which is either a type or an expression. 2472 bool IsExpr; 2473 void *TypeOrExpr = nullptr; 2474 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { 2475 SkipUntil(tok::r_square, StopAtSemi); 2476 return ExprError(); 2477 } 2478 2479 if (IsExpr) 2480 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2481 ParsedType(), 2482 static_cast<Expr*>(TypeOrExpr)); 2483 2484 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2485 ParsedType::getFromOpaquePtr(TypeOrExpr), 2486 nullptr); 2487 } 2488 2489 if (Tok.is(tok::identifier)) { 2490 IdentifierInfo *Name = Tok.getIdentifierInfo(); 2491 SourceLocation NameLoc = Tok.getLocation(); 2492 ParsedType ReceiverType; 2493 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc, 2494 Name == Ident_super, 2495 NextToken().is(tok::period), 2496 ReceiverType)) { 2497 case Sema::ObjCSuperMessage: 2498 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 2499 ParsedType(), nullptr); 2500 2501 case Sema::ObjCClassMessage: 2502 if (!ReceiverType) { 2503 SkipUntil(tok::r_square, StopAtSemi); 2504 return ExprError(); 2505 } 2506 2507 ConsumeToken(); // the type name 2508 2509 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2510 ReceiverType, nullptr); 2511 2512 case Sema::ObjCInstanceMessage: 2513 // Fall through to parse an expression. 2514 break; 2515 } 2516 } 2517 2518 // Otherwise, an arbitrary expression can be the receiver of a send. 2519 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression()); 2520 if (Res.isInvalid()) { 2521 SkipUntil(tok::r_square, StopAtSemi); 2522 return Res; 2523 } 2524 2525 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 2526 ParsedType(), Res.get()); 2527 } 2528 2529 /// \brief Parse the remainder of an Objective-C message following the 2530 /// '[' objc-receiver. 2531 /// 2532 /// This routine handles sends to super, class messages (sent to a 2533 /// class name), and instance messages (sent to an object), and the 2534 /// target is represented by \p SuperLoc, \p ReceiverType, or \p 2535 /// ReceiverExpr, respectively. Only one of these parameters may have 2536 /// a valid value. 2537 /// 2538 /// \param LBracLoc The location of the opening '['. 2539 /// 2540 /// \param SuperLoc If this is a send to 'super', the location of the 2541 /// 'super' keyword that indicates a send to the superclass. 2542 /// 2543 /// \param ReceiverType If this is a class message, the type of the 2544 /// class we are sending a message to. 2545 /// 2546 /// \param ReceiverExpr If this is an instance message, the expression 2547 /// used to compute the receiver object. 2548 /// 2549 /// objc-message-args: 2550 /// objc-selector 2551 /// objc-keywordarg-list 2552 /// 2553 /// objc-keywordarg-list: 2554 /// objc-keywordarg 2555 /// objc-keywordarg-list objc-keywordarg 2556 /// 2557 /// objc-keywordarg: 2558 /// selector-name[opt] ':' objc-keywordexpr 2559 /// 2560 /// objc-keywordexpr: 2561 /// nonempty-expr-list 2562 /// 2563 /// nonempty-expr-list: 2564 /// assignment-expression 2565 /// nonempty-expr-list , assignment-expression 2566 /// 2567 ExprResult 2568 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, 2569 SourceLocation SuperLoc, 2570 ParsedType ReceiverType, 2571 Expr *ReceiverExpr) { 2572 InMessageExpressionRAIIObject InMessage(*this, true); 2573 2574 if (Tok.is(tok::code_completion)) { 2575 if (SuperLoc.isValid()) 2576 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None, 2577 false); 2578 else if (ReceiverType) 2579 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None, 2580 false); 2581 else 2582 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2583 None, false); 2584 cutOffParsing(); 2585 return ExprError(); 2586 } 2587 2588 // Parse objc-selector 2589 SourceLocation Loc; 2590 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); 2591 2592 SmallVector<IdentifierInfo *, 12> KeyIdents; 2593 SmallVector<SourceLocation, 12> KeyLocs; 2594 ExprVector KeyExprs; 2595 2596 if (Tok.is(tok::colon)) { 2597 while (1) { 2598 // Each iteration parses a single keyword argument. 2599 KeyIdents.push_back(selIdent); 2600 KeyLocs.push_back(Loc); 2601 2602 if (ExpectAndConsume(tok::colon)) { 2603 // We must manually skip to a ']', otherwise the expression skipper will 2604 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2605 // the enclosing expression. 2606 SkipUntil(tok::r_square, StopAtSemi); 2607 return ExprError(); 2608 } 2609 2610 /// Parse the expression after ':' 2611 2612 if (Tok.is(tok::code_completion)) { 2613 if (SuperLoc.isValid()) 2614 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2615 KeyIdents, 2616 /*AtArgumentEpression=*/true); 2617 else if (ReceiverType) 2618 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2619 KeyIdents, 2620 /*AtArgumentEpression=*/true); 2621 else 2622 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2623 KeyIdents, 2624 /*AtArgumentEpression=*/true); 2625 2626 cutOffParsing(); 2627 return ExprError(); 2628 } 2629 2630 ExprResult Expr; 2631 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 2632 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2633 Expr = ParseBraceInitializer(); 2634 } else 2635 Expr = ParseAssignmentExpression(); 2636 2637 ExprResult Res(Expr); 2638 if (Res.isInvalid()) { 2639 // We must manually skip to a ']', otherwise the expression skipper will 2640 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2641 // the enclosing expression. 2642 SkipUntil(tok::r_square, StopAtSemi); 2643 return Res; 2644 } 2645 2646 // We have a valid expression. 2647 KeyExprs.push_back(Res.get()); 2648 2649 // Code completion after each argument. 2650 if (Tok.is(tok::code_completion)) { 2651 if (SuperLoc.isValid()) 2652 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 2653 KeyIdents, 2654 /*AtArgumentEpression=*/false); 2655 else if (ReceiverType) 2656 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 2657 KeyIdents, 2658 /*AtArgumentEpression=*/false); 2659 else 2660 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, 2661 KeyIdents, 2662 /*AtArgumentEpression=*/false); 2663 cutOffParsing(); 2664 return ExprError(); 2665 } 2666 2667 // Check for another keyword selector. 2668 selIdent = ParseObjCSelectorPiece(Loc); 2669 if (!selIdent && Tok.isNot(tok::colon)) 2670 break; 2671 // We have a selector or a colon, continue parsing. 2672 } 2673 // Parse the, optional, argument list, comma separated. 2674 while (Tok.is(tok::comma)) { 2675 SourceLocation commaLoc = ConsumeToken(); // Eat the ','. 2676 /// Parse the expression after ',' 2677 ExprResult Res(ParseAssignmentExpression()); 2678 if (Tok.is(tok::colon)) 2679 Res = Actions.CorrectDelayedTyposInExpr(Res); 2680 if (Res.isInvalid()) { 2681 if (Tok.is(tok::colon)) { 2682 Diag(commaLoc, diag::note_extra_comma_message_arg) << 2683 FixItHint::CreateRemoval(commaLoc); 2684 } 2685 // We must manually skip to a ']', otherwise the expression skipper will 2686 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2687 // the enclosing expression. 2688 SkipUntil(tok::r_square, StopAtSemi); 2689 return Res; 2690 } 2691 2692 // We have a valid expression. 2693 KeyExprs.push_back(Res.get()); 2694 } 2695 } else if (!selIdent) { 2696 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name. 2697 2698 // We must manually skip to a ']', otherwise the expression skipper will 2699 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2700 // the enclosing expression. 2701 SkipUntil(tok::r_square, StopAtSemi); 2702 return ExprError(); 2703 } 2704 2705 if (Tok.isNot(tok::r_square)) { 2706 Diag(Tok, diag::err_expected) 2707 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square); 2708 // We must manually skip to a ']', otherwise the expression skipper will 2709 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2710 // the enclosing expression. 2711 SkipUntil(tok::r_square, StopAtSemi); 2712 return ExprError(); 2713 } 2714 2715 SourceLocation RBracLoc = ConsumeBracket(); // consume ']' 2716 2717 unsigned nKeys = KeyIdents.size(); 2718 if (nKeys == 0) { 2719 KeyIdents.push_back(selIdent); 2720 KeyLocs.push_back(Loc); 2721 } 2722 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]); 2723 2724 if (SuperLoc.isValid()) 2725 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel, 2726 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 2727 else if (ReceiverType) 2728 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel, 2729 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 2730 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel, 2731 LBracLoc, KeyLocs, RBracLoc, KeyExprs); 2732 } 2733 2734 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { 2735 ExprResult Res(ParseStringLiteralExpression()); 2736 if (Res.isInvalid()) return Res; 2737 2738 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string 2739 // expressions. At this point, we know that the only valid thing that starts 2740 // with '@' is an @"". 2741 SmallVector<SourceLocation, 4> AtLocs; 2742 ExprVector AtStrings; 2743 AtLocs.push_back(AtLoc); 2744 AtStrings.push_back(Res.get()); 2745 2746 while (Tok.is(tok::at)) { 2747 AtLocs.push_back(ConsumeToken()); // eat the @. 2748 2749 // Invalid unless there is a string literal. 2750 if (!isTokenStringLiteral()) 2751 return ExprError(Diag(Tok, diag::err_objc_concat_string)); 2752 2753 ExprResult Lit(ParseStringLiteralExpression()); 2754 if (Lit.isInvalid()) 2755 return Lit; 2756 2757 AtStrings.push_back(Lit.get()); 2758 } 2759 2760 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(), 2761 AtStrings.size()); 2762 } 2763 2764 /// ParseObjCBooleanLiteral - 2765 /// objc-scalar-literal : '@' boolean-keyword 2766 /// ; 2767 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no' 2768 /// ; 2769 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, 2770 bool ArgValue) { 2771 SourceLocation EndLoc = ConsumeToken(); // consume the keyword. 2772 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue); 2773 } 2774 2775 /// ParseObjCCharacterLiteral - 2776 /// objc-scalar-literal : '@' character-literal 2777 /// ; 2778 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) { 2779 ExprResult Lit(Actions.ActOnCharacterConstant(Tok)); 2780 if (Lit.isInvalid()) { 2781 return Lit; 2782 } 2783 ConsumeToken(); // Consume the literal token. 2784 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()); 2785 } 2786 2787 /// ParseObjCNumericLiteral - 2788 /// objc-scalar-literal : '@' scalar-literal 2789 /// ; 2790 /// scalar-literal : | numeric-constant /* any numeric constant. */ 2791 /// ; 2792 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) { 2793 ExprResult Lit(Actions.ActOnNumericConstant(Tok)); 2794 if (Lit.isInvalid()) { 2795 return Lit; 2796 } 2797 ConsumeToken(); // Consume the literal token. 2798 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()); 2799 } 2800 2801 /// ParseObjCBoxedExpr - 2802 /// objc-box-expression: 2803 /// @( assignment-expression ) 2804 ExprResult 2805 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) { 2806 if (Tok.isNot(tok::l_paren)) 2807 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@"); 2808 2809 BalancedDelimiterTracker T(*this, tok::l_paren); 2810 T.consumeOpen(); 2811 ExprResult ValueExpr(ParseAssignmentExpression()); 2812 if (T.consumeClose()) 2813 return ExprError(); 2814 2815 if (ValueExpr.isInvalid()) 2816 return ExprError(); 2817 2818 // Wrap the sub-expression in a parenthesized expression, to distinguish 2819 // a boxed expression from a literal. 2820 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation(); 2821 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get()); 2822 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc), 2823 ValueExpr.get()); 2824 } 2825 2826 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) { 2827 ExprVector ElementExprs; // array elements. 2828 ConsumeBracket(); // consume the l_square. 2829 2830 while (Tok.isNot(tok::r_square)) { 2831 // Parse list of array element expressions (all must be id types). 2832 ExprResult Res(ParseAssignmentExpression()); 2833 if (Res.isInvalid()) { 2834 // We must manually skip to a ']', otherwise the expression skipper will 2835 // stop at the ']' when it skips to the ';'. We want it to skip beyond 2836 // the enclosing expression. 2837 SkipUntil(tok::r_square, StopAtSemi); 2838 return Res; 2839 } 2840 2841 // Parse the ellipsis that indicates a pack expansion. 2842 if (Tok.is(tok::ellipsis)) 2843 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); 2844 if (Res.isInvalid()) 2845 return true; 2846 2847 ElementExprs.push_back(Res.get()); 2848 2849 if (Tok.is(tok::comma)) 2850 ConsumeToken(); // Eat the ','. 2851 else if (Tok.isNot(tok::r_square)) 2852 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square 2853 << tok::comma); 2854 } 2855 SourceLocation EndLoc = ConsumeBracket(); // location of ']' 2856 MultiExprArg Args(ElementExprs); 2857 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args); 2858 } 2859 2860 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { 2861 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements. 2862 ConsumeBrace(); // consume the l_square. 2863 while (Tok.isNot(tok::r_brace)) { 2864 // Parse the comma separated key : value expressions. 2865 ExprResult KeyExpr; 2866 { 2867 ColonProtectionRAIIObject X(*this); 2868 KeyExpr = ParseAssignmentExpression(); 2869 if (KeyExpr.isInvalid()) { 2870 // We must manually skip to a '}', otherwise the expression skipper will 2871 // stop at the '}' when it skips to the ';'. We want it to skip beyond 2872 // the enclosing expression. 2873 SkipUntil(tok::r_brace, StopAtSemi); 2874 return KeyExpr; 2875 } 2876 } 2877 2878 if (ExpectAndConsume(tok::colon)) { 2879 SkipUntil(tok::r_brace, StopAtSemi); 2880 return ExprError(); 2881 } 2882 2883 ExprResult ValueExpr(ParseAssignmentExpression()); 2884 if (ValueExpr.isInvalid()) { 2885 // We must manually skip to a '}', otherwise the expression skipper will 2886 // stop at the '}' when it skips to the ';'. We want it to skip beyond 2887 // the enclosing expression. 2888 SkipUntil(tok::r_brace, StopAtSemi); 2889 return ValueExpr; 2890 } 2891 2892 // Parse the ellipsis that designates this as a pack expansion. 2893 SourceLocation EllipsisLoc; 2894 if (getLangOpts().CPlusPlus) 2895 TryConsumeToken(tok::ellipsis, EllipsisLoc); 2896 2897 // We have a valid expression. Collect it in a vector so we can 2898 // build the argument list. 2899 ObjCDictionaryElement Element = { 2900 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None 2901 }; 2902 Elements.push_back(Element); 2903 2904 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace)) 2905 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace 2906 << tok::comma); 2907 } 2908 SourceLocation EndLoc = ConsumeBrace(); 2909 2910 // Create the ObjCDictionaryLiteral. 2911 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc), 2912 Elements.data(), Elements.size()); 2913 } 2914 2915 /// objc-encode-expression: 2916 /// \@encode ( type-name ) 2917 ExprResult 2918 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) { 2919 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!"); 2920 2921 SourceLocation EncLoc = ConsumeToken(); 2922 2923 if (Tok.isNot(tok::l_paren)) 2924 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode"); 2925 2926 BalancedDelimiterTracker T(*this, tok::l_paren); 2927 T.consumeOpen(); 2928 2929 TypeResult Ty = ParseTypeName(); 2930 2931 T.consumeClose(); 2932 2933 if (Ty.isInvalid()) 2934 return ExprError(); 2935 2936 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(), 2937 Ty.get(), T.getCloseLocation()); 2938 } 2939 2940 /// objc-protocol-expression 2941 /// \@protocol ( protocol-name ) 2942 ExprResult 2943 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) { 2944 SourceLocation ProtoLoc = ConsumeToken(); 2945 2946 if (Tok.isNot(tok::l_paren)) 2947 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol"); 2948 2949 BalancedDelimiterTracker T(*this, tok::l_paren); 2950 T.consumeOpen(); 2951 2952 if (Tok.isNot(tok::identifier)) 2953 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); 2954 2955 IdentifierInfo *protocolId = Tok.getIdentifierInfo(); 2956 SourceLocation ProtoIdLoc = ConsumeToken(); 2957 2958 T.consumeClose(); 2959 2960 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc, 2961 T.getOpenLocation(), ProtoIdLoc, 2962 T.getCloseLocation()); 2963 } 2964 2965 /// objc-selector-expression 2966 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')' 2967 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { 2968 SourceLocation SelectorLoc = ConsumeToken(); 2969 2970 if (Tok.isNot(tok::l_paren)) 2971 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector"); 2972 2973 SmallVector<IdentifierInfo *, 12> KeyIdents; 2974 SourceLocation sLoc; 2975 2976 BalancedDelimiterTracker T(*this, tok::l_paren); 2977 T.consumeOpen(); 2978 bool HasOptionalParen = Tok.is(tok::l_paren); 2979 if (HasOptionalParen) 2980 ConsumeParen(); 2981 2982 if (Tok.is(tok::code_completion)) { 2983 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); 2984 cutOffParsing(); 2985 return ExprError(); 2986 } 2987 2988 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); 2989 if (!SelIdent && // missing selector name. 2990 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 2991 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); 2992 2993 KeyIdents.push_back(SelIdent); 2994 2995 unsigned nColons = 0; 2996 if (Tok.isNot(tok::r_paren)) { 2997 while (1) { 2998 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++. 2999 ++nColons; 3000 KeyIdents.push_back(nullptr); 3001 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'. 3002 return ExprError(); 3003 ++nColons; 3004 3005 if (Tok.is(tok::r_paren)) 3006 break; 3007 3008 if (Tok.is(tok::code_completion)) { 3009 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); 3010 cutOffParsing(); 3011 return ExprError(); 3012 } 3013 3014 // Check for another keyword selector. 3015 SourceLocation Loc; 3016 SelIdent = ParseObjCSelectorPiece(Loc); 3017 KeyIdents.push_back(SelIdent); 3018 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) 3019 break; 3020 } 3021 } 3022 if (HasOptionalParen && Tok.is(tok::r_paren)) 3023 ConsumeParen(); // ')' 3024 T.consumeClose(); 3025 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]); 3026 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc, 3027 T.getOpenLocation(), 3028 T.getCloseLocation(), 3029 !HasOptionalParen); 3030 } 3031 3032 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { 3033 // MCDecl might be null due to error in method or c-function prototype, etc. 3034 Decl *MCDecl = LM.D; 3035 bool skip = MCDecl && 3036 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) || 3037 (!parseMethod && Actions.isObjCMethodDecl(MCDecl))); 3038 if (skip) 3039 return; 3040 3041 // Save the current token position. 3042 SourceLocation OrigLoc = Tok.getLocation(); 3043 3044 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!"); 3045 // Append the current token at the end of the new token stream so that it 3046 // doesn't get lost. 3047 LM.Toks.push_back(Tok); 3048 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false); 3049 3050 // Consume the previously pushed token. 3051 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 3052 3053 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && 3054 "Inline objective-c method not starting with '{' or 'try' or ':'"); 3055 // Enter a scope for the method or c-function body. 3056 ParseScope BodyScope(this, 3057 parseMethod 3058 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope 3059 : Scope::FnScope|Scope::DeclScope); 3060 3061 // Tell the actions module that we have entered a method or c-function definition 3062 // with the specified Declarator for the method/function. 3063 if (parseMethod) 3064 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl); 3065 else 3066 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl); 3067 if (Tok.is(tok::kw_try)) 3068 ParseFunctionTryBlock(MCDecl, BodyScope); 3069 else { 3070 if (Tok.is(tok::colon)) 3071 ParseConstructorInitializer(MCDecl); 3072 ParseFunctionStatementBody(MCDecl, BodyScope); 3073 } 3074 3075 if (Tok.getLocation() != OrigLoc) { 3076 // Due to parsing error, we either went over the cached tokens or 3077 // there are still cached tokens left. If it's the latter case skip the 3078 // leftover tokens. 3079 // Since this is an uncommon situation that should be avoided, use the 3080 // expensive isBeforeInTranslationUnit call. 3081 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 3082 OrigLoc)) 3083 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof)) 3084 ConsumeAnyToken(); 3085 } 3086 3087 return; 3088 } 3089