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