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