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