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