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