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