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