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