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