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