xref: /llvm-project/clang/lib/Parse/ParseObjc.cpp (revision 66e3877b42fea73fde704c45ad340b13516b7e84)
1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the Objective-C portions of the Parser interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/DeclSpec.h"
16 #include "clang/Parse/Scope.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "llvm/ADT/SmallVector.h"
19 using namespace clang;
20 
21 
22 /// ParseExternalDeclaration:
23 ///       external-declaration: [C99 6.9]
24 /// [OBJC]  objc-class-definition
25 /// [OBJC]  objc-class-declaration
26 /// [OBJC]  objc-alias-declaration
27 /// [OBJC]  objc-protocol-definition
28 /// [OBJC]  objc-method-definition
29 /// [OBJC]  '@' 'end'
30 Parser::DeclTy *Parser::ParseObjCAtDirectives() {
31   SourceLocation AtLoc = ConsumeToken(); // the "@"
32 
33   switch (Tok.getObjCKeywordID()) {
34   case tok::objc_class:
35     return ParseObjCAtClassDeclaration(AtLoc);
36   case tok::objc_interface:
37     return ParseObjCAtInterfaceDeclaration(AtLoc);
38   case tok::objc_protocol:
39     return ParseObjCAtProtocolDeclaration(AtLoc);
40   case tok::objc_implementation:
41     return ParseObjCAtImplementationDeclaration(AtLoc);
42   case tok::objc_end:
43     return ParseObjCAtEndDeclaration(AtLoc);
44   case tok::objc_compatibility_alias:
45     return ParseObjCAtAliasDeclaration(AtLoc);
46   case tok::objc_synthesize:
47     return ParseObjCPropertySynthesize(AtLoc);
48   case tok::objc_dynamic:
49     return ParseObjCPropertyDynamic(AtLoc);
50   default:
51     Diag(AtLoc, diag::err_unexpected_at);
52     SkipUntil(tok::semi);
53     return 0;
54   }
55 }
56 
57 ///
58 /// objc-class-declaration:
59 ///    '@' 'class' identifier-list ';'
60 ///
61 Parser::DeclTy *Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
62   ConsumeToken(); // the identifier "class"
63   llvm::SmallVector<IdentifierInfo *, 8> ClassNames;
64 
65   while (1) {
66     if (Tok.isNot(tok::identifier)) {
67       Diag(Tok, diag::err_expected_ident);
68       SkipUntil(tok::semi);
69       return 0;
70     }
71     ClassNames.push_back(Tok.getIdentifierInfo());
72     ConsumeToken();
73 
74     if (Tok.isNot(tok::comma))
75       break;
76 
77     ConsumeToken();
78   }
79 
80   // Consume the ';'.
81   if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
82     return 0;
83 
84   return Actions.ActOnForwardClassDeclaration(atLoc,
85                                       &ClassNames[0], ClassNames.size());
86 }
87 
88 ///
89 ///   objc-interface:
90 ///     objc-class-interface-attributes[opt] objc-class-interface
91 ///     objc-category-interface
92 ///
93 ///   objc-class-interface:
94 ///     '@' 'interface' identifier objc-superclass[opt]
95 ///       objc-protocol-refs[opt]
96 ///       objc-class-instance-variables[opt]
97 ///       objc-interface-decl-list
98 ///     @end
99 ///
100 ///   objc-category-interface:
101 ///     '@' 'interface' identifier '(' identifier[opt] ')'
102 ///       objc-protocol-refs[opt]
103 ///       objc-interface-decl-list
104 ///     @end
105 ///
106 ///   objc-superclass:
107 ///     ':' identifier
108 ///
109 ///   objc-class-interface-attributes:
110 ///     __attribute__((visibility("default")))
111 ///     __attribute__((visibility("hidden")))
112 ///     __attribute__((deprecated))
113 ///     __attribute__((unavailable))
114 ///     __attribute__((objc_exception)) - used by NSException on 64-bit
115 ///
116 Parser::DeclTy *Parser::ParseObjCAtInterfaceDeclaration(
117   SourceLocation atLoc, AttributeList *attrList) {
118   assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
119          "ParseObjCAtInterfaceDeclaration(): Expected @interface");
120   ConsumeToken(); // the "interface" identifier
121 
122   if (Tok.isNot(tok::identifier)) {
123     Diag(Tok, diag::err_expected_ident); // missing class or category name.
124     return 0;
125   }
126   // We have a class or category name - consume it.
127   IdentifierInfo *nameId = Tok.getIdentifierInfo();
128   SourceLocation nameLoc = ConsumeToken();
129 
130   if (Tok.is(tok::l_paren)) { // we have a category.
131     SourceLocation lparenLoc = ConsumeParen();
132     SourceLocation categoryLoc, rparenLoc;
133     IdentifierInfo *categoryId = 0;
134 
135     // For ObjC2, the category name is optional (not an error).
136     if (Tok.is(tok::identifier)) {
137       categoryId = Tok.getIdentifierInfo();
138       categoryLoc = ConsumeToken();
139     } else if (!getLang().ObjC2) {
140       Diag(Tok, diag::err_expected_ident); // missing category name.
141       return 0;
142     }
143     if (Tok.isNot(tok::r_paren)) {
144       Diag(Tok, diag::err_expected_rparen);
145       SkipUntil(tok::r_paren, false); // don't stop at ';'
146       return 0;
147     }
148     rparenLoc = ConsumeParen();
149 
150     // Next, we need to check for any protocol references.
151     SourceLocation EndProtoLoc;
152     llvm::SmallVector<DeclTy *, 8> ProtocolRefs;
153     if (Tok.is(tok::less) &&
154         ParseObjCProtocolReferences(ProtocolRefs, true, EndProtoLoc))
155       return 0;
156 
157     if (attrList) // categories don't support attributes.
158       Diag(Tok, diag::err_objc_no_attributes_on_category);
159 
160     DeclTy *CategoryType = Actions.ActOnStartCategoryInterface(atLoc,
161                                      nameId, nameLoc, categoryId, categoryLoc,
162                                      &ProtocolRefs[0], ProtocolRefs.size(),
163                                      EndProtoLoc);
164 
165     ParseObjCInterfaceDeclList(CategoryType, tok::objc_not_keyword);
166     return CategoryType;
167   }
168   // Parse a class interface.
169   IdentifierInfo *superClassId = 0;
170   SourceLocation superClassLoc;
171 
172   if (Tok.is(tok::colon)) { // a super class is specified.
173     ConsumeToken();
174     if (Tok.isNot(tok::identifier)) {
175       Diag(Tok, diag::err_expected_ident); // missing super class name.
176       return 0;
177     }
178     superClassId = Tok.getIdentifierInfo();
179     superClassLoc = ConsumeToken();
180   }
181   // Next, we need to check for any protocol references.
182   llvm::SmallVector<Action::DeclTy*, 8> ProtocolRefs;
183   SourceLocation EndProtoLoc;
184   if (Tok.is(tok::less) &&
185       ParseObjCProtocolReferences(ProtocolRefs, true, EndProtoLoc))
186     return 0;
187 
188   DeclTy *ClsType =
189     Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc,
190                                      superClassId, superClassLoc,
191                                      &ProtocolRefs[0], ProtocolRefs.size(),
192                                      EndProtoLoc, attrList);
193 
194   if (Tok.is(tok::l_brace))
195     ParseObjCClassInstanceVariables(ClsType, atLoc);
196 
197   ParseObjCInterfaceDeclList(ClsType, tok::objc_interface);
198   return ClsType;
199 }
200 
201 /// constructSetterName - Return the setter name for the given
202 /// identifier, i.e. "set" + Name where the initial character of Name
203 /// has been capitalized.
204 static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
205                                            const IdentifierInfo *Name) {
206   llvm::SmallString<100> SelectorName;
207   SelectorName += "set";
208   SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
209   SelectorName[3] = toupper(SelectorName[3]);
210   return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
211 }
212 
213 ///   objc-interface-decl-list:
214 ///     empty
215 ///     objc-interface-decl-list objc-property-decl [OBJC2]
216 ///     objc-interface-decl-list objc-method-requirement [OBJC2]
217 ///     objc-interface-decl-list objc-method-proto ';'
218 ///     objc-interface-decl-list declaration
219 ///     objc-interface-decl-list ';'
220 ///
221 ///   objc-method-requirement: [OBJC2]
222 ///     @required
223 ///     @optional
224 ///
225 void Parser::ParseObjCInterfaceDeclList(DeclTy *interfaceDecl,
226                                         tok::ObjCKeywordKind contextKey) {
227   llvm::SmallVector<DeclTy*, 32> allMethods;
228   llvm::SmallVector<DeclTy*, 16> allProperties;
229   tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
230 
231   SourceLocation AtEndLoc;
232 
233   while (1) {
234     // If this is a method prototype, parse it.
235     if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
236       DeclTy *methodPrototype =
237         ParseObjCMethodPrototype(interfaceDecl, MethodImplKind);
238       allMethods.push_back(methodPrototype);
239       // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
240       // method definitions.
241       ExpectAndConsume(tok::semi, diag::err_expected_semi_after,"method proto");
242       continue;
243     }
244 
245     // Ignore excess semicolons.
246     if (Tok.is(tok::semi)) {
247       ConsumeToken();
248       continue;
249     }
250 
251     // If we got to the end of the file, exit the loop.
252     if (Tok.is(tok::eof))
253       break;
254 
255     // If we don't have an @ directive, parse it as a function definition.
256     if (Tok.isNot(tok::at)) {
257       // FIXME: as the name implies, this rule allows function definitions.
258       // We could pass a flag or check for functions during semantic analysis.
259       ParseDeclarationOrFunctionDefinition();
260       continue;
261     }
262 
263     // Otherwise, we have an @ directive, eat the @.
264     SourceLocation AtLoc = ConsumeToken(); // the "@"
265     tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
266 
267     if (DirectiveKind == tok::objc_end) { // @end -> terminate list
268       AtEndLoc = AtLoc;
269       break;
270     }
271 
272     // Eat the identifier.
273     ConsumeToken();
274 
275     switch (DirectiveKind) {
276     default:
277       // FIXME: If someone forgets an @end on a protocol, this loop will
278       // continue to eat up tons of stuff and spew lots of nonsense errors.  It
279       // would probably be better to bail out if we saw an @class or @interface
280       // or something like that.
281       Diag(AtLoc, diag::err_objc_illegal_interface_qual);
282       // Skip until we see an '@' or '}' or ';'.
283       SkipUntil(tok::r_brace, tok::at);
284       break;
285 
286     case tok::objc_required:
287     case tok::objc_optional:
288       // This is only valid on protocols.
289       // FIXME: Should this check for ObjC2 being enabled?
290       if (contextKey != tok::objc_protocol)
291         Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
292       else
293         MethodImplKind = DirectiveKind;
294       break;
295 
296     case tok::objc_property:
297       if (!getLang().ObjC2)
298         Diag(AtLoc, diag::err_objc_propertoes_require_objc2);
299 
300       ObjCDeclSpec OCDS;
301       // Parse property attribute list, if any.
302       if (Tok.is(tok::l_paren))
303         ParseObjCPropertyAttribute(OCDS);
304 
305       // Parse all the comma separated declarators.
306       DeclSpec DS;
307       llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
308       ParseStructDeclaration(DS, FieldDeclarators);
309 
310       ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list, "",
311                        tok::at);
312 
313       // Convert them all to property declarations.
314       for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
315         FieldDeclarator &FD = FieldDeclarators[i];
316         if (FD.D.getIdentifier() == 0) {
317           Diag(AtLoc, diag::err_objc_property_requires_field_name)
318             << FD.D.getSourceRange();
319           continue;
320         }
321 
322         // Install the property declarator into interfaceDecl.
323         IdentifierInfo *SelName =
324           OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
325 
326         Selector GetterSel =
327           PP.getSelectorTable().getNullarySelector(SelName);
328         IdentifierInfo *SetterName = OCDS.getSetterName();
329         if (!SetterName)
330           SetterName = constructSetterName(PP.getIdentifierTable(),
331                                            FD.D.getIdentifier());
332         Selector SetterSel =
333           PP.getSelectorTable().getUnarySelector(SetterName);
334         DeclTy *Property = Actions.ActOnProperty(CurScope, AtLoc, FD, OCDS,
335                                                  GetterSel, SetterSel,
336                                                  MethodImplKind);
337         allProperties.push_back(Property);
338       }
339       break;
340     }
341   }
342 
343   // We break out of the big loop in two cases: when we see @end or when we see
344   // EOF.  In the former case, eat the @end.  In the later case, emit an error.
345   if (Tok.isObjCAtKeyword(tok::objc_end))
346     ConsumeToken(); // the "end" identifier
347   else
348     Diag(Tok, diag::err_objc_missing_end);
349 
350   // Insert collected methods declarations into the @interface object.
351   // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
352   Actions.ActOnAtEnd(AtEndLoc, interfaceDecl,
353                      allMethods.empty() ? 0 : &allMethods[0],
354                      allMethods.size(),
355                      allProperties.empty() ? 0 : &allProperties[0],
356                      allProperties.size());
357 }
358 
359 ///   Parse property attribute declarations.
360 ///
361 ///   property-attr-decl: '(' property-attrlist ')'
362 ///   property-attrlist:
363 ///     property-attribute
364 ///     property-attrlist ',' property-attribute
365 ///   property-attribute:
366 ///     getter '=' identifier
367 ///     setter '=' identifier ':'
368 ///     readonly
369 ///     readwrite
370 ///     assign
371 ///     retain
372 ///     copy
373 ///     nonatomic
374 ///
375 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
376   assert(Tok.getKind() == tok::l_paren);
377   SourceLocation LHSLoc = ConsumeParen(); // consume '('
378 
379   while (1) {
380     const IdentifierInfo *II = Tok.getIdentifierInfo();
381 
382     // If this is not an identifier at all, bail out early.
383     if (II == 0) {
384       MatchRHSPunctuation(tok::r_paren, LHSLoc);
385       return;
386     }
387 
388     SourceLocation AttrName = ConsumeToken(); // consume last attribute name
389 
390     if (!strcmp(II->getName(), "readonly"))
391       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
392     else if (!strcmp(II->getName(), "assign"))
393       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
394     else if (!strcmp(II->getName(), "readwrite"))
395       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
396     else if (!strcmp(II->getName(), "retain"))
397       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
398     else if (!strcmp(II->getName(), "copy"))
399       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
400     else if (!strcmp(II->getName(), "nonatomic"))
401       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
402     else if (!strcmp(II->getName(), "getter") ||
403              !strcmp(II->getName(), "setter")) {
404       // getter/setter require extra treatment.
405       if (ExpectAndConsume(tok::equal, diag::err_objc_expected_equal, "",
406                            tok::r_paren))
407         return;
408 
409       if (Tok.isNot(tok::identifier)) {
410         Diag(Tok, diag::err_expected_ident);
411         SkipUntil(tok::r_paren);
412         return;
413       }
414 
415       if (II->getName()[0] == 's') {
416         DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
417         DS.setSetterName(Tok.getIdentifierInfo());
418         ConsumeToken();  // consume method name
419 
420         if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "",
421                              tok::r_paren))
422           return;
423       } else {
424         DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
425         DS.setGetterName(Tok.getIdentifierInfo());
426         ConsumeToken();  // consume method name
427       }
428     } else {
429       Diag(AttrName, diag::err_objc_expected_property_attr) << II->getName();
430       SkipUntil(tok::r_paren);
431       return;
432     }
433 
434     if (Tok.isNot(tok::comma))
435       break;
436 
437     ConsumeToken();
438   }
439 
440   MatchRHSPunctuation(tok::r_paren, LHSLoc);
441 }
442 
443 ///   objc-method-proto:
444 ///     objc-instance-method objc-method-decl objc-method-attributes[opt]
445 ///     objc-class-method objc-method-decl objc-method-attributes[opt]
446 ///
447 ///   objc-instance-method: '-'
448 ///   objc-class-method: '+'
449 ///
450 ///   objc-method-attributes:         [OBJC2]
451 ///     __attribute__((deprecated))
452 ///
453 Parser::DeclTy *Parser::ParseObjCMethodPrototype(DeclTy *IDecl,
454                           tok::ObjCKeywordKind MethodImplKind) {
455   assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
456 
457   tok::TokenKind methodType = Tok.getKind();
458   SourceLocation mLoc = ConsumeToken();
459 
460   DeclTy *MDecl = ParseObjCMethodDecl(mLoc, methodType, IDecl, MethodImplKind);
461   // Since this rule is used for both method declarations and definitions,
462   // the caller is (optionally) responsible for consuming the ';'.
463   return MDecl;
464 }
465 
466 ///   objc-selector:
467 ///     identifier
468 ///     one of
469 ///       enum struct union if else while do for switch case default
470 ///       break continue return goto asm sizeof typeof __alignof
471 ///       unsigned long const short volatile signed restrict _Complex
472 ///       in out inout bycopy byref oneway int char float double void _Bool
473 ///
474 IdentifierInfo *Parser::ParseObjCSelector(SourceLocation &SelectorLoc) {
475   switch (Tok.getKind()) {
476   default:
477     return 0;
478   case tok::identifier:
479   case tok::kw_asm:
480   case tok::kw_auto:
481   case tok::kw_bool:
482   case tok::kw_break:
483   case tok::kw_case:
484   case tok::kw_catch:
485   case tok::kw_char:
486   case tok::kw_class:
487   case tok::kw_const:
488   case tok::kw_const_cast:
489   case tok::kw_continue:
490   case tok::kw_default:
491   case tok::kw_delete:
492   case tok::kw_do:
493   case tok::kw_double:
494   case tok::kw_dynamic_cast:
495   case tok::kw_else:
496   case tok::kw_enum:
497   case tok::kw_explicit:
498   case tok::kw_export:
499   case tok::kw_extern:
500   case tok::kw_false:
501   case tok::kw_float:
502   case tok::kw_for:
503   case tok::kw_friend:
504   case tok::kw_goto:
505   case tok::kw_if:
506   case tok::kw_inline:
507   case tok::kw_int:
508   case tok::kw_long:
509   case tok::kw_mutable:
510   case tok::kw_namespace:
511   case tok::kw_new:
512   case tok::kw_operator:
513   case tok::kw_private:
514   case tok::kw_protected:
515   case tok::kw_public:
516   case tok::kw_register:
517   case tok::kw_reinterpret_cast:
518   case tok::kw_restrict:
519   case tok::kw_return:
520   case tok::kw_short:
521   case tok::kw_signed:
522   case tok::kw_sizeof:
523   case tok::kw_static:
524   case tok::kw_static_cast:
525   case tok::kw_struct:
526   case tok::kw_switch:
527   case tok::kw_template:
528   case tok::kw_this:
529   case tok::kw_throw:
530   case tok::kw_true:
531   case tok::kw_try:
532   case tok::kw_typedef:
533   case tok::kw_typeid:
534   case tok::kw_typename:
535   case tok::kw_typeof:
536   case tok::kw_union:
537   case tok::kw_unsigned:
538   case tok::kw_using:
539   case tok::kw_virtual:
540   case tok::kw_void:
541   case tok::kw_volatile:
542   case tok::kw_wchar_t:
543   case tok::kw_while:
544   case tok::kw__Bool:
545   case tok::kw__Complex:
546   case tok::kw___alignof:
547     IdentifierInfo *II = Tok.getIdentifierInfo();
548     SelectorLoc = ConsumeToken();
549     return II;
550   }
551 }
552 
553 ///  objc-for-collection-in: 'in'
554 ///
555 bool Parser::isTokIdentifier_in() const {
556   // FIXME: May have to do additional look-ahead to only allow for
557   // valid tokens following an 'in'; such as an identifier, unary operators,
558   // '[' etc.
559   return (getLang().ObjC2 && Tok.is(tok::identifier) &&
560           Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
561 }
562 
563 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
564 /// qualifier list and builds their bitmask representation in the input
565 /// argument.
566 ///
567 ///   objc-type-qualifiers:
568 ///     objc-type-qualifier
569 ///     objc-type-qualifiers objc-type-qualifier
570 ///
571 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS) {
572   while (1) {
573     if (Tok.isNot(tok::identifier))
574       return;
575 
576     const IdentifierInfo *II = Tok.getIdentifierInfo();
577     for (unsigned i = 0; i != objc_NumQuals; ++i) {
578       if (II != ObjCTypeQuals[i])
579         continue;
580 
581       ObjCDeclSpec::ObjCDeclQualifier Qual;
582       switch (i) {
583       default: assert(0 && "Unknown decl qualifier");
584       case objc_in:     Qual = ObjCDeclSpec::DQ_In; break;
585       case objc_out:    Qual = ObjCDeclSpec::DQ_Out; break;
586       case objc_inout:  Qual = ObjCDeclSpec::DQ_Inout; break;
587       case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
588       case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
589       case objc_byref:  Qual = ObjCDeclSpec::DQ_Byref; break;
590       }
591       DS.setObjCDeclQualifier(Qual);
592       ConsumeToken();
593       II = 0;
594       break;
595     }
596 
597     // If this wasn't a recognized qualifier, bail out.
598     if (II) return;
599   }
600 }
601 
602 ///   objc-type-name:
603 ///     '(' objc-type-qualifiers[opt] type-name ')'
604 ///     '(' objc-type-qualifiers[opt] ')'
605 ///
606 Parser::TypeTy *Parser::ParseObjCTypeName(ObjCDeclSpec &DS) {
607   assert(Tok.is(tok::l_paren) && "expected (");
608 
609   SourceLocation LParenLoc = ConsumeParen();
610   SourceLocation TypeStartLoc = Tok.getLocation();
611 
612   // Parse type qualifiers, in, inout, etc.
613   ParseObjCTypeQualifierList(DS);
614 
615   TypeTy *Ty = 0;
616   if (isTypeSpecifierQualifier())
617     Ty = ParseTypeName();
618 
619   if (Tok.is(tok::r_paren))
620     ConsumeParen();
621   else if (Tok.getLocation() == TypeStartLoc) {
622     // If we didn't eat any tokens, then this isn't a type.
623     Diag(Tok, diag::err_expected_type);
624     SkipUntil(tok::r_paren);
625   } else {
626     // Otherwise, we found *something*, but didn't get a ')' in the right
627     // place.  Emit an error then return what we have as the type.
628     MatchRHSPunctuation(tok::r_paren, LParenLoc);
629   }
630   return Ty;
631 }
632 
633 ///   objc-method-decl:
634 ///     objc-selector
635 ///     objc-keyword-selector objc-parmlist[opt]
636 ///     objc-type-name objc-selector
637 ///     objc-type-name objc-keyword-selector objc-parmlist[opt]
638 ///
639 ///   objc-keyword-selector:
640 ///     objc-keyword-decl
641 ///     objc-keyword-selector objc-keyword-decl
642 ///
643 ///   objc-keyword-decl:
644 ///     objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
645 ///     objc-selector ':' objc-keyword-attributes[opt] identifier
646 ///     ':' objc-type-name objc-keyword-attributes[opt] identifier
647 ///     ':' objc-keyword-attributes[opt] identifier
648 ///
649 ///   objc-parmlist:
650 ///     objc-parms objc-ellipsis[opt]
651 ///
652 ///   objc-parms:
653 ///     objc-parms , parameter-declaration
654 ///
655 ///   objc-ellipsis:
656 ///     , ...
657 ///
658 ///   objc-keyword-attributes:         [OBJC2]
659 ///     __attribute__((unused))
660 ///
661 Parser::DeclTy *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
662                                             tok::TokenKind mType,
663                                             DeclTy *IDecl,
664                                             tok::ObjCKeywordKind MethodImplKind)
665 {
666   // Parse the return type if present.
667   TypeTy *ReturnType = 0;
668   ObjCDeclSpec DSRet;
669   if (Tok.is(tok::l_paren))
670     ReturnType = ParseObjCTypeName(DSRet);
671 
672   SourceLocation selLoc;
673   IdentifierInfo *SelIdent = ParseObjCSelector(selLoc);
674 
675   if (!SelIdent) { // missing selector name.
676     Diag(Tok, diag::err_expected_selector_for_method)
677       << SourceRange(mLoc, Tok.getLocation());
678     // Skip until we get a ; or {}.
679     SkipUntil(tok::r_brace);
680     return 0;
681   }
682 
683   if (Tok.isNot(tok::colon)) {
684     // If attributes exist after the method, parse them.
685     AttributeList *MethodAttrs = 0;
686     if (getLang().ObjC2 && Tok.is(tok::kw___attribute))
687       MethodAttrs = ParseAttributes();
688 
689     Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
690     return Actions.ActOnMethodDeclaration(mLoc, Tok.getLocation(),
691                                           mType, IDecl, DSRet, ReturnType, Sel,
692                                           0, 0, 0, MethodAttrs, MethodImplKind);
693   }
694 
695   llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
696   llvm::SmallVector<Action::TypeTy *, 12> KeyTypes;
697   llvm::SmallVector<ObjCDeclSpec, 12> ArgTypeQuals;
698   llvm::SmallVector<IdentifierInfo *, 12> ArgNames;
699 
700   Action::TypeTy *TypeInfo;
701   while (1) {
702     KeyIdents.push_back(SelIdent);
703 
704     // Each iteration parses a single keyword argument.
705     if (Tok.isNot(tok::colon)) {
706       Diag(Tok, diag::err_expected_colon);
707       break;
708     }
709     ConsumeToken(); // Eat the ':'.
710     ObjCDeclSpec DSType;
711     if (Tok.is(tok::l_paren)) // Parse the argument type.
712       TypeInfo = ParseObjCTypeName(DSType);
713     else
714       TypeInfo = 0;
715     KeyTypes.push_back(TypeInfo);
716     ArgTypeQuals.push_back(DSType);
717 
718     // If attributes exist before the argument name, parse them.
719     if (getLang().ObjC2 && Tok.is(tok::kw___attribute))
720       ParseAttributes(); // FIXME: pass attributes through.
721 
722     if (Tok.isNot(tok::identifier)) {
723       Diag(Tok, diag::err_expected_ident); // missing argument name.
724       break;
725     }
726     ArgNames.push_back(Tok.getIdentifierInfo());
727     ConsumeToken(); // Eat the identifier.
728 
729     // Check for another keyword selector.
730     SourceLocation Loc;
731     SelIdent = ParseObjCSelector(Loc);
732     if (!SelIdent && Tok.isNot(tok::colon))
733       break;
734     // We have a selector or a colon, continue parsing.
735   }
736 
737   bool isVariadic = false;
738 
739   // Parse the (optional) parameter list.
740   while (Tok.is(tok::comma)) {
741     ConsumeToken();
742     if (Tok.is(tok::ellipsis)) {
743       isVariadic = true;
744       ConsumeToken();
745       break;
746     }
747     // FIXME: implement this...
748     // Parse the c-style argument declaration-specifier.
749     DeclSpec DS;
750     ParseDeclarationSpecifiers(DS);
751     // Parse the declarator.
752     Declarator ParmDecl(DS, Declarator::PrototypeContext);
753     ParseDeclarator(ParmDecl);
754   }
755 
756   // FIXME: Add support for optional parmameter list...
757   // If attributes exist after the method, parse them.
758   AttributeList *MethodAttrs = 0;
759   if (getLang().ObjC2 && Tok.is(tok::kw___attribute))
760     MethodAttrs = ParseAttributes();
761 
762   Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
763                                                    &KeyIdents[0]);
764   return Actions.ActOnMethodDeclaration(mLoc, Tok.getLocation(),
765                                         mType, IDecl, DSRet, ReturnType, Sel,
766                                         &ArgTypeQuals[0], &KeyTypes[0],
767                                         &ArgNames[0], MethodAttrs,
768                                         MethodImplKind, isVariadic);
769 }
770 
771 ///   objc-protocol-refs:
772 ///     '<' identifier-list '>'
773 ///
774 bool Parser::
775 ParseObjCProtocolReferences(llvm::SmallVectorImpl<Action::DeclTy*> &Protocols,
776                             bool WarnOnDeclarations, SourceLocation &EndLoc) {
777   assert(Tok.is(tok::less) && "expected <");
778 
779   ConsumeToken(); // the "<"
780 
781   llvm::SmallVector<IdentifierLocPair, 8> ProtocolIdents;
782 
783   while (1) {
784     if (Tok.isNot(tok::identifier)) {
785       Diag(Tok, diag::err_expected_ident);
786       SkipUntil(tok::greater);
787       return true;
788     }
789     ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
790                                        Tok.getLocation()));
791     ConsumeToken();
792 
793     if (Tok.isNot(tok::comma))
794       break;
795     ConsumeToken();
796   }
797 
798   // Consume the '>'.
799   if (Tok.isNot(tok::greater)) {
800     Diag(Tok, diag::err_expected_greater);
801     return true;
802   }
803 
804   EndLoc = ConsumeAnyToken();
805 
806   // Convert the list of protocols identifiers into a list of protocol decls.
807   Actions.FindProtocolDeclaration(WarnOnDeclarations,
808                                   &ProtocolIdents[0], ProtocolIdents.size(),
809                                   Protocols);
810   return false;
811 }
812 
813 ///   objc-class-instance-variables:
814 ///     '{' objc-instance-variable-decl-list[opt] '}'
815 ///
816 ///   objc-instance-variable-decl-list:
817 ///     objc-visibility-spec
818 ///     objc-instance-variable-decl ';'
819 ///     ';'
820 ///     objc-instance-variable-decl-list objc-visibility-spec
821 ///     objc-instance-variable-decl-list objc-instance-variable-decl ';'
822 ///     objc-instance-variable-decl-list ';'
823 ///
824 ///   objc-visibility-spec:
825 ///     @private
826 ///     @protected
827 ///     @public
828 ///     @package [OBJC2]
829 ///
830 ///   objc-instance-variable-decl:
831 ///     struct-declaration
832 ///
833 void Parser::ParseObjCClassInstanceVariables(DeclTy *interfaceDecl,
834                                              SourceLocation atLoc) {
835   assert(Tok.is(tok::l_brace) && "expected {");
836   llvm::SmallVector<DeclTy*, 32> AllIvarDecls;
837   llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
838 
839   SourceLocation LBraceLoc = ConsumeBrace(); // the "{"
840 
841   tok::ObjCKeywordKind visibility = tok::objc_protected;
842   // While we still have something to read, read the instance variables.
843   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
844     // Each iteration of this loop reads one objc-instance-variable-decl.
845 
846     // Check for extraneous top-level semicolon.
847     if (Tok.is(tok::semi)) {
848       Diag(Tok, diag::ext_extra_struct_semi);
849       ConsumeToken();
850       continue;
851     }
852 
853     // Set the default visibility to private.
854     if (Tok.is(tok::at)) { // parse objc-visibility-spec
855       ConsumeToken(); // eat the @ sign
856       switch (Tok.getObjCKeywordID()) {
857       case tok::objc_private:
858       case tok::objc_public:
859       case tok::objc_protected:
860       case tok::objc_package:
861         visibility = Tok.getObjCKeywordID();
862         ConsumeToken();
863         continue;
864       default:
865         Diag(Tok, diag::err_objc_illegal_visibility_spec);
866         continue;
867       }
868     }
869 
870     // Parse all the comma separated declarators.
871     DeclSpec DS;
872     FieldDeclarators.clear();
873     ParseStructDeclaration(DS, FieldDeclarators);
874 
875     // Convert them all to fields.
876     for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
877       FieldDeclarator &FD = FieldDeclarators[i];
878       // Install the declarator into interfaceDecl.
879       DeclTy *Field = Actions.ActOnIvar(CurScope,
880                                          DS.getSourceRange().getBegin(),
881                                          FD.D, FD.BitfieldSize, visibility);
882       AllIvarDecls.push_back(Field);
883     }
884 
885     if (Tok.is(tok::semi)) {
886       ConsumeToken();
887     } else {
888       Diag(Tok, diag::err_expected_semi_decl_list);
889       // Skip to end of block or statement
890       SkipUntil(tok::r_brace, true, true);
891     }
892   }
893   SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
894   // Call ActOnFields() even if we don't have any decls. This is useful
895   // for code rewriting tools that need to be aware of the empty list.
896   Actions.ActOnFields(CurScope, atLoc, interfaceDecl,
897                       &AllIvarDecls[0], AllIvarDecls.size(),
898                       LBraceLoc, RBraceLoc, 0);
899   return;
900 }
901 
902 ///   objc-protocol-declaration:
903 ///     objc-protocol-definition
904 ///     objc-protocol-forward-reference
905 ///
906 ///   objc-protocol-definition:
907 ///     @protocol identifier
908 ///       objc-protocol-refs[opt]
909 ///       objc-interface-decl-list
910 ///     @end
911 ///
912 ///   objc-protocol-forward-reference:
913 ///     @protocol identifier-list ';'
914 ///
915 ///   "@protocol identifier ;" should be resolved as "@protocol
916 ///   identifier-list ;": objc-interface-decl-list may not start with a
917 ///   semicolon in the first alternative if objc-protocol-refs are omitted.
918 Parser::DeclTy *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
919                                                AttributeList *attrList) {
920   assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
921          "ParseObjCAtProtocolDeclaration(): Expected @protocol");
922   ConsumeToken(); // the "protocol" identifier
923 
924   if (Tok.isNot(tok::identifier)) {
925     Diag(Tok, diag::err_expected_ident); // missing protocol name.
926     return 0;
927   }
928   // Save the protocol name, then consume it.
929   IdentifierInfo *protocolName = Tok.getIdentifierInfo();
930   SourceLocation nameLoc = ConsumeToken();
931 
932   if (Tok.is(tok::semi)) { // forward declaration of one protocol.
933     IdentifierLocPair ProtoInfo(protocolName, nameLoc);
934     ConsumeToken();
935     return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1);
936   }
937 
938   if (Tok.is(tok::comma)) { // list of forward declarations.
939     llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs;
940     ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
941 
942     // Parse the list of forward declarations.
943     while (1) {
944       ConsumeToken(); // the ','
945       if (Tok.isNot(tok::identifier)) {
946         Diag(Tok, diag::err_expected_ident);
947         SkipUntil(tok::semi);
948         return 0;
949       }
950       ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
951                                                Tok.getLocation()));
952       ConsumeToken(); // the identifier
953 
954       if (Tok.isNot(tok::comma))
955         break;
956     }
957     // Consume the ';'.
958     if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
959       return 0;
960 
961     return Actions.ActOnForwardProtocolDeclaration(AtLoc,
962                                                    &ProtocolRefs[0],
963                                                    ProtocolRefs.size());
964   }
965 
966   // Last, and definitely not least, parse a protocol declaration.
967   SourceLocation EndProtoLoc;
968 
969   llvm::SmallVector<DeclTy *, 8> ProtocolRefs;
970   if (Tok.is(tok::less) &&
971       ParseObjCProtocolReferences(ProtocolRefs, true, EndProtoLoc))
972     return 0;
973 
974   DeclTy *ProtoType =
975     Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
976                                         &ProtocolRefs[0], ProtocolRefs.size(),
977                                         EndProtoLoc, attrList);
978   ParseObjCInterfaceDeclList(ProtoType, tok::objc_protocol);
979   return ProtoType;
980 }
981 
982 ///   objc-implementation:
983 ///     objc-class-implementation-prologue
984 ///     objc-category-implementation-prologue
985 ///
986 ///   objc-class-implementation-prologue:
987 ///     @implementation identifier objc-superclass[opt]
988 ///       objc-class-instance-variables[opt]
989 ///
990 ///   objc-category-implementation-prologue:
991 ///     @implementation identifier ( identifier )
992 
993 Parser::DeclTy *Parser::ParseObjCAtImplementationDeclaration(
994   SourceLocation atLoc) {
995   assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
996          "ParseObjCAtImplementationDeclaration(): Expected @implementation");
997   ConsumeToken(); // the "implementation" identifier
998 
999   if (Tok.isNot(tok::identifier)) {
1000     Diag(Tok, diag::err_expected_ident); // missing class or category name.
1001     return 0;
1002   }
1003   // We have a class or category name - consume it.
1004   IdentifierInfo *nameId = Tok.getIdentifierInfo();
1005   SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1006 
1007   if (Tok.is(tok::l_paren)) {
1008     // we have a category implementation.
1009     SourceLocation lparenLoc = ConsumeParen();
1010     SourceLocation categoryLoc, rparenLoc;
1011     IdentifierInfo *categoryId = 0;
1012 
1013     if (Tok.is(tok::identifier)) {
1014       categoryId = Tok.getIdentifierInfo();
1015       categoryLoc = ConsumeToken();
1016     } else {
1017       Diag(Tok, diag::err_expected_ident); // missing category name.
1018       return 0;
1019     }
1020     if (Tok.isNot(tok::r_paren)) {
1021       Diag(Tok, diag::err_expected_rparen);
1022       SkipUntil(tok::r_paren, false); // don't stop at ';'
1023       return 0;
1024     }
1025     rparenLoc = ConsumeParen();
1026     DeclTy *ImplCatType = Actions.ActOnStartCategoryImplementation(
1027                                     atLoc, nameId, nameLoc, categoryId,
1028                                     categoryLoc);
1029     ObjCImpDecl = ImplCatType;
1030     return 0;
1031   }
1032   // We have a class implementation
1033   SourceLocation superClassLoc;
1034   IdentifierInfo *superClassId = 0;
1035   if (Tok.is(tok::colon)) {
1036     // We have a super class
1037     ConsumeToken();
1038     if (Tok.isNot(tok::identifier)) {
1039       Diag(Tok, diag::err_expected_ident); // missing super class name.
1040       return 0;
1041     }
1042     superClassId = Tok.getIdentifierInfo();
1043     superClassLoc = ConsumeToken(); // Consume super class name
1044   }
1045   DeclTy *ImplClsType = Actions.ActOnStartClassImplementation(
1046                                   atLoc, nameId, nameLoc,
1047                                   superClassId, superClassLoc);
1048 
1049   if (Tok.is(tok::l_brace)) // we have ivars
1050     ParseObjCClassInstanceVariables(ImplClsType/*FIXME*/, atLoc);
1051   ObjCImpDecl = ImplClsType;
1052 
1053   return 0;
1054 }
1055 
1056 Parser::DeclTy *Parser::ParseObjCAtEndDeclaration(SourceLocation atLoc) {
1057   assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1058          "ParseObjCAtEndDeclaration(): Expected @end");
1059   ConsumeToken(); // the "end" identifier
1060   if (ObjCImpDecl)
1061     Actions.ActOnAtEnd(atLoc, ObjCImpDecl);
1062   else
1063     Diag(atLoc, diag::warn_expected_implementation); // missing @implementation
1064   return ObjCImpDecl;
1065 }
1066 
1067 ///   compatibility-alias-decl:
1068 ///     @compatibility_alias alias-name  class-name ';'
1069 ///
1070 Parser::DeclTy *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1071   assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1072          "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1073   ConsumeToken(); // consume compatibility_alias
1074   if (Tok.isNot(tok::identifier)) {
1075     Diag(Tok, diag::err_expected_ident);
1076     return 0;
1077   }
1078   IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1079   SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1080   if (Tok.isNot(tok::identifier)) {
1081     Diag(Tok, diag::err_expected_ident);
1082     return 0;
1083   }
1084   IdentifierInfo *classId = Tok.getIdentifierInfo();
1085   SourceLocation classLoc = ConsumeToken(); // consume class-name;
1086   if (Tok.isNot(tok::semi)) {
1087     Diag(Tok, diag::err_expected_semi_after) << "@compatibility_alias";
1088     return 0;
1089   }
1090   DeclTy *ClsType = Actions.ActOnCompatiblityAlias(atLoc,
1091                                                    aliasId, aliasLoc,
1092                                                    classId, classLoc);
1093   return ClsType;
1094 }
1095 
1096 ///   property-synthesis:
1097 ///     @synthesize property-ivar-list ';'
1098 ///
1099 ///   property-ivar-list:
1100 ///     property-ivar
1101 ///     property-ivar-list ',' property-ivar
1102 ///
1103 ///   property-ivar:
1104 ///     identifier
1105 ///     identifier '=' identifier
1106 ///
1107 Parser::DeclTy *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1108   assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1109          "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1110   SourceLocation loc = ConsumeToken(); // consume synthesize
1111   if (Tok.isNot(tok::identifier)) {
1112     Diag(Tok, diag::err_expected_ident);
1113     return 0;
1114   }
1115   while (Tok.is(tok::identifier)) {
1116     IdentifierInfo *propertyIvar = 0;
1117     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1118     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1119     if (Tok.is(tok::equal)) {
1120       // property '=' ivar-name
1121       ConsumeToken(); // consume '='
1122       if (Tok.isNot(tok::identifier)) {
1123         Diag(Tok, diag::err_expected_ident);
1124         break;
1125       }
1126       propertyIvar = Tok.getIdentifierInfo();
1127       ConsumeToken(); // consume ivar-name
1128     }
1129     Actions.ActOnPropertyImplDecl(atLoc, propertyLoc, true, ObjCImpDecl,
1130                                   propertyId, propertyIvar);
1131     if (Tok.isNot(tok::comma))
1132       break;
1133     ConsumeToken(); // consume ','
1134   }
1135   if (Tok.isNot(tok::semi))
1136     Diag(Tok, diag::err_expected_semi_after) << "@synthesize";
1137   return 0;
1138 }
1139 
1140 ///   property-dynamic:
1141 ///     @dynamic  property-list
1142 ///
1143 ///   property-list:
1144 ///     identifier
1145 ///     property-list ',' identifier
1146 ///
1147 Parser::DeclTy *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1148   assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1149          "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1150   SourceLocation loc = ConsumeToken(); // consume dynamic
1151   if (Tok.isNot(tok::identifier)) {
1152     Diag(Tok, diag::err_expected_ident);
1153     return 0;
1154   }
1155   while (Tok.is(tok::identifier)) {
1156     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1157     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1158     Actions.ActOnPropertyImplDecl(atLoc, propertyLoc, false, ObjCImpDecl,
1159                                   propertyId, 0);
1160 
1161     if (Tok.isNot(tok::comma))
1162       break;
1163     ConsumeToken(); // consume ','
1164   }
1165   if (Tok.isNot(tok::semi))
1166     Diag(Tok, diag::err_expected_semi_after) << "@dynamic";
1167   return 0;
1168 }
1169 
1170 ///  objc-throw-statement:
1171 ///    throw expression[opt];
1172 ///
1173 Parser::StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1174   ExprResult Res;
1175   ConsumeToken(); // consume throw
1176   if (Tok.isNot(tok::semi)) {
1177     Res = ParseExpression();
1178     if (Res.isInvalid) {
1179       SkipUntil(tok::semi);
1180       return true;
1181     }
1182   }
1183   ConsumeToken(); // consume ';'
1184   return Actions.ActOnObjCAtThrowStmt(atLoc, Res.Val);
1185 }
1186 
1187 /// objc-synchronized-statement:
1188 ///   @synchronized '(' expression ')' compound-statement
1189 ///
1190 Parser::StmtResult Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1191   ConsumeToken(); // consume synchronized
1192   if (Tok.isNot(tok::l_paren)) {
1193     Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1194     return true;
1195   }
1196   ConsumeParen();  // '('
1197   ExprResult Res = ParseExpression();
1198   if (Res.isInvalid) {
1199     SkipUntil(tok::semi);
1200     return true;
1201   }
1202   if (Tok.isNot(tok::r_paren)) {
1203     Diag(Tok, diag::err_expected_lbrace);
1204     return true;
1205   }
1206   ConsumeParen();  // ')'
1207   if (Tok.isNot(tok::l_brace)) {
1208     Diag(Tok, diag::err_expected_lbrace);
1209     return true;
1210   }
1211   // Enter a scope to hold everything within the compound stmt.  Compound
1212   // statements can always hold declarations.
1213   EnterScope(Scope::DeclScope);
1214 
1215   StmtResult SynchBody = ParseCompoundStatementBody();
1216 
1217   ExitScope();
1218   if (SynchBody.isInvalid)
1219     SynchBody = Actions.ActOnNullStmt(Tok.getLocation());
1220   return Actions.ActOnObjCAtSynchronizedStmt(atLoc, Res.Val, SynchBody.Val);
1221 }
1222 
1223 ///  objc-try-catch-statement:
1224 ///    @try compound-statement objc-catch-list[opt]
1225 ///    @try compound-statement objc-catch-list[opt] @finally compound-statement
1226 ///
1227 ///  objc-catch-list:
1228 ///    @catch ( parameter-declaration ) compound-statement
1229 ///    objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1230 ///  catch-parameter-declaration:
1231 ///     parameter-declaration
1232 ///     '...' [OBJC2]
1233 ///
1234 Parser::StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1235   bool catch_or_finally_seen = false;
1236 
1237   ConsumeToken(); // consume try
1238   if (Tok.isNot(tok::l_brace)) {
1239     Diag(Tok, diag::err_expected_lbrace);
1240     return true;
1241   }
1242   StmtResult CatchStmts;
1243   StmtResult FinallyStmt;
1244   EnterScope(Scope::DeclScope);
1245   StmtResult TryBody = ParseCompoundStatementBody();
1246   ExitScope();
1247   if (TryBody.isInvalid)
1248     TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1249 
1250   while (Tok.is(tok::at)) {
1251     // At this point, we need to lookahead to determine if this @ is the start
1252     // of an @catch or @finally.  We don't want to consume the @ token if this
1253     // is an @try or @encode or something else.
1254     Token AfterAt = GetLookAheadToken(1);
1255     if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1256         !AfterAt.isObjCAtKeyword(tok::objc_finally))
1257       break;
1258 
1259     SourceLocation AtCatchFinallyLoc = ConsumeToken();
1260     if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1261       StmtTy *FirstPart = 0;
1262       ConsumeToken(); // consume catch
1263       if (Tok.is(tok::l_paren)) {
1264         ConsumeParen();
1265         EnterScope(Scope::DeclScope);
1266         if (Tok.isNot(tok::ellipsis)) {
1267           DeclSpec DS;
1268           ParseDeclarationSpecifiers(DS);
1269           // For some odd reason, the name of the exception variable is
1270           // optional. As a result, we need to use PrototypeContext.
1271           Declarator DeclaratorInfo(DS, Declarator::PrototypeContext);
1272           ParseDeclarator(DeclaratorInfo);
1273           if (DeclaratorInfo.getIdentifier()) {
1274             DeclTy *aBlockVarDecl = Actions.ActOnDeclarator(CurScope,
1275                                                           DeclaratorInfo, 0);
1276             StmtResult stmtResult =
1277               Actions.ActOnDeclStmt(aBlockVarDecl,
1278                                     DS.getSourceRange().getBegin(),
1279                                     DeclaratorInfo.getSourceRange().getEnd());
1280             FirstPart = stmtResult.isInvalid ? 0 : stmtResult.Val;
1281           }
1282         } else
1283           ConsumeToken(); // consume '...'
1284         SourceLocation RParenLoc = ConsumeParen();
1285 
1286         StmtResult CatchBody(true);
1287         if (Tok.is(tok::l_brace))
1288           CatchBody = ParseCompoundStatementBody();
1289         else
1290           Diag(Tok, diag::err_expected_lbrace);
1291         if (CatchBody.isInvalid)
1292           CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1293         CatchStmts = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, RParenLoc,
1294           FirstPart, CatchBody.Val, CatchStmts.Val);
1295         ExitScope();
1296       } else {
1297         Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1298           << "@catch clause";
1299         return true;
1300       }
1301       catch_or_finally_seen = true;
1302     } else {
1303       assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1304       ConsumeToken(); // consume finally
1305       EnterScope(Scope::DeclScope);
1306 
1307 
1308       StmtResult FinallyBody(true);
1309       if (Tok.is(tok::l_brace))
1310         FinallyBody = ParseCompoundStatementBody();
1311       else
1312         Diag(Tok, diag::err_expected_lbrace);
1313       if (FinallyBody.isInvalid)
1314         FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1315       FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1316                                                    FinallyBody.Val);
1317       catch_or_finally_seen = true;
1318       ExitScope();
1319       break;
1320     }
1321   }
1322   if (!catch_or_finally_seen) {
1323     Diag(atLoc, diag::err_missing_catch_finally);
1324     return true;
1325   }
1326   return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.Val, CatchStmts.Val,
1327                                     FinallyStmt.Val);
1328 }
1329 
1330 ///   objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1331 ///
1332 Parser::DeclTy *Parser::ParseObjCMethodDefinition() {
1333   DeclTy *MDecl = ParseObjCMethodPrototype(ObjCImpDecl);
1334   // parse optional ';'
1335   if (Tok.is(tok::semi))
1336     ConsumeToken();
1337 
1338   // We should have an opening brace now.
1339   if (Tok.isNot(tok::l_brace)) {
1340     Diag(Tok, diag::err_expected_method_body);
1341 
1342     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1343     SkipUntil(tok::l_brace, true, true);
1344 
1345     // If we didn't find the '{', bail out.
1346     if (Tok.isNot(tok::l_brace))
1347       return 0;
1348   }
1349   SourceLocation BraceLoc = Tok.getLocation();
1350 
1351   // Enter a scope for the method body.
1352   EnterScope(Scope::FnScope|Scope::DeclScope);
1353 
1354   // Tell the actions module that we have entered a method definition with the
1355   // specified Declarator for the method.
1356   Actions.ObjCActOnStartOfMethodDef(CurScope, MDecl);
1357 
1358   StmtResult FnBody = ParseCompoundStatementBody();
1359 
1360   // If the function body could not be parsed, make a bogus compoundstmt.
1361   if (FnBody.isInvalid)
1362     FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc, 0, 0, false);
1363 
1364   // Leave the function body scope.
1365   ExitScope();
1366 
1367   // TODO: Pass argument information.
1368   Actions.ActOnFinishFunctionBody(MDecl, FnBody.Val);
1369   return MDecl;
1370 }
1371 
1372 Parser::StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
1373   if (Tok.isObjCAtKeyword(tok::objc_try)) {
1374     return ParseObjCTryStmt(AtLoc);
1375   } else if (Tok.isObjCAtKeyword(tok::objc_throw))
1376     return ParseObjCThrowStmt(AtLoc);
1377   else if (Tok.isObjCAtKeyword(tok::objc_synchronized))
1378     return ParseObjCSynchronizedStmt(AtLoc);
1379   ExprResult Res = ParseExpressionWithLeadingAt(AtLoc);
1380   if (Res.isInvalid) {
1381     // If the expression is invalid, skip ahead to the next semicolon. Not
1382     // doing this opens us up to the possibility of infinite loops if
1383     // ParseExpression does not consume any tokens.
1384     SkipUntil(tok::semi);
1385     return true;
1386   }
1387   // Otherwise, eat the semicolon.
1388   ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
1389   return Actions.ActOnExprStmt(Res.Val);
1390 }
1391 
1392 Parser::ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
1393   switch (Tok.getKind()) {
1394   case tok::string_literal:    // primary-expression: string-literal
1395   case tok::wide_string_literal:
1396     return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
1397   default:
1398     if (Tok.getIdentifierInfo() == 0)
1399       return Diag(AtLoc, diag::err_unexpected_at);
1400 
1401     switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
1402     case tok::objc_encode:
1403       return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
1404     case tok::objc_protocol:
1405       return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
1406     case tok::objc_selector:
1407       return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
1408     default:
1409         return Diag(AtLoc, diag::err_unexpected_at);
1410     }
1411   }
1412 }
1413 
1414 ///   objc-message-expr:
1415 ///     '[' objc-receiver objc-message-args ']'
1416 ///
1417 ///   objc-receiver:
1418 ///     expression
1419 ///     class-name
1420 ///     type-name
1421 Parser::ExprResult Parser::ParseObjCMessageExpression() {
1422   assert(Tok.is(tok::l_square) && "'[' expected");
1423   SourceLocation LBracLoc = ConsumeBracket(); // consume '['
1424 
1425   // Parse receiver
1426   if (isTokObjCMessageIdentifierReceiver()) {
1427     IdentifierInfo *ReceiverName = Tok.getIdentifierInfo();
1428     ConsumeToken();
1429     return ParseObjCMessageExpressionBody(LBracLoc, ReceiverName, 0);
1430   }
1431 
1432   ExprResult Res = ParseExpression();
1433   if (Res.isInvalid) {
1434     SkipUntil(tok::r_square);
1435     return Res;
1436   }
1437 
1438   return ParseObjCMessageExpressionBody(LBracLoc, 0, Res.Val);
1439 }
1440 
1441 /// ParseObjCMessageExpressionBody - Having parsed "'[' objc-receiver", parse
1442 /// the rest of a message expression.
1443 ///
1444 ///   objc-message-args:
1445 ///     objc-selector
1446 ///     objc-keywordarg-list
1447 ///
1448 ///   objc-keywordarg-list:
1449 ///     objc-keywordarg
1450 ///     objc-keywordarg-list objc-keywordarg
1451 ///
1452 ///   objc-keywordarg:
1453 ///     selector-name[opt] ':' objc-keywordexpr
1454 ///
1455 ///   objc-keywordexpr:
1456 ///     nonempty-expr-list
1457 ///
1458 ///   nonempty-expr-list:
1459 ///     assignment-expression
1460 ///     nonempty-expr-list , assignment-expression
1461 ///
1462 Parser::ExprResult
1463 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
1464                                        IdentifierInfo *ReceiverName,
1465                                        ExprTy *ReceiverExpr) {
1466   // Parse objc-selector
1467   SourceLocation Loc;
1468   IdentifierInfo *selIdent = ParseObjCSelector(Loc);
1469 
1470   llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
1471   llvm::SmallVector<Action::ExprTy *, 12> KeyExprs;
1472 
1473   if (Tok.is(tok::colon)) {
1474     while (1) {
1475       // Each iteration parses a single keyword argument.
1476       KeyIdents.push_back(selIdent);
1477 
1478       if (Tok.isNot(tok::colon)) {
1479         Diag(Tok, diag::err_expected_colon);
1480         // We must manually skip to a ']', otherwise the expression skipper will
1481         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
1482         // the enclosing expression.
1483         SkipUntil(tok::r_square);
1484         return true;
1485       }
1486 
1487       ConsumeToken(); // Eat the ':'.
1488       ///  Parse the expression after ':'
1489       ExprResult Res = ParseAssignmentExpression();
1490       if (Res.isInvalid) {
1491         // We must manually skip to a ']', otherwise the expression skipper will
1492         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
1493         // the enclosing expression.
1494         SkipUntil(tok::r_square);
1495         return Res;
1496       }
1497 
1498       // We have a valid expression.
1499       KeyExprs.push_back(Res.Val);
1500 
1501       // Check for another keyword selector.
1502       selIdent = ParseObjCSelector(Loc);
1503       if (!selIdent && Tok.isNot(tok::colon))
1504         break;
1505       // We have a selector or a colon, continue parsing.
1506     }
1507     // Parse the, optional, argument list, comma separated.
1508     while (Tok.is(tok::comma)) {
1509       ConsumeToken(); // Eat the ','.
1510       ///  Parse the expression after ','
1511       ExprResult Res = ParseAssignmentExpression();
1512       if (Res.isInvalid) {
1513         // We must manually skip to a ']', otherwise the expression skipper will
1514         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
1515         // the enclosing expression.
1516         SkipUntil(tok::r_square);
1517         return Res;
1518       }
1519 
1520       // We have a valid expression.
1521       KeyExprs.push_back(Res.Val);
1522     }
1523   } else if (!selIdent) {
1524     Diag(Tok, diag::err_expected_ident); // missing selector name.
1525 
1526     // We must manually skip to a ']', otherwise the expression skipper will
1527     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
1528     // the enclosing expression.
1529     SkipUntil(tok::r_square);
1530     return true;
1531   }
1532 
1533   if (Tok.isNot(tok::r_square)) {
1534     Diag(Tok, diag::err_expected_rsquare);
1535     // We must manually skip to a ']', otherwise the expression skipper will
1536     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
1537     // the enclosing expression.
1538     SkipUntil(tok::r_square);
1539     return true;
1540   }
1541 
1542   SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
1543 
1544   unsigned nKeys = KeyIdents.size();
1545   if (nKeys == 0)
1546     KeyIdents.push_back(selIdent);
1547   Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
1548 
1549   // We've just parsed a keyword message.
1550   if (ReceiverName)
1551     return Actions.ActOnClassMessage(CurScope,
1552                                      ReceiverName, Sel, LBracLoc, RBracLoc,
1553                                      &KeyExprs[0], KeyExprs.size());
1554   return Actions.ActOnInstanceMessage(ReceiverExpr, Sel, LBracLoc, RBracLoc,
1555                                       &KeyExprs[0], KeyExprs.size());
1556 }
1557 
1558 Parser::ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
1559   ExprResult Res = ParseStringLiteralExpression();
1560   if (Res.isInvalid) return Res;
1561 
1562   // @"foo" @"bar" is a valid concatenated string.  Eat any subsequent string
1563   // expressions.  At this point, we know that the only valid thing that starts
1564   // with '@' is an @"".
1565   llvm::SmallVector<SourceLocation, 4> AtLocs;
1566   llvm::SmallVector<ExprTy*, 4> AtStrings;
1567   AtLocs.push_back(AtLoc);
1568   AtStrings.push_back(Res.Val);
1569 
1570   while (Tok.is(tok::at)) {
1571     AtLocs.push_back(ConsumeToken()); // eat the @.
1572 
1573     ExprResult Res(true);  // Invalid unless there is a string literal.
1574     if (isTokenStringLiteral())
1575       Res = ParseStringLiteralExpression();
1576     else
1577       Diag(Tok, diag::err_objc_concat_string);
1578 
1579     if (Res.isInvalid) {
1580       while (!AtStrings.empty()) {
1581         Actions.DeleteExpr(AtStrings.back());
1582         AtStrings.pop_back();
1583       }
1584       return Res;
1585     }
1586 
1587     AtStrings.push_back(Res.Val);
1588   }
1589 
1590   return Actions.ParseObjCStringLiteral(&AtLocs[0], &AtStrings[0],
1591                                         AtStrings.size());
1592 }
1593 
1594 ///    objc-encode-expression:
1595 ///      @encode ( type-name )
1596 Parser::ExprResult Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
1597   assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
1598 
1599   SourceLocation EncLoc = ConsumeToken();
1600 
1601   if (Tok.isNot(tok::l_paren))
1602     return Diag(Tok, diag::err_expected_lparen_after) << "@encode";
1603 
1604   SourceLocation LParenLoc = ConsumeParen();
1605 
1606   TypeTy *Ty = ParseTypeName();
1607 
1608   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1609 
1610   return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc, Ty,
1611                                            RParenLoc);
1612 }
1613 
1614 ///     objc-protocol-expression
1615 ///       @protocol ( protocol-name )
1616 
1617 Parser::ExprResult Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
1618   SourceLocation ProtoLoc = ConsumeToken();
1619 
1620   if (Tok.isNot(tok::l_paren))
1621     return Diag(Tok, diag::err_expected_lparen_after) << "@protocol";
1622 
1623   SourceLocation LParenLoc = ConsumeParen();
1624 
1625   if (Tok.isNot(tok::identifier))
1626     return Diag(Tok, diag::err_expected_ident);
1627 
1628   IdentifierInfo *protocolId = Tok.getIdentifierInfo();
1629   ConsumeToken();
1630 
1631   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1632 
1633   return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
1634                                              LParenLoc, RParenLoc);
1635 }
1636 
1637 ///     objc-selector-expression
1638 ///       @selector '(' objc-keyword-selector ')'
1639 Parser::ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
1640   SourceLocation SelectorLoc = ConsumeToken();
1641 
1642   if (Tok.isNot(tok::l_paren))
1643     return Diag(Tok, diag::err_expected_lparen_after) << "@selector";
1644 
1645   llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
1646   SourceLocation LParenLoc = ConsumeParen();
1647   SourceLocation sLoc;
1648   IdentifierInfo *SelIdent = ParseObjCSelector(sLoc);
1649   if (!SelIdent && Tok.isNot(tok::colon))
1650     return Diag(Tok, diag::err_expected_ident); // missing selector name.
1651 
1652   KeyIdents.push_back(SelIdent);
1653   unsigned nColons = 0;
1654   if (Tok.isNot(tok::r_paren)) {
1655     while (1) {
1656       if (Tok.isNot(tok::colon))
1657         return Diag(Tok, diag::err_expected_colon);
1658 
1659       nColons++;
1660       ConsumeToken(); // Eat the ':'.
1661       if (Tok.is(tok::r_paren))
1662         break;
1663       // Check for another keyword selector.
1664       SourceLocation Loc;
1665       SelIdent = ParseObjCSelector(Loc);
1666       KeyIdents.push_back(SelIdent);
1667       if (!SelIdent && Tok.isNot(tok::colon))
1668         break;
1669     }
1670   }
1671   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1672   Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
1673   return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc, LParenLoc,
1674                                              RParenLoc);
1675  }
1676