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