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