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