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