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