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