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