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