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