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