xref: /llvm-project/clang/lib/Parse/ParseObjc.cpp (revision d6d866d6faf2f70860182f1433959999f90ea6f2)
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 
780   // Parse type qualifiers, in, inout, etc.
781   ParseObjCTypeQualifierList(DS, Context);
782 
783   ParsedType Ty;
784   if (isTypeSpecifierQualifier()) {
785     TypeResult TypeSpec =
786       ParseTypeName(0, Declarator::ObjCPrototypeContext, &DS);
787     if (!TypeSpec.isInvalid())
788       Ty = TypeSpec.get();
789   }
790 
791   if (Tok.is(tok::r_paren))
792     ConsumeParen();
793   else if (Tok.getLocation() == TypeStartLoc) {
794     // If we didn't eat any tokens, then this isn't a type.
795     Diag(Tok, diag::err_expected_type);
796     SkipUntil(tok::r_paren);
797   } else {
798     // Otherwise, we found *something*, but didn't get a ')' in the right
799     // place.  Emit an error then return what we have as the type.
800     MatchRHSPunctuation(tok::r_paren, LParenLoc);
801   }
802   return Ty;
803 }
804 
805 ///   objc-method-decl:
806 ///     objc-selector
807 ///     objc-keyword-selector objc-parmlist[opt]
808 ///     objc-type-name objc-selector
809 ///     objc-type-name objc-keyword-selector objc-parmlist[opt]
810 ///
811 ///   objc-keyword-selector:
812 ///     objc-keyword-decl
813 ///     objc-keyword-selector objc-keyword-decl
814 ///
815 ///   objc-keyword-decl:
816 ///     objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
817 ///     objc-selector ':' objc-keyword-attributes[opt] identifier
818 ///     ':' objc-type-name objc-keyword-attributes[opt] identifier
819 ///     ':' objc-keyword-attributes[opt] identifier
820 ///
821 ///   objc-parmlist:
822 ///     objc-parms objc-ellipsis[opt]
823 ///
824 ///   objc-parms:
825 ///     objc-parms , parameter-declaration
826 ///
827 ///   objc-ellipsis:
828 ///     , ...
829 ///
830 ///   objc-keyword-attributes:         [OBJC2]
831 ///     __attribute__((unused))
832 ///
833 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
834                                   tok::TokenKind mType,
835                                   tok::ObjCKeywordKind MethodImplKind,
836                                   bool MethodDefinition) {
837   ParsingDeclRAIIObject PD(*this);
838 
839   if (Tok.is(tok::code_completion)) {
840     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
841                                        /*ReturnType=*/ ParsedType());
842     ConsumeCodeCompletionToken();
843   }
844 
845   // Parse the return type if present.
846   ParsedType ReturnType;
847   ObjCDeclSpec DSRet;
848   if (Tok.is(tok::l_paren))
849     ReturnType = ParseObjCTypeName(DSRet, OTN_ResultType);
850 
851   // If attributes exist before the method, parse them.
852   ParsedAttributes methodAttrs(AttrFactory);
853   if (getLang().ObjC2)
854     MaybeParseGNUAttributes(methodAttrs);
855 
856   if (Tok.is(tok::code_completion)) {
857     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
858                                        ReturnType);
859     ConsumeCodeCompletionToken();
860   }
861 
862   // Now parse the selector.
863   SourceLocation selLoc;
864   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
865 
866   // An unnamed colon is valid.
867   if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
868     Diag(Tok, diag::err_expected_selector_for_method)
869       << SourceRange(mLoc, Tok.getLocation());
870     // Skip until we get a ; or {}.
871     SkipUntil(tok::r_brace);
872     return 0;
873   }
874 
875   SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
876   if (Tok.isNot(tok::colon)) {
877     // If attributes exist after the method, parse them.
878     if (getLang().ObjC2)
879       MaybeParseGNUAttributes(methodAttrs);
880 
881     Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
882     Decl *Result
883          = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
884                                           mType, DSRet, ReturnType,
885                                           selLoc, Sel, 0,
886                                           CParamInfo.data(), CParamInfo.size(),
887                                           methodAttrs.getList(), MethodImplKind,
888                                           false, MethodDefinition);
889     PD.complete(Result);
890     return Result;
891   }
892 
893   SmallVector<IdentifierInfo *, 12> KeyIdents;
894   SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
895   ParseScope PrototypeScope(this,
896                             Scope::FunctionPrototypeScope|Scope::DeclScope);
897 
898   AttributePool allParamAttrs(AttrFactory);
899 
900   while (1) {
901     ParsedAttributes paramAttrs(AttrFactory);
902     Sema::ObjCArgInfo ArgInfo;
903 
904     // Each iteration parses a single keyword argument.
905     if (Tok.isNot(tok::colon)) {
906       Diag(Tok, diag::err_expected_colon);
907       break;
908     }
909     ConsumeToken(); // Eat the ':'.
910 
911     ArgInfo.Type = ParsedType();
912     if (Tok.is(tok::l_paren)) // Parse the argument type if present.
913       ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, OTN_ParameterType);
914 
915     // If attributes exist before the argument name, parse them.
916     ArgInfo.ArgAttrs = 0;
917     if (getLang().ObjC2) {
918       MaybeParseGNUAttributes(paramAttrs);
919       ArgInfo.ArgAttrs = paramAttrs.getList();
920     }
921 
922     // Code completion for the next piece of the selector.
923     if (Tok.is(tok::code_completion)) {
924       ConsumeCodeCompletionToken();
925       KeyIdents.push_back(SelIdent);
926       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
927                                                  mType == tok::minus,
928                                                  /*AtParameterName=*/true,
929                                                  ReturnType,
930                                                  KeyIdents.data(),
931                                                  KeyIdents.size());
932       KeyIdents.pop_back();
933       break;
934     }
935 
936     if (Tok.isNot(tok::identifier)) {
937       Diag(Tok, diag::err_expected_ident); // missing argument name.
938       break;
939     }
940 
941     ArgInfo.Name = Tok.getIdentifierInfo();
942     ArgInfo.NameLoc = Tok.getLocation();
943     ConsumeToken(); // Eat the identifier.
944 
945     ArgInfos.push_back(ArgInfo);
946     KeyIdents.push_back(SelIdent);
947 
948     // Make sure the attributes persist.
949     allParamAttrs.takeAllFrom(paramAttrs.getPool());
950 
951     // Code completion for the next piece of the selector.
952     if (Tok.is(tok::code_completion)) {
953       ConsumeCodeCompletionToken();
954       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
955                                                  mType == tok::minus,
956                                                  /*AtParameterName=*/false,
957                                                  ReturnType,
958                                                  KeyIdents.data(),
959                                                  KeyIdents.size());
960       break;
961     }
962 
963     // Check for another keyword selector.
964     SourceLocation Loc;
965     SelIdent = ParseObjCSelectorPiece(Loc);
966     if (!SelIdent && Tok.isNot(tok::colon))
967       break;
968     // We have a selector or a colon, continue parsing.
969   }
970 
971   bool isVariadic = false;
972 
973   // Parse the (optional) parameter list.
974   while (Tok.is(tok::comma)) {
975     ConsumeToken();
976     if (Tok.is(tok::ellipsis)) {
977       isVariadic = true;
978       ConsumeToken();
979       break;
980     }
981     DeclSpec DS(AttrFactory);
982     ParseDeclarationSpecifiers(DS);
983     // Parse the declarator.
984     Declarator ParmDecl(DS, Declarator::PrototypeContext);
985     ParseDeclarator(ParmDecl);
986     IdentifierInfo *ParmII = ParmDecl.getIdentifier();
987     Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
988     CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
989                                                     ParmDecl.getIdentifierLoc(),
990                                                     Param,
991                                                    0));
992 
993   }
994 
995   // FIXME: Add support for optional parameter list...
996   // If attributes exist after the method, parse them.
997   if (getLang().ObjC2)
998     MaybeParseGNUAttributes(methodAttrs);
999 
1000   if (KeyIdents.size() == 0)
1001     return 0;
1002 
1003   Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1004                                                    &KeyIdents[0]);
1005   Decl *Result
1006        = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1007                                         mType, DSRet, ReturnType,
1008                                         selLoc, Sel, &ArgInfos[0],
1009                                         CParamInfo.data(), CParamInfo.size(),
1010                                         methodAttrs.getList(),
1011                                         MethodImplKind, isVariadic, MethodDefinition);
1012 
1013   PD.complete(Result);
1014   return Result;
1015 }
1016 
1017 ///   objc-protocol-refs:
1018 ///     '<' identifier-list '>'
1019 ///
1020 bool Parser::
1021 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1022                             SmallVectorImpl<SourceLocation> &ProtocolLocs,
1023                             bool WarnOnDeclarations,
1024                             SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1025   assert(Tok.is(tok::less) && "expected <");
1026 
1027   LAngleLoc = ConsumeToken(); // the "<"
1028 
1029   SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1030 
1031   while (1) {
1032     if (Tok.is(tok::code_completion)) {
1033       Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1034                                                  ProtocolIdents.size());
1035       ConsumeCodeCompletionToken();
1036     }
1037 
1038     if (Tok.isNot(tok::identifier)) {
1039       Diag(Tok, diag::err_expected_ident);
1040       SkipUntil(tok::greater);
1041       return true;
1042     }
1043     ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1044                                        Tok.getLocation()));
1045     ProtocolLocs.push_back(Tok.getLocation());
1046     ConsumeToken();
1047 
1048     if (Tok.isNot(tok::comma))
1049       break;
1050     ConsumeToken();
1051   }
1052 
1053   // Consume the '>'.
1054   if (Tok.isNot(tok::greater)) {
1055     Diag(Tok, diag::err_expected_greater);
1056     return true;
1057   }
1058 
1059   EndLoc = ConsumeAnyToken();
1060 
1061   // Convert the list of protocols identifiers into a list of protocol decls.
1062   Actions.FindProtocolDeclaration(WarnOnDeclarations,
1063                                   &ProtocolIdents[0], ProtocolIdents.size(),
1064                                   Protocols);
1065   return false;
1066 }
1067 
1068 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1069 /// in a decl-specifier-seq, starting at the '<'.
1070 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1071   assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1072   assert(getLang().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1073   SourceLocation LAngleLoc, EndProtoLoc;
1074   SmallVector<Decl *, 8> ProtocolDecl;
1075   SmallVector<SourceLocation, 8> ProtocolLocs;
1076   bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1077                                             LAngleLoc, EndProtoLoc);
1078   DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1079                            ProtocolLocs.data(), LAngleLoc);
1080   if (EndProtoLoc.isValid())
1081     DS.SetRangeEnd(EndProtoLoc);
1082   return Result;
1083 }
1084 
1085 
1086 ///   objc-class-instance-variables:
1087 ///     '{' objc-instance-variable-decl-list[opt] '}'
1088 ///
1089 ///   objc-instance-variable-decl-list:
1090 ///     objc-visibility-spec
1091 ///     objc-instance-variable-decl ';'
1092 ///     ';'
1093 ///     objc-instance-variable-decl-list objc-visibility-spec
1094 ///     objc-instance-variable-decl-list objc-instance-variable-decl ';'
1095 ///     objc-instance-variable-decl-list ';'
1096 ///
1097 ///   objc-visibility-spec:
1098 ///     @private
1099 ///     @protected
1100 ///     @public
1101 ///     @package [OBJC2]
1102 ///
1103 ///   objc-instance-variable-decl:
1104 ///     struct-declaration
1105 ///
1106 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1107                                              tok::ObjCKeywordKind visibility,
1108                                              SourceLocation atLoc) {
1109   assert(Tok.is(tok::l_brace) && "expected {");
1110   SmallVector<Decl *, 32> AllIvarDecls;
1111 
1112   ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1113 
1114   SourceLocation LBraceLoc = ConsumeBrace(); // the "{"
1115 
1116   // While we still have something to read, read the instance variables.
1117   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1118     // Each iteration of this loop reads one objc-instance-variable-decl.
1119 
1120     // Check for extraneous top-level semicolon.
1121     if (Tok.is(tok::semi)) {
1122       Diag(Tok, diag::ext_extra_ivar_semi)
1123         << FixItHint::CreateRemoval(Tok.getLocation());
1124       ConsumeToken();
1125       continue;
1126     }
1127 
1128     // Set the default visibility to private.
1129     if (Tok.is(tok::at)) { // parse objc-visibility-spec
1130       ConsumeToken(); // eat the @ sign
1131 
1132       if (Tok.is(tok::code_completion)) {
1133         Actions.CodeCompleteObjCAtVisibility(getCurScope());
1134         ConsumeCodeCompletionToken();
1135       }
1136 
1137       switch (Tok.getObjCKeywordID()) {
1138       case tok::objc_private:
1139       case tok::objc_public:
1140       case tok::objc_protected:
1141       case tok::objc_package:
1142         visibility = Tok.getObjCKeywordID();
1143         ConsumeToken();
1144         continue;
1145       default:
1146         Diag(Tok, diag::err_objc_illegal_visibility_spec);
1147         continue;
1148       }
1149     }
1150 
1151     if (Tok.is(tok::code_completion)) {
1152       Actions.CodeCompleteOrdinaryName(getCurScope(),
1153                                        Sema::PCC_ObjCInstanceVariableList);
1154       ConsumeCodeCompletionToken();
1155     }
1156 
1157     struct ObjCIvarCallback : FieldCallback {
1158       Parser &P;
1159       Decl *IDecl;
1160       tok::ObjCKeywordKind visibility;
1161       SmallVectorImpl<Decl *> &AllIvarDecls;
1162 
1163       ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1164                        SmallVectorImpl<Decl *> &AllIvarDecls) :
1165         P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1166       }
1167 
1168       Decl *invoke(FieldDeclarator &FD) {
1169         P.Actions.ActOnObjCContainerStartDefinition(IDecl);
1170         // Install the declarator into the interface decl.
1171         Decl *Field
1172           = P.Actions.ActOnIvar(P.getCurScope(),
1173                                 FD.D.getDeclSpec().getSourceRange().getBegin(),
1174                                 FD.D, FD.BitfieldSize, visibility);
1175         P.Actions.ActOnObjCContainerFinishDefinition(IDecl);
1176         if (Field)
1177           AllIvarDecls.push_back(Field);
1178         return Field;
1179       }
1180     } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1181 
1182     // Parse all the comma separated declarators.
1183     DeclSpec DS(AttrFactory);
1184     ParseStructDeclaration(DS, Callback);
1185 
1186     if (Tok.is(tok::semi)) {
1187       ConsumeToken();
1188     } else {
1189       Diag(Tok, diag::err_expected_semi_decl_list);
1190       // Skip to end of block or statement
1191       SkipUntil(tok::r_brace, true, true);
1192     }
1193   }
1194   SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1195   Actions.ActOnLastBitfield(RBraceLoc, AllIvarDecls);
1196   // Call ActOnFields() even if we don't have any decls. This is useful
1197   // for code rewriting tools that need to be aware of the empty list.
1198   Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1199                       AllIvarDecls.data(), AllIvarDecls.size(),
1200                       LBraceLoc, RBraceLoc, 0);
1201   return;
1202 }
1203 
1204 ///   objc-protocol-declaration:
1205 ///     objc-protocol-definition
1206 ///     objc-protocol-forward-reference
1207 ///
1208 ///   objc-protocol-definition:
1209 ///     @protocol identifier
1210 ///       objc-protocol-refs[opt]
1211 ///       objc-interface-decl-list
1212 ///     @end
1213 ///
1214 ///   objc-protocol-forward-reference:
1215 ///     @protocol identifier-list ';'
1216 ///
1217 ///   "@protocol identifier ;" should be resolved as "@protocol
1218 ///   identifier-list ;": objc-interface-decl-list may not start with a
1219 ///   semicolon in the first alternative if objc-protocol-refs are omitted.
1220 Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1221                                              ParsedAttributes &attrs) {
1222   assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1223          "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1224   ConsumeToken(); // the "protocol" identifier
1225 
1226   if (Tok.is(tok::code_completion)) {
1227     Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1228     ConsumeCodeCompletionToken();
1229   }
1230 
1231   if (Tok.isNot(tok::identifier)) {
1232     Diag(Tok, diag::err_expected_ident); // missing protocol name.
1233     return 0;
1234   }
1235   // Save the protocol name, then consume it.
1236   IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1237   SourceLocation nameLoc = ConsumeToken();
1238 
1239   if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1240     IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1241     ConsumeToken();
1242     return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1243                                                    attrs.getList());
1244   }
1245 
1246   if (Tok.is(tok::comma)) { // list of forward declarations.
1247     SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1248     ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1249 
1250     // Parse the list of forward declarations.
1251     while (1) {
1252       ConsumeToken(); // the ','
1253       if (Tok.isNot(tok::identifier)) {
1254         Diag(Tok, diag::err_expected_ident);
1255         SkipUntil(tok::semi);
1256         return 0;
1257       }
1258       ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1259                                                Tok.getLocation()));
1260       ConsumeToken(); // the identifier
1261 
1262       if (Tok.isNot(tok::comma))
1263         break;
1264     }
1265     // Consume the ';'.
1266     if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1267       return 0;
1268 
1269     return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1270                                                    &ProtocolRefs[0],
1271                                                    ProtocolRefs.size(),
1272                                                    attrs.getList());
1273   }
1274 
1275   // Last, and definitely not least, parse a protocol declaration.
1276   SourceLocation LAngleLoc, EndProtoLoc;
1277 
1278   SmallVector<Decl *, 8> ProtocolRefs;
1279   SmallVector<SourceLocation, 8> ProtocolLocs;
1280   if (Tok.is(tok::less) &&
1281       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1282                                   LAngleLoc, EndProtoLoc))
1283     return 0;
1284 
1285   Decl *ProtoType =
1286     Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1287                                         ProtocolRefs.data(),
1288                                         ProtocolRefs.size(),
1289                                         ProtocolLocs.data(),
1290                                         EndProtoLoc, attrs.getList());
1291 
1292 
1293   Actions.ActOnObjCContainerStartDefinition(ProtoType);
1294   ParseObjCInterfaceDeclList(tok::objc_protocol);
1295   Actions.ActOnObjCContainerFinishDefinition(ProtoType);
1296   return ProtoType;
1297 }
1298 
1299 ///   objc-implementation:
1300 ///     objc-class-implementation-prologue
1301 ///     objc-category-implementation-prologue
1302 ///
1303 ///   objc-class-implementation-prologue:
1304 ///     @implementation identifier objc-superclass[opt]
1305 ///       objc-class-instance-variables[opt]
1306 ///
1307 ///   objc-category-implementation-prologue:
1308 ///     @implementation identifier ( identifier )
1309 Decl *Parser::ParseObjCAtImplementationDeclaration(
1310   SourceLocation atLoc) {
1311   assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1312          "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1313   ConsumeToken(); // the "implementation" identifier
1314 
1315   // Code completion after '@implementation'.
1316   if (Tok.is(tok::code_completion)) {
1317     Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1318     ConsumeCodeCompletionToken();
1319   }
1320 
1321   if (Tok.isNot(tok::identifier)) {
1322     Diag(Tok, diag::err_expected_ident); // missing class or category name.
1323     return 0;
1324   }
1325   // We have a class or category name - consume it.
1326   IdentifierInfo *nameId = Tok.getIdentifierInfo();
1327   SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1328 
1329   if (Tok.is(tok::l_paren)) {
1330     // we have a category implementation.
1331     ConsumeParen();
1332     SourceLocation categoryLoc, rparenLoc;
1333     IdentifierInfo *categoryId = 0;
1334 
1335     if (Tok.is(tok::code_completion)) {
1336       Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1337       ConsumeCodeCompletionToken();
1338     }
1339 
1340     if (Tok.is(tok::identifier)) {
1341       categoryId = Tok.getIdentifierInfo();
1342       categoryLoc = ConsumeToken();
1343     } else {
1344       Diag(Tok, diag::err_expected_ident); // missing category name.
1345       return 0;
1346     }
1347     if (Tok.isNot(tok::r_paren)) {
1348       Diag(Tok, diag::err_expected_rparen);
1349       SkipUntil(tok::r_paren, false); // don't stop at ';'
1350       return 0;
1351     }
1352     rparenLoc = ConsumeParen();
1353     Decl *ImplCatType = Actions.ActOnStartCategoryImplementation(
1354                                     atLoc, nameId, nameLoc, categoryId,
1355                                     categoryLoc);
1356 
1357     Actions.ActOnObjCContainerStartDefinition(ImplCatType);
1358     ObjCImpDecl = ImplCatType;
1359     PendingObjCImpDecl.push_back(ObjCImpDecl);
1360     return 0;
1361   }
1362   // We have a class implementation
1363   SourceLocation superClassLoc;
1364   IdentifierInfo *superClassId = 0;
1365   if (Tok.is(tok::colon)) {
1366     // We have a super class
1367     ConsumeToken();
1368     if (Tok.isNot(tok::identifier)) {
1369       Diag(Tok, diag::err_expected_ident); // missing super class name.
1370       return 0;
1371     }
1372     superClassId = Tok.getIdentifierInfo();
1373     superClassLoc = ConsumeToken(); // Consume super class name
1374   }
1375   Decl *ImplClsType = Actions.ActOnStartClassImplementation(
1376                                   atLoc, nameId, nameLoc,
1377                                   superClassId, superClassLoc);
1378 
1379   if (Tok.is(tok::l_brace)) // we have ivars
1380     ParseObjCClassInstanceVariables(ImplClsType, tok::objc_private, atLoc);
1381 
1382   Actions.ActOnObjCContainerStartDefinition(ImplClsType);
1383   ObjCImpDecl = ImplClsType;
1384   PendingObjCImpDecl.push_back(ObjCImpDecl);
1385   return 0;
1386 }
1387 
1388 Decl *Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1389   assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1390          "ParseObjCAtEndDeclaration(): Expected @end");
1391   Decl *Result = ObjCImpDecl;
1392   ConsumeToken(); // the "end" identifier
1393   if (ObjCImpDecl) {
1394     Actions.ActOnAtEnd(getCurScope(), atEnd);
1395     Actions.ActOnObjCContainerFinishDefinition(ObjCImpDecl);
1396     ObjCImpDecl = 0;
1397     PendingObjCImpDecl.pop_back();
1398   }
1399   else {
1400     // missing @implementation
1401     Diag(atEnd.getBegin(), diag::err_expected_implementation);
1402   }
1403   return Result;
1404 }
1405 
1406 Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() {
1407   Actions.DiagnoseUseOfUnimplementedSelectors();
1408   if (PendingObjCImpDecl.empty())
1409     return Actions.ConvertDeclToDeclGroup(0);
1410   Decl *ImpDecl = PendingObjCImpDecl.pop_back_val();
1411   Actions.ActOnAtEnd(getCurScope(), SourceRange());
1412   Actions.ActOnObjCContainerFinishDefinition(ImpDecl);
1413   return Actions.ConvertDeclToDeclGroup(ImpDecl);
1414 }
1415 
1416 ///   compatibility-alias-decl:
1417 ///     @compatibility_alias alias-name  class-name ';'
1418 ///
1419 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1420   assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1421          "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1422   ConsumeToken(); // consume compatibility_alias
1423   if (Tok.isNot(tok::identifier)) {
1424     Diag(Tok, diag::err_expected_ident);
1425     return 0;
1426   }
1427   IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1428   SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1429   if (Tok.isNot(tok::identifier)) {
1430     Diag(Tok, diag::err_expected_ident);
1431     return 0;
1432   }
1433   IdentifierInfo *classId = Tok.getIdentifierInfo();
1434   SourceLocation classLoc = ConsumeToken(); // consume class-name;
1435   ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1436                    "@compatibility_alias");
1437   return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
1438                                         classId, classLoc);
1439 }
1440 
1441 ///   property-synthesis:
1442 ///     @synthesize property-ivar-list ';'
1443 ///
1444 ///   property-ivar-list:
1445 ///     property-ivar
1446 ///     property-ivar-list ',' property-ivar
1447 ///
1448 ///   property-ivar:
1449 ///     identifier
1450 ///     identifier '=' identifier
1451 ///
1452 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1453   assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1454          "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1455   ConsumeToken(); // consume synthesize
1456 
1457   while (true) {
1458     if (Tok.is(tok::code_completion)) {
1459       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1460       ConsumeCodeCompletionToken();
1461     }
1462 
1463     if (Tok.isNot(tok::identifier)) {
1464       Diag(Tok, diag::err_synthesized_property_name);
1465       SkipUntil(tok::semi);
1466       return 0;
1467     }
1468 
1469     IdentifierInfo *propertyIvar = 0;
1470     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1471     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1472     SourceLocation propertyIvarLoc;
1473     if (Tok.is(tok::equal)) {
1474       // property '=' ivar-name
1475       ConsumeToken(); // consume '='
1476 
1477       if (Tok.is(tok::code_completion)) {
1478         Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1479         ConsumeCodeCompletionToken();
1480       }
1481 
1482       if (Tok.isNot(tok::identifier)) {
1483         Diag(Tok, diag::err_expected_ident);
1484         break;
1485       }
1486       propertyIvar = Tok.getIdentifierInfo();
1487       propertyIvarLoc = ConsumeToken(); // consume ivar-name
1488     }
1489     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1490                                   propertyId, propertyIvar, propertyIvarLoc);
1491     if (Tok.isNot(tok::comma))
1492       break;
1493     ConsumeToken(); // consume ','
1494   }
1495   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1496   return 0;
1497 }
1498 
1499 ///   property-dynamic:
1500 ///     @dynamic  property-list
1501 ///
1502 ///   property-list:
1503 ///     identifier
1504 ///     property-list ',' identifier
1505 ///
1506 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1507   assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1508          "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1509   ConsumeToken(); // consume dynamic
1510   while (true) {
1511     if (Tok.is(tok::code_completion)) {
1512       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1513       ConsumeCodeCompletionToken();
1514     }
1515 
1516     if (Tok.isNot(tok::identifier)) {
1517       Diag(Tok, diag::err_expected_ident);
1518       SkipUntil(tok::semi);
1519       return 0;
1520     }
1521 
1522     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1523     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1524     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1525                                   propertyId, 0, SourceLocation());
1526 
1527     if (Tok.isNot(tok::comma))
1528       break;
1529     ConsumeToken(); // consume ','
1530   }
1531   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1532   return 0;
1533 }
1534 
1535 ///  objc-throw-statement:
1536 ///    throw expression[opt];
1537 ///
1538 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1539   ExprResult Res;
1540   ConsumeToken(); // consume throw
1541   if (Tok.isNot(tok::semi)) {
1542     Res = ParseExpression();
1543     if (Res.isInvalid()) {
1544       SkipUntil(tok::semi);
1545       return StmtError();
1546     }
1547   }
1548   // consume ';'
1549   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1550   return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1551 }
1552 
1553 /// objc-synchronized-statement:
1554 ///   @synchronized '(' expression ')' compound-statement
1555 ///
1556 StmtResult
1557 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1558   ConsumeToken(); // consume synchronized
1559   if (Tok.isNot(tok::l_paren)) {
1560     Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1561     return StmtError();
1562   }
1563 
1564   // The operand is surrounded with parentheses.
1565   ConsumeParen();  // '('
1566   ExprResult operand(ParseExpression());
1567 
1568   if (Tok.is(tok::r_paren)) {
1569     ConsumeParen();  // ')'
1570   } else {
1571     if (!operand.isInvalid())
1572       Diag(Tok, diag::err_expected_rparen);
1573 
1574     // Skip forward until we see a left brace, but don't consume it.
1575     SkipUntil(tok::l_brace, true, true);
1576   }
1577 
1578   // Require a compound statement.
1579   if (Tok.isNot(tok::l_brace)) {
1580     if (!operand.isInvalid())
1581       Diag(Tok, diag::err_expected_lbrace);
1582     return StmtError();
1583   }
1584 
1585   // Check the @synchronized operand now.
1586   if (!operand.isInvalid())
1587     operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
1588 
1589   // Parse the compound statement within a new scope.
1590   ParseScope bodyScope(this, Scope::DeclScope);
1591   StmtResult body(ParseCompoundStatementBody());
1592   bodyScope.Exit();
1593 
1594   // If there was a semantic or parse error earlier with the
1595   // operand, fail now.
1596   if (operand.isInvalid())
1597     return StmtError();
1598 
1599   if (body.isInvalid())
1600     body = Actions.ActOnNullStmt(Tok.getLocation());
1601 
1602   return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1603 }
1604 
1605 ///  objc-try-catch-statement:
1606 ///    @try compound-statement objc-catch-list[opt]
1607 ///    @try compound-statement objc-catch-list[opt] @finally compound-statement
1608 ///
1609 ///  objc-catch-list:
1610 ///    @catch ( parameter-declaration ) compound-statement
1611 ///    objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1612 ///  catch-parameter-declaration:
1613 ///     parameter-declaration
1614 ///     '...' [OBJC2]
1615 ///
1616 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1617   bool catch_or_finally_seen = false;
1618 
1619   ConsumeToken(); // consume try
1620   if (Tok.isNot(tok::l_brace)) {
1621     Diag(Tok, diag::err_expected_lbrace);
1622     return StmtError();
1623   }
1624   StmtVector CatchStmts(Actions);
1625   StmtResult FinallyStmt;
1626   ParseScope TryScope(this, Scope::DeclScope);
1627   StmtResult TryBody(ParseCompoundStatementBody());
1628   TryScope.Exit();
1629   if (TryBody.isInvalid())
1630     TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1631 
1632   while (Tok.is(tok::at)) {
1633     // At this point, we need to lookahead to determine if this @ is the start
1634     // of an @catch or @finally.  We don't want to consume the @ token if this
1635     // is an @try or @encode or something else.
1636     Token AfterAt = GetLookAheadToken(1);
1637     if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1638         !AfterAt.isObjCAtKeyword(tok::objc_finally))
1639       break;
1640 
1641     SourceLocation AtCatchFinallyLoc = ConsumeToken();
1642     if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1643       Decl *FirstPart = 0;
1644       ConsumeToken(); // consume catch
1645       if (Tok.is(tok::l_paren)) {
1646         ConsumeParen();
1647         ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1648         if (Tok.isNot(tok::ellipsis)) {
1649           DeclSpec DS(AttrFactory);
1650           ParseDeclarationSpecifiers(DS);
1651           Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1652           ParseDeclarator(ParmDecl);
1653 
1654           // Inform the actions module about the declarator, so it
1655           // gets added to the current scope.
1656           FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1657         } else
1658           ConsumeToken(); // consume '...'
1659 
1660         SourceLocation RParenLoc;
1661 
1662         if (Tok.is(tok::r_paren))
1663           RParenLoc = ConsumeParen();
1664         else // Skip over garbage, until we get to ')'.  Eat the ')'.
1665           SkipUntil(tok::r_paren, true, false);
1666 
1667         StmtResult CatchBody(true);
1668         if (Tok.is(tok::l_brace))
1669           CatchBody = ParseCompoundStatementBody();
1670         else
1671           Diag(Tok, diag::err_expected_lbrace);
1672         if (CatchBody.isInvalid())
1673           CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1674 
1675         StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1676                                                               RParenLoc,
1677                                                               FirstPart,
1678                                                               CatchBody.take());
1679         if (!Catch.isInvalid())
1680           CatchStmts.push_back(Catch.release());
1681 
1682       } else {
1683         Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1684           << "@catch clause";
1685         return StmtError();
1686       }
1687       catch_or_finally_seen = true;
1688     } else {
1689       assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1690       ConsumeToken(); // consume finally
1691       ParseScope FinallyScope(this, Scope::DeclScope);
1692 
1693       StmtResult FinallyBody(true);
1694       if (Tok.is(tok::l_brace))
1695         FinallyBody = ParseCompoundStatementBody();
1696       else
1697         Diag(Tok, diag::err_expected_lbrace);
1698       if (FinallyBody.isInvalid())
1699         FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1700       FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1701                                                    FinallyBody.take());
1702       catch_or_finally_seen = true;
1703       break;
1704     }
1705   }
1706   if (!catch_or_finally_seen) {
1707     Diag(atLoc, diag::err_missing_catch_finally);
1708     return StmtError();
1709   }
1710 
1711   return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1712                                     move_arg(CatchStmts),
1713                                     FinallyStmt.take());
1714 }
1715 
1716 /// objc-autoreleasepool-statement:
1717 ///   @autoreleasepool compound-statement
1718 ///
1719 StmtResult
1720 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1721   ConsumeToken(); // consume autoreleasepool
1722   if (Tok.isNot(tok::l_brace)) {
1723     Diag(Tok, diag::err_expected_lbrace);
1724     return StmtError();
1725   }
1726   // Enter a scope to hold everything within the compound stmt.  Compound
1727   // statements can always hold declarations.
1728   ParseScope BodyScope(this, Scope::DeclScope);
1729 
1730   StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1731 
1732   BodyScope.Exit();
1733   if (AutoreleasePoolBody.isInvalid())
1734     AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1735   return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1736                                                 AutoreleasePoolBody.take());
1737 }
1738 
1739 ///   objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1740 ///
1741 Decl *Parser::ParseObjCMethodDefinition() {
1742   Decl *MDecl = ParseObjCMethodPrototype();
1743 
1744   PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1745                                       "parsing Objective-C method");
1746 
1747   // parse optional ';'
1748   if (Tok.is(tok::semi)) {
1749     if (ObjCImpDecl) {
1750       Diag(Tok, diag::warn_semicolon_before_method_body)
1751         << FixItHint::CreateRemoval(Tok.getLocation());
1752     }
1753     ConsumeToken();
1754   }
1755 
1756   // We should have an opening brace now.
1757   if (Tok.isNot(tok::l_brace)) {
1758     Diag(Tok, diag::err_expected_method_body);
1759 
1760     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1761     SkipUntil(tok::l_brace, true, true);
1762 
1763     // If we didn't find the '{', bail out.
1764     if (Tok.isNot(tok::l_brace))
1765       return 0;
1766   }
1767   SourceLocation BraceLoc = Tok.getLocation();
1768 
1769   // Enter a scope for the method body.
1770   ParseScope BodyScope(this,
1771                        Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
1772 
1773   // Tell the actions module that we have entered a method definition with the
1774   // specified Declarator for the method.
1775   Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
1776 
1777   if (PP.isCodeCompletionEnabled()) {
1778     if (trySkippingFunctionBodyForCodeCompletion()) {
1779       BodyScope.Exit();
1780       return Actions.ActOnFinishFunctionBody(MDecl, 0);
1781     }
1782   }
1783 
1784   StmtResult FnBody(ParseCompoundStatementBody());
1785 
1786   // If the function body could not be parsed, make a bogus compoundstmt.
1787   if (FnBody.isInvalid())
1788     FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
1789                                        MultiStmtArg(Actions), false);
1790 
1791   // Leave the function body scope.
1792   BodyScope.Exit();
1793 
1794   // TODO: Pass argument information.
1795   Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
1796   return MDecl;
1797 }
1798 
1799 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
1800   if (Tok.is(tok::code_completion)) {
1801     Actions.CodeCompleteObjCAtStatement(getCurScope());
1802     ConsumeCodeCompletionToken();
1803     return StmtError();
1804   }
1805 
1806   if (Tok.isObjCAtKeyword(tok::objc_try))
1807     return ParseObjCTryStmt(AtLoc);
1808 
1809   if (Tok.isObjCAtKeyword(tok::objc_throw))
1810     return ParseObjCThrowStmt(AtLoc);
1811 
1812   if (Tok.isObjCAtKeyword(tok::objc_synchronized))
1813     return ParseObjCSynchronizedStmt(AtLoc);
1814 
1815   if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
1816     return ParseObjCAutoreleasePoolStmt(AtLoc);
1817 
1818   ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
1819   if (Res.isInvalid()) {
1820     // If the expression is invalid, skip ahead to the next semicolon. Not
1821     // doing this opens us up to the possibility of infinite loops if
1822     // ParseExpression does not consume any tokens.
1823     SkipUntil(tok::semi);
1824     return StmtError();
1825   }
1826 
1827   // Otherwise, eat the semicolon.
1828   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1829   return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
1830 }
1831 
1832 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
1833   switch (Tok.getKind()) {
1834   case tok::code_completion:
1835     Actions.CodeCompleteObjCAtExpression(getCurScope());
1836     ConsumeCodeCompletionToken();
1837     return ExprError();
1838 
1839   case tok::string_literal:    // primary-expression: string-literal
1840   case tok::wide_string_literal:
1841     return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
1842   default:
1843     if (Tok.getIdentifierInfo() == 0)
1844       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1845 
1846     switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
1847     case tok::objc_encode:
1848       return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
1849     case tok::objc_protocol:
1850       return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
1851     case tok::objc_selector:
1852       return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
1853     default:
1854       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1855     }
1856   }
1857 }
1858 
1859 /// \brirg Parse the receiver of an Objective-C++ message send.
1860 ///
1861 /// This routine parses the receiver of a message send in
1862 /// Objective-C++ either as a type or as an expression. Note that this
1863 /// routine must not be called to parse a send to 'super', since it
1864 /// has no way to return such a result.
1865 ///
1866 /// \param IsExpr Whether the receiver was parsed as an expression.
1867 ///
1868 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
1869 /// IsExpr is true), the parsed expression. If the receiver was parsed
1870 /// as a type (\c IsExpr is false), the parsed type.
1871 ///
1872 /// \returns True if an error occurred during parsing or semantic
1873 /// analysis, in which case the arguments do not have valid
1874 /// values. Otherwise, returns false for a successful parse.
1875 ///
1876 ///   objc-receiver: [C++]
1877 ///     'super' [not parsed here]
1878 ///     expression
1879 ///     simple-type-specifier
1880 ///     typename-specifier
1881 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
1882   InMessageExpressionRAIIObject InMessage(*this, true);
1883 
1884   if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1885       Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
1886     TryAnnotateTypeOrScopeToken();
1887 
1888   if (!isCXXSimpleTypeSpecifier()) {
1889     //   objc-receiver:
1890     //     expression
1891     ExprResult Receiver = ParseExpression();
1892     if (Receiver.isInvalid())
1893       return true;
1894 
1895     IsExpr = true;
1896     TypeOrExpr = Receiver.take();
1897     return false;
1898   }
1899 
1900   // objc-receiver:
1901   //   typename-specifier
1902   //   simple-type-specifier
1903   //   expression (that starts with one of the above)
1904   DeclSpec DS(AttrFactory);
1905   ParseCXXSimpleTypeSpecifier(DS);
1906 
1907   if (Tok.is(tok::l_paren)) {
1908     // If we see an opening parentheses at this point, we are
1909     // actually parsing an expression that starts with a
1910     // function-style cast, e.g.,
1911     //
1912     //   postfix-expression:
1913     //     simple-type-specifier ( expression-list [opt] )
1914     //     typename-specifier ( expression-list [opt] )
1915     //
1916     // Parse the remainder of this case, then the (optional)
1917     // postfix-expression suffix, followed by the (optional)
1918     // right-hand side of the binary expression. We have an
1919     // instance method.
1920     ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
1921     if (!Receiver.isInvalid())
1922       Receiver = ParsePostfixExpressionSuffix(Receiver.take());
1923     if (!Receiver.isInvalid())
1924       Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
1925     if (Receiver.isInvalid())
1926       return true;
1927 
1928     IsExpr = true;
1929     TypeOrExpr = Receiver.take();
1930     return false;
1931   }
1932 
1933   // We have a class message. Turn the simple-type-specifier or
1934   // typename-specifier we parsed into a type and parse the
1935   // remainder of the class message.
1936   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1937   TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1938   if (Type.isInvalid())
1939     return true;
1940 
1941   IsExpr = false;
1942   TypeOrExpr = Type.get().getAsOpaquePtr();
1943   return false;
1944 }
1945 
1946 /// \brief Determine whether the parser is currently referring to a an
1947 /// Objective-C message send, using a simplified heuristic to avoid overhead.
1948 ///
1949 /// This routine will only return true for a subset of valid message-send
1950 /// expressions.
1951 bool Parser::isSimpleObjCMessageExpression() {
1952   assert(Tok.is(tok::l_square) && getLang().ObjC1 &&
1953          "Incorrect start for isSimpleObjCMessageExpression");
1954   return GetLookAheadToken(1).is(tok::identifier) &&
1955          GetLookAheadToken(2).is(tok::identifier);
1956 }
1957 
1958 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
1959   if (!getLang().ObjC1 || !NextToken().is(tok::identifier) ||
1960       InMessageExpression)
1961     return false;
1962 
1963 
1964   ParsedType Type;
1965 
1966   if (Tok.is(tok::annot_typename))
1967     Type = getTypeAnnotation(Tok);
1968   else if (Tok.is(tok::identifier))
1969     Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
1970                                getCurScope());
1971   else
1972     return false;
1973 
1974   if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
1975     const Token &AfterNext = GetLookAheadToken(2);
1976     if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
1977       if (Tok.is(tok::identifier))
1978         TryAnnotateTypeOrScopeToken();
1979 
1980       return Tok.is(tok::annot_typename);
1981     }
1982   }
1983 
1984   return false;
1985 }
1986 
1987 ///   objc-message-expr:
1988 ///     '[' objc-receiver objc-message-args ']'
1989 ///
1990 ///   objc-receiver: [C]
1991 ///     'super'
1992 ///     expression
1993 ///     class-name
1994 ///     type-name
1995 ///
1996 ExprResult Parser::ParseObjCMessageExpression() {
1997   assert(Tok.is(tok::l_square) && "'[' expected");
1998   SourceLocation LBracLoc = ConsumeBracket(); // consume '['
1999 
2000   if (Tok.is(tok::code_completion)) {
2001     Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2002     ConsumeCodeCompletionToken();
2003     SkipUntil(tok::r_square);
2004     return ExprError();
2005   }
2006 
2007   InMessageExpressionRAIIObject InMessage(*this, true);
2008 
2009   if (getLang().CPlusPlus) {
2010     // We completely separate the C and C++ cases because C++ requires
2011     // more complicated (read: slower) parsing.
2012 
2013     // Handle send to super.
2014     // FIXME: This doesn't benefit from the same typo-correction we
2015     // get in Objective-C.
2016     if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2017         NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2018       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2019                                             ParsedType(), 0);
2020 
2021     // Parse the receiver, which is either a type or an expression.
2022     bool IsExpr;
2023     void *TypeOrExpr = NULL;
2024     if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2025       SkipUntil(tok::r_square);
2026       return ExprError();
2027     }
2028 
2029     if (IsExpr)
2030       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2031                                             ParsedType(),
2032                                             static_cast<Expr*>(TypeOrExpr));
2033 
2034     return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2035                               ParsedType::getFromOpaquePtr(TypeOrExpr),
2036                                           0);
2037   }
2038 
2039   if (Tok.is(tok::identifier)) {
2040     IdentifierInfo *Name = Tok.getIdentifierInfo();
2041     SourceLocation NameLoc = Tok.getLocation();
2042     ParsedType ReceiverType;
2043     switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2044                                        Name == Ident_super,
2045                                        NextToken().is(tok::period),
2046                                        ReceiverType)) {
2047     case Sema::ObjCSuperMessage:
2048       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2049                                             ParsedType(), 0);
2050 
2051     case Sema::ObjCClassMessage:
2052       if (!ReceiverType) {
2053         SkipUntil(tok::r_square);
2054         return ExprError();
2055       }
2056 
2057       ConsumeToken(); // the type name
2058 
2059       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2060                                             ReceiverType, 0);
2061 
2062     case Sema::ObjCInstanceMessage:
2063       // Fall through to parse an expression.
2064       break;
2065     }
2066   }
2067 
2068   // Otherwise, an arbitrary expression can be the receiver of a send.
2069   ExprResult Res(ParseExpression());
2070   if (Res.isInvalid()) {
2071     SkipUntil(tok::r_square);
2072     return move(Res);
2073   }
2074 
2075   return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2076                                         ParsedType(), Res.take());
2077 }
2078 
2079 /// \brief Parse the remainder of an Objective-C message following the
2080 /// '[' objc-receiver.
2081 ///
2082 /// This routine handles sends to super, class messages (sent to a
2083 /// class name), and instance messages (sent to an object), and the
2084 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2085 /// ReceiverExpr, respectively. Only one of these parameters may have
2086 /// a valid value.
2087 ///
2088 /// \param LBracLoc The location of the opening '['.
2089 ///
2090 /// \param SuperLoc If this is a send to 'super', the location of the
2091 /// 'super' keyword that indicates a send to the superclass.
2092 ///
2093 /// \param ReceiverType If this is a class message, the type of the
2094 /// class we are sending a message to.
2095 ///
2096 /// \param ReceiverExpr If this is an instance message, the expression
2097 /// used to compute the receiver object.
2098 ///
2099 ///   objc-message-args:
2100 ///     objc-selector
2101 ///     objc-keywordarg-list
2102 ///
2103 ///   objc-keywordarg-list:
2104 ///     objc-keywordarg
2105 ///     objc-keywordarg-list objc-keywordarg
2106 ///
2107 ///   objc-keywordarg:
2108 ///     selector-name[opt] ':' objc-keywordexpr
2109 ///
2110 ///   objc-keywordexpr:
2111 ///     nonempty-expr-list
2112 ///
2113 ///   nonempty-expr-list:
2114 ///     assignment-expression
2115 ///     nonempty-expr-list , assignment-expression
2116 ///
2117 ExprResult
2118 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2119                                        SourceLocation SuperLoc,
2120                                        ParsedType ReceiverType,
2121                                        ExprArg ReceiverExpr) {
2122   InMessageExpressionRAIIObject InMessage(*this, true);
2123 
2124   if (Tok.is(tok::code_completion)) {
2125     if (SuperLoc.isValid())
2126       Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2127                                            false);
2128     else if (ReceiverType)
2129       Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2130                                            false);
2131     else
2132       Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2133                                               0, 0, false);
2134     ConsumeCodeCompletionToken();
2135   }
2136 
2137   // Parse objc-selector
2138   SourceLocation Loc;
2139   IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2140 
2141   SourceLocation SelectorLoc = Loc;
2142 
2143   SmallVector<IdentifierInfo *, 12> KeyIdents;
2144   ExprVector KeyExprs(Actions);
2145 
2146   if (Tok.is(tok::colon)) {
2147     while (1) {
2148       // Each iteration parses a single keyword argument.
2149       KeyIdents.push_back(selIdent);
2150 
2151       if (Tok.isNot(tok::colon)) {
2152         Diag(Tok, diag::err_expected_colon);
2153         // We must manually skip to a ']', otherwise the expression skipper will
2154         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2155         // the enclosing expression.
2156         SkipUntil(tok::r_square);
2157         return ExprError();
2158       }
2159 
2160       ConsumeToken(); // Eat the ':'.
2161       ///  Parse the expression after ':'
2162 
2163       if (Tok.is(tok::code_completion)) {
2164         if (SuperLoc.isValid())
2165           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2166                                                KeyIdents.data(),
2167                                                KeyIdents.size(),
2168                                                /*AtArgumentEpression=*/true);
2169         else if (ReceiverType)
2170           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2171                                                KeyIdents.data(),
2172                                                KeyIdents.size(),
2173                                                /*AtArgumentEpression=*/true);
2174         else
2175           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2176                                                   KeyIdents.data(),
2177                                                   KeyIdents.size(),
2178                                                   /*AtArgumentEpression=*/true);
2179 
2180         ConsumeCodeCompletionToken();
2181         SkipUntil(tok::r_square);
2182         return ExprError();
2183       }
2184 
2185       ExprResult Res(ParseAssignmentExpression());
2186       if (Res.isInvalid()) {
2187         // We must manually skip to a ']', otherwise the expression skipper will
2188         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2189         // the enclosing expression.
2190         SkipUntil(tok::r_square);
2191         return move(Res);
2192       }
2193 
2194       // We have a valid expression.
2195       KeyExprs.push_back(Res.release());
2196 
2197       // Code completion after each argument.
2198       if (Tok.is(tok::code_completion)) {
2199         if (SuperLoc.isValid())
2200           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2201                                                KeyIdents.data(),
2202                                                KeyIdents.size(),
2203                                                /*AtArgumentEpression=*/false);
2204         else if (ReceiverType)
2205           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2206                                                KeyIdents.data(),
2207                                                KeyIdents.size(),
2208                                                /*AtArgumentEpression=*/false);
2209         else
2210           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2211                                                   KeyIdents.data(),
2212                                                   KeyIdents.size(),
2213                                                 /*AtArgumentEpression=*/false);
2214         ConsumeCodeCompletionToken();
2215         SkipUntil(tok::r_square);
2216         return ExprError();
2217       }
2218 
2219       // Check for another keyword selector.
2220       selIdent = ParseObjCSelectorPiece(Loc);
2221       if (!selIdent && Tok.isNot(tok::colon))
2222         break;
2223       // We have a selector or a colon, continue parsing.
2224     }
2225     // Parse the, optional, argument list, comma separated.
2226     while (Tok.is(tok::comma)) {
2227       ConsumeToken(); // Eat the ','.
2228       ///  Parse the expression after ','
2229       ExprResult Res(ParseAssignmentExpression());
2230       if (Res.isInvalid()) {
2231         // We must manually skip to a ']', otherwise the expression skipper will
2232         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2233         // the enclosing expression.
2234         SkipUntil(tok::r_square);
2235         return move(Res);
2236       }
2237 
2238       // We have a valid expression.
2239       KeyExprs.push_back(Res.release());
2240     }
2241   } else if (!selIdent) {
2242     Diag(Tok, diag::err_expected_ident); // missing selector name.
2243 
2244     // We must manually skip to a ']', otherwise the expression skipper will
2245     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2246     // the enclosing expression.
2247     SkipUntil(tok::r_square);
2248     return ExprError();
2249   }
2250 
2251   if (Tok.isNot(tok::r_square)) {
2252     if (Tok.is(tok::identifier))
2253       Diag(Tok, diag::err_expected_colon);
2254     else
2255       Diag(Tok, diag::err_expected_rsquare);
2256     // We must manually skip to a ']', otherwise the expression skipper will
2257     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2258     // the enclosing expression.
2259     SkipUntil(tok::r_square);
2260     return ExprError();
2261   }
2262 
2263   SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2264 
2265   unsigned nKeys = KeyIdents.size();
2266   if (nKeys == 0)
2267     KeyIdents.push_back(selIdent);
2268   Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2269 
2270   if (SuperLoc.isValid())
2271     return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2272                                      LBracLoc, SelectorLoc, RBracLoc,
2273                                      MultiExprArg(Actions,
2274                                                   KeyExprs.take(),
2275                                                   KeyExprs.size()));
2276   else if (ReceiverType)
2277     return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2278                                      LBracLoc, SelectorLoc, RBracLoc,
2279                                      MultiExprArg(Actions,
2280                                                   KeyExprs.take(),
2281                                                   KeyExprs.size()));
2282   return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2283                                       LBracLoc, SelectorLoc, RBracLoc,
2284                                       MultiExprArg(Actions,
2285                                                    KeyExprs.take(),
2286                                                    KeyExprs.size()));
2287 }
2288 
2289 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2290   ExprResult Res(ParseStringLiteralExpression());
2291   if (Res.isInvalid()) return move(Res);
2292 
2293   // @"foo" @"bar" is a valid concatenated string.  Eat any subsequent string
2294   // expressions.  At this point, we know that the only valid thing that starts
2295   // with '@' is an @"".
2296   SmallVector<SourceLocation, 4> AtLocs;
2297   ExprVector AtStrings(Actions);
2298   AtLocs.push_back(AtLoc);
2299   AtStrings.push_back(Res.release());
2300 
2301   while (Tok.is(tok::at)) {
2302     AtLocs.push_back(ConsumeToken()); // eat the @.
2303 
2304     // Invalid unless there is a string literal.
2305     if (!isTokenStringLiteral())
2306       return ExprError(Diag(Tok, diag::err_objc_concat_string));
2307 
2308     ExprResult Lit(ParseStringLiteralExpression());
2309     if (Lit.isInvalid())
2310       return move(Lit);
2311 
2312     AtStrings.push_back(Lit.release());
2313   }
2314 
2315   return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
2316                                               AtStrings.size()));
2317 }
2318 
2319 ///    objc-encode-expression:
2320 ///      @encode ( type-name )
2321 ExprResult
2322 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2323   assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2324 
2325   SourceLocation EncLoc = ConsumeToken();
2326 
2327   if (Tok.isNot(tok::l_paren))
2328     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2329 
2330   SourceLocation LParenLoc = ConsumeParen();
2331 
2332   TypeResult Ty = ParseTypeName();
2333 
2334   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2335 
2336   if (Ty.isInvalid())
2337     return ExprError();
2338 
2339   return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc,
2340                                                  Ty.get(), RParenLoc));
2341 }
2342 
2343 ///     objc-protocol-expression
2344 ///       @protocol ( protocol-name )
2345 ExprResult
2346 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2347   SourceLocation ProtoLoc = ConsumeToken();
2348 
2349   if (Tok.isNot(tok::l_paren))
2350     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2351 
2352   SourceLocation LParenLoc = ConsumeParen();
2353 
2354   if (Tok.isNot(tok::identifier))
2355     return ExprError(Diag(Tok, diag::err_expected_ident));
2356 
2357   IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2358   ConsumeToken();
2359 
2360   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2361 
2362   return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2363                                                    LParenLoc, RParenLoc));
2364 }
2365 
2366 ///     objc-selector-expression
2367 ///       @selector '(' objc-keyword-selector ')'
2368 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2369   SourceLocation SelectorLoc = ConsumeToken();
2370 
2371   if (Tok.isNot(tok::l_paren))
2372     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2373 
2374   SmallVector<IdentifierInfo *, 12> KeyIdents;
2375   SourceLocation LParenLoc = ConsumeParen();
2376   SourceLocation sLoc;
2377 
2378   if (Tok.is(tok::code_completion)) {
2379     Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2380                                      KeyIdents.size());
2381     ConsumeCodeCompletionToken();
2382     MatchRHSPunctuation(tok::r_paren, LParenLoc);
2383     return ExprError();
2384   }
2385 
2386   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2387   if (!SelIdent &&  // missing selector name.
2388       Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2389     return ExprError(Diag(Tok, diag::err_expected_ident));
2390 
2391   KeyIdents.push_back(SelIdent);
2392   unsigned nColons = 0;
2393   if (Tok.isNot(tok::r_paren)) {
2394     while (1) {
2395       if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2396         ++nColons;
2397         KeyIdents.push_back(0);
2398       } else if (Tok.isNot(tok::colon))
2399         return ExprError(Diag(Tok, diag::err_expected_colon));
2400 
2401       ++nColons;
2402       ConsumeToken(); // Eat the ':' or '::'.
2403       if (Tok.is(tok::r_paren))
2404         break;
2405 
2406       if (Tok.is(tok::code_completion)) {
2407         Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2408                                          KeyIdents.size());
2409         ConsumeCodeCompletionToken();
2410         MatchRHSPunctuation(tok::r_paren, LParenLoc);
2411         return ExprError();
2412       }
2413 
2414       // Check for another keyword selector.
2415       SourceLocation Loc;
2416       SelIdent = ParseObjCSelectorPiece(Loc);
2417       KeyIdents.push_back(SelIdent);
2418       if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2419         break;
2420     }
2421   }
2422   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2423   Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2424   return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2425                                                    LParenLoc, RParenLoc));
2426  }
2427