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