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