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