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