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