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