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