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