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