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