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