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