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