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