xref: /llvm-project/clang/lib/Parse/ParseObjc.cpp (revision b268a282a4f1911f1300fb703f28d77a78562d16)
1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the Objective-C portions of the Parser interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Parse/ParseDiagnostic.h"
15 #include "clang/Parse/Parser.h"
16 #include "clang/Sema/DeclSpec.h"
17 #include "clang/Sema/Scope.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 Decl *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 0;
59   }
60 }
61 
62 ///
63 /// objc-class-declaration:
64 ///    '@' 'class' identifier-list ';'
65 ///
66 Decl *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 0;
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 0;
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 Decl *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 0;
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 0;
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 0;
168     }
169     rparenLoc = ConsumeParen();
170     // Next, we need to check for any protocol references.
171     SourceLocation LAngleLoc, EndProtoLoc;
172     llvm::SmallVector<Decl *, 8> ProtocolRefs;
173     llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
174     if (Tok.is(tok::less) &&
175         ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
176                                     LAngleLoc, EndProtoLoc))
177       return 0;
178 
179     if (attrList) // categories don't support attributes.
180       Diag(Tok, diag::err_objc_no_attributes_on_category);
181 
182     Decl *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 0;
213     }
214     superClassId = Tok.getIdentifierInfo();
215     superClassLoc = ConsumeToken();
216   }
217   // Next, we need to check for any protocol references.
218   llvm::SmallVector<Decl *, 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 0;
225 
226   Decl *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   Decl *IDecl;
245   llvm::SmallVectorImpl<Decl *> &Props;
246   ObjCDeclSpec &OCDS;
247   SourceLocation AtLoc;
248   tok::ObjCKeywordKind MethodImplKind;
249 
250   ObjCPropertyCallback(Parser &P, Decl *IDecl,
251                        llvm::SmallVectorImpl<Decl *> &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   Decl *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 0;
263     }
264     if (FD.BitfieldSize) {
265       P.Diag(AtLoc, diag::err_objc_property_bitfield)
266         << FD.D.getSourceRange();
267       return 0;
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     Decl *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(Decl *interfaceDecl,
310                                         tok::ObjCKeywordKind contextKey) {
311   llvm::SmallVector<Decl *, 32> allMethods;
312   llvm::SmallVector<Decl *, 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       Decl *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       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::PCC_ObjCImplementation
352                                              : Action::PCC_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, Decl *ClassDecl,
472                                         Decl **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 Decl *Parser::ParseObjCMethodPrototype(Decl *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   Decl *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 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
777                                   tok::TokenKind mType,
778                                   Decl *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 0;
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     Decl *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     // Code completion for the next piece of the selector.
860     if (Tok.is(tok::code_completion)) {
861       ConsumeCodeCompletionToken();
862       KeyIdents.push_back(SelIdent);
863       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
864                                                  mType == tok::minus,
865                                                  /*AtParameterName=*/true,
866                                                  ReturnType,
867                                                  KeyIdents.data(),
868                                                  KeyIdents.size());
869       KeyIdents.pop_back();
870       break;
871     }
872 
873     if (Tok.isNot(tok::identifier)) {
874       Diag(Tok, diag::err_expected_ident); // missing argument name.
875       break;
876     }
877 
878     ArgInfo.Name = Tok.getIdentifierInfo();
879     ArgInfo.NameLoc = Tok.getLocation();
880     ConsumeToken(); // Eat the identifier.
881 
882     ArgInfos.push_back(ArgInfo);
883     KeyIdents.push_back(SelIdent);
884 
885     // Code completion for the next piece of the selector.
886     if (Tok.is(tok::code_completion)) {
887       ConsumeCodeCompletionToken();
888       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
889                                                  mType == tok::minus,
890                                                  /*AtParameterName=*/false,
891                                                  ReturnType,
892                                                  KeyIdents.data(),
893                                                  KeyIdents.size());
894       break;
895     }
896 
897     // Check for another keyword selector.
898     SourceLocation Loc;
899     SelIdent = ParseObjCSelectorPiece(Loc);
900     if (!SelIdent && Tok.isNot(tok::colon))
901       break;
902     // We have a selector or a colon, continue parsing.
903   }
904 
905   bool isVariadic = false;
906 
907   // Parse the (optional) parameter list.
908   while (Tok.is(tok::comma)) {
909     ConsumeToken();
910     if (Tok.is(tok::ellipsis)) {
911       isVariadic = true;
912       ConsumeToken();
913       break;
914     }
915     DeclSpec DS;
916     ParseDeclarationSpecifiers(DS);
917     // Parse the declarator.
918     Declarator ParmDecl(DS, Declarator::PrototypeContext);
919     ParseDeclarator(ParmDecl);
920     IdentifierInfo *ParmII = ParmDecl.getIdentifier();
921     Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
922     CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
923                                                     ParmDecl.getIdentifierLoc(),
924                                                     Param,
925                                                    0));
926 
927   }
928 
929   // FIXME: Add support for optional parmameter list...
930   // If attributes exist after the method, parse them.
931   if (getLang().ObjC2 && Tok.is(tok::kw___attribute))
932     MethodAttrs.reset(addAttributeLists(MethodAttrs.take(),
933                                         ParseGNUAttributes()));
934 
935   if (KeyIdents.size() == 0)
936     return 0;
937   Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
938                                                    &KeyIdents[0]);
939   Decl *Result
940        = Actions.ActOnMethodDeclaration(mLoc, Tok.getLocation(),
941                                         mType, IDecl, DSRet, ReturnType, Sel,
942                                         &ArgInfos[0],
943                                         CParamInfo.data(), CParamInfo.size(),
944                                         MethodAttrs.get(),
945                                         MethodImplKind, isVariadic);
946   PD.complete(Result);
947 
948   // Delete referenced AttributeList objects.
949   for (llvm::SmallVectorImpl<Action::ObjCArgInfo>::iterator
950        I = ArgInfos.begin(), E = ArgInfos.end(); I != E; ++I)
951     delete I->ArgAttrs;
952 
953   return Result;
954 }
955 
956 ///   objc-protocol-refs:
957 ///     '<' identifier-list '>'
958 ///
959 bool Parser::
960 ParseObjCProtocolReferences(llvm::SmallVectorImpl<Decl *> &Protocols,
961                             llvm::SmallVectorImpl<SourceLocation> &ProtocolLocs,
962                             bool WarnOnDeclarations,
963                             SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
964   assert(Tok.is(tok::less) && "expected <");
965 
966   LAngleLoc = ConsumeToken(); // the "<"
967 
968   llvm::SmallVector<IdentifierLocPair, 8> ProtocolIdents;
969 
970   while (1) {
971     if (Tok.is(tok::code_completion)) {
972       Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
973                                                  ProtocolIdents.size());
974       ConsumeCodeCompletionToken();
975     }
976 
977     if (Tok.isNot(tok::identifier)) {
978       Diag(Tok, diag::err_expected_ident);
979       SkipUntil(tok::greater);
980       return true;
981     }
982     ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
983                                        Tok.getLocation()));
984     ProtocolLocs.push_back(Tok.getLocation());
985     ConsumeToken();
986 
987     if (Tok.isNot(tok::comma))
988       break;
989     ConsumeToken();
990   }
991 
992   // Consume the '>'.
993   if (Tok.isNot(tok::greater)) {
994     Diag(Tok, diag::err_expected_greater);
995     return true;
996   }
997 
998   EndLoc = ConsumeAnyToken();
999 
1000   // Convert the list of protocols identifiers into a list of protocol decls.
1001   Actions.FindProtocolDeclaration(WarnOnDeclarations,
1002                                   &ProtocolIdents[0], ProtocolIdents.size(),
1003                                   Protocols);
1004   return false;
1005 }
1006 
1007 ///   objc-class-instance-variables:
1008 ///     '{' objc-instance-variable-decl-list[opt] '}'
1009 ///
1010 ///   objc-instance-variable-decl-list:
1011 ///     objc-visibility-spec
1012 ///     objc-instance-variable-decl ';'
1013 ///     ';'
1014 ///     objc-instance-variable-decl-list objc-visibility-spec
1015 ///     objc-instance-variable-decl-list objc-instance-variable-decl ';'
1016 ///     objc-instance-variable-decl-list ';'
1017 ///
1018 ///   objc-visibility-spec:
1019 ///     @private
1020 ///     @protected
1021 ///     @public
1022 ///     @package [OBJC2]
1023 ///
1024 ///   objc-instance-variable-decl:
1025 ///     struct-declaration
1026 ///
1027 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1028                                              tok::ObjCKeywordKind visibility,
1029                                              SourceLocation atLoc) {
1030   assert(Tok.is(tok::l_brace) && "expected {");
1031   llvm::SmallVector<Decl *, 32> AllIvarDecls;
1032 
1033   ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1034 
1035   SourceLocation LBraceLoc = ConsumeBrace(); // the "{"
1036 
1037   // While we still have something to read, read the instance variables.
1038   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1039     // Each iteration of this loop reads one objc-instance-variable-decl.
1040 
1041     // Check for extraneous top-level semicolon.
1042     if (Tok.is(tok::semi)) {
1043       Diag(Tok, diag::ext_extra_ivar_semi)
1044         << FixItHint::CreateRemoval(Tok.getLocation());
1045       ConsumeToken();
1046       continue;
1047     }
1048 
1049     // Set the default visibility to private.
1050     if (Tok.is(tok::at)) { // parse objc-visibility-spec
1051       ConsumeToken(); // eat the @ sign
1052 
1053       if (Tok.is(tok::code_completion)) {
1054         Actions.CodeCompleteObjCAtVisibility(getCurScope());
1055         ConsumeCodeCompletionToken();
1056       }
1057 
1058       switch (Tok.getObjCKeywordID()) {
1059       case tok::objc_private:
1060       case tok::objc_public:
1061       case tok::objc_protected:
1062       case tok::objc_package:
1063         visibility = Tok.getObjCKeywordID();
1064         ConsumeToken();
1065         continue;
1066       default:
1067         Diag(Tok, diag::err_objc_illegal_visibility_spec);
1068         continue;
1069       }
1070     }
1071 
1072     if (Tok.is(tok::code_completion)) {
1073       Actions.CodeCompleteOrdinaryName(getCurScope(),
1074                                        Action::PCC_ObjCInstanceVariableList);
1075       ConsumeCodeCompletionToken();
1076     }
1077 
1078     struct ObjCIvarCallback : FieldCallback {
1079       Parser &P;
1080       Decl *IDecl;
1081       tok::ObjCKeywordKind visibility;
1082       llvm::SmallVectorImpl<Decl *> &AllIvarDecls;
1083 
1084       ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1085                        llvm::SmallVectorImpl<Decl *> &AllIvarDecls) :
1086         P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1087       }
1088 
1089       Decl *invoke(FieldDeclarator &FD) {
1090         // Install the declarator into the interface decl.
1091         Decl *Field
1092           = P.Actions.ActOnIvar(P.getCurScope(),
1093                                 FD.D.getDeclSpec().getSourceRange().getBegin(),
1094                                 IDecl, FD.D, FD.BitfieldSize, visibility);
1095         if (Field)
1096           AllIvarDecls.push_back(Field);
1097         return Field;
1098       }
1099     } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1100 
1101     // Parse all the comma separated declarators.
1102     DeclSpec DS;
1103     ParseStructDeclaration(DS, Callback);
1104 
1105     if (Tok.is(tok::semi)) {
1106       ConsumeToken();
1107     } else {
1108       Diag(Tok, diag::err_expected_semi_decl_list);
1109       // Skip to end of block or statement
1110       SkipUntil(tok::r_brace, true, true);
1111     }
1112   }
1113   SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1114   Actions.ActOnLastBitfield(RBraceLoc, interfaceDecl, AllIvarDecls);
1115   // Call ActOnFields() even if we don't have any decls. This is useful
1116   // for code rewriting tools that need to be aware of the empty list.
1117   Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1118                       AllIvarDecls.data(), AllIvarDecls.size(),
1119                       LBraceLoc, RBraceLoc, 0);
1120   return;
1121 }
1122 
1123 ///   objc-protocol-declaration:
1124 ///     objc-protocol-definition
1125 ///     objc-protocol-forward-reference
1126 ///
1127 ///   objc-protocol-definition:
1128 ///     @protocol identifier
1129 ///       objc-protocol-refs[opt]
1130 ///       objc-interface-decl-list
1131 ///     @end
1132 ///
1133 ///   objc-protocol-forward-reference:
1134 ///     @protocol identifier-list ';'
1135 ///
1136 ///   "@protocol identifier ;" should be resolved as "@protocol
1137 ///   identifier-list ;": objc-interface-decl-list may not start with a
1138 ///   semicolon in the first alternative if objc-protocol-refs are omitted.
1139 Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1140                                                       AttributeList *attrList) {
1141   assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1142          "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1143   ConsumeToken(); // the "protocol" identifier
1144 
1145   if (Tok.is(tok::code_completion)) {
1146     Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1147     ConsumeCodeCompletionToken();
1148   }
1149 
1150   if (Tok.isNot(tok::identifier)) {
1151     Diag(Tok, diag::err_expected_ident); // missing protocol name.
1152     return 0;
1153   }
1154   // Save the protocol name, then consume it.
1155   IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1156   SourceLocation nameLoc = ConsumeToken();
1157 
1158   if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1159     IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1160     ConsumeToken();
1161     return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1162                                                    attrList);
1163   }
1164 
1165   if (Tok.is(tok::comma)) { // list of forward declarations.
1166     llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1167     ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1168 
1169     // Parse the list of forward declarations.
1170     while (1) {
1171       ConsumeToken(); // the ','
1172       if (Tok.isNot(tok::identifier)) {
1173         Diag(Tok, diag::err_expected_ident);
1174         SkipUntil(tok::semi);
1175         return 0;
1176       }
1177       ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1178                                                Tok.getLocation()));
1179       ConsumeToken(); // the identifier
1180 
1181       if (Tok.isNot(tok::comma))
1182         break;
1183     }
1184     // Consume the ';'.
1185     if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1186       return 0;
1187 
1188     return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1189                                                    &ProtocolRefs[0],
1190                                                    ProtocolRefs.size(),
1191                                                    attrList);
1192   }
1193 
1194   // Last, and definitely not least, parse a protocol declaration.
1195   SourceLocation LAngleLoc, EndProtoLoc;
1196 
1197   llvm::SmallVector<Decl *, 8> ProtocolRefs;
1198   llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1199   if (Tok.is(tok::less) &&
1200       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1201                                   LAngleLoc, EndProtoLoc))
1202     return 0;
1203 
1204   Decl *ProtoType =
1205     Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1206                                         ProtocolRefs.data(),
1207                                         ProtocolRefs.size(),
1208                                         ProtocolLocs.data(),
1209                                         EndProtoLoc, attrList);
1210   ParseObjCInterfaceDeclList(ProtoType, tok::objc_protocol);
1211   return ProtoType;
1212 }
1213 
1214 ///   objc-implementation:
1215 ///     objc-class-implementation-prologue
1216 ///     objc-category-implementation-prologue
1217 ///
1218 ///   objc-class-implementation-prologue:
1219 ///     @implementation identifier objc-superclass[opt]
1220 ///       objc-class-instance-variables[opt]
1221 ///
1222 ///   objc-category-implementation-prologue:
1223 ///     @implementation identifier ( identifier )
1224 Decl *Parser::ParseObjCAtImplementationDeclaration(
1225   SourceLocation atLoc) {
1226   assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1227          "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1228   ConsumeToken(); // the "implementation" identifier
1229 
1230   // Code completion after '@implementation'.
1231   if (Tok.is(tok::code_completion)) {
1232     Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1233     ConsumeCodeCompletionToken();
1234   }
1235 
1236   if (Tok.isNot(tok::identifier)) {
1237     Diag(Tok, diag::err_expected_ident); // missing class or category name.
1238     return 0;
1239   }
1240   // We have a class or category name - consume it.
1241   IdentifierInfo *nameId = Tok.getIdentifierInfo();
1242   SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1243 
1244   if (Tok.is(tok::l_paren)) {
1245     // we have a category implementation.
1246     SourceLocation lparenLoc = ConsumeParen();
1247     SourceLocation categoryLoc, rparenLoc;
1248     IdentifierInfo *categoryId = 0;
1249 
1250     if (Tok.is(tok::code_completion)) {
1251       Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1252       ConsumeCodeCompletionToken();
1253     }
1254 
1255     if (Tok.is(tok::identifier)) {
1256       categoryId = Tok.getIdentifierInfo();
1257       categoryLoc = ConsumeToken();
1258     } else {
1259       Diag(Tok, diag::err_expected_ident); // missing category name.
1260       return 0;
1261     }
1262     if (Tok.isNot(tok::r_paren)) {
1263       Diag(Tok, diag::err_expected_rparen);
1264       SkipUntil(tok::r_paren, false); // don't stop at ';'
1265       return 0;
1266     }
1267     rparenLoc = ConsumeParen();
1268     Decl *ImplCatType = Actions.ActOnStartCategoryImplementation(
1269                                     atLoc, nameId, nameLoc, categoryId,
1270                                     categoryLoc);
1271     ObjCImpDecl = ImplCatType;
1272     PendingObjCImpDecl.push_back(ObjCImpDecl);
1273     return 0;
1274   }
1275   // We have a class implementation
1276   SourceLocation superClassLoc;
1277   IdentifierInfo *superClassId = 0;
1278   if (Tok.is(tok::colon)) {
1279     // We have a super class
1280     ConsumeToken();
1281     if (Tok.isNot(tok::identifier)) {
1282       Diag(Tok, diag::err_expected_ident); // missing super class name.
1283       return 0;
1284     }
1285     superClassId = Tok.getIdentifierInfo();
1286     superClassLoc = ConsumeToken(); // Consume super class name
1287   }
1288   Decl *ImplClsType = Actions.ActOnStartClassImplementation(
1289                                   atLoc, nameId, nameLoc,
1290                                   superClassId, superClassLoc);
1291 
1292   if (Tok.is(tok::l_brace)) // we have ivars
1293     ParseObjCClassInstanceVariables(ImplClsType/*FIXME*/,
1294                                     tok::objc_private, atLoc);
1295   ObjCImpDecl = ImplClsType;
1296   PendingObjCImpDecl.push_back(ObjCImpDecl);
1297 
1298   return 0;
1299 }
1300 
1301 Decl *Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1302   assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1303          "ParseObjCAtEndDeclaration(): Expected @end");
1304   Decl *Result = ObjCImpDecl;
1305   ConsumeToken(); // the "end" identifier
1306   if (ObjCImpDecl) {
1307     Actions.ActOnAtEnd(getCurScope(), atEnd, ObjCImpDecl);
1308     ObjCImpDecl = 0;
1309     PendingObjCImpDecl.pop_back();
1310   }
1311   else {
1312     // missing @implementation
1313     Diag(atEnd.getBegin(), diag::warn_expected_implementation);
1314   }
1315   return Result;
1316 }
1317 
1318 Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() {
1319   Actions.DiagnoseUseOfUnimplementedSelectors();
1320   if (PendingObjCImpDecl.empty())
1321     return Actions.ConvertDeclToDeclGroup(0);
1322   Decl *ImpDecl = PendingObjCImpDecl.pop_back_val();
1323   Actions.ActOnAtEnd(getCurScope(), SourceRange(), ImpDecl);
1324   return Actions.ConvertDeclToDeclGroup(ImpDecl);
1325 }
1326 
1327 ///   compatibility-alias-decl:
1328 ///     @compatibility_alias alias-name  class-name ';'
1329 ///
1330 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1331   assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1332          "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1333   ConsumeToken(); // consume compatibility_alias
1334   if (Tok.isNot(tok::identifier)) {
1335     Diag(Tok, diag::err_expected_ident);
1336     return 0;
1337   }
1338   IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1339   SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1340   if (Tok.isNot(tok::identifier)) {
1341     Diag(Tok, diag::err_expected_ident);
1342     return 0;
1343   }
1344   IdentifierInfo *classId = Tok.getIdentifierInfo();
1345   SourceLocation classLoc = ConsumeToken(); // consume class-name;
1346   if (Tok.isNot(tok::semi)) {
1347     Diag(Tok, diag::err_expected_semi_after) << "@compatibility_alias";
1348     return 0;
1349   }
1350   return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
1351                                         classId, classLoc);
1352 }
1353 
1354 ///   property-synthesis:
1355 ///     @synthesize property-ivar-list ';'
1356 ///
1357 ///   property-ivar-list:
1358 ///     property-ivar
1359 ///     property-ivar-list ',' property-ivar
1360 ///
1361 ///   property-ivar:
1362 ///     identifier
1363 ///     identifier '=' identifier
1364 ///
1365 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1366   assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1367          "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1368   SourceLocation loc = ConsumeToken(); // consume synthesize
1369 
1370   while (true) {
1371     if (Tok.is(tok::code_completion)) {
1372       Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1373       ConsumeCodeCompletionToken();
1374     }
1375 
1376     if (Tok.isNot(tok::identifier)) {
1377       Diag(Tok, diag::err_synthesized_property_name);
1378       SkipUntil(tok::semi);
1379       return 0;
1380     }
1381 
1382     IdentifierInfo *propertyIvar = 0;
1383     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1384     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1385     if (Tok.is(tok::equal)) {
1386       // property '=' ivar-name
1387       ConsumeToken(); // consume '='
1388 
1389       if (Tok.is(tok::code_completion)) {
1390         Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId,
1391                                                        ObjCImpDecl);
1392         ConsumeCodeCompletionToken();
1393       }
1394 
1395       if (Tok.isNot(tok::identifier)) {
1396         Diag(Tok, diag::err_expected_ident);
1397         break;
1398       }
1399       propertyIvar = Tok.getIdentifierInfo();
1400       ConsumeToken(); // consume ivar-name
1401     }
1402     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, ObjCImpDecl,
1403                                   propertyId, propertyIvar);
1404     if (Tok.isNot(tok::comma))
1405       break;
1406     ConsumeToken(); // consume ','
1407   }
1408   if (Tok.isNot(tok::semi)) {
1409     Diag(Tok, diag::err_expected_semi_after) << "@synthesize";
1410     SkipUntil(tok::semi);
1411   }
1412   else
1413     ConsumeToken(); // consume ';'
1414   return 0;
1415 }
1416 
1417 ///   property-dynamic:
1418 ///     @dynamic  property-list
1419 ///
1420 ///   property-list:
1421 ///     identifier
1422 ///     property-list ',' identifier
1423 ///
1424 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1425   assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1426          "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1427   SourceLocation loc = ConsumeToken(); // consume dynamic
1428   while (true) {
1429     if (Tok.is(tok::code_completion)) {
1430       Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1431       ConsumeCodeCompletionToken();
1432     }
1433 
1434     if (Tok.isNot(tok::identifier)) {
1435       Diag(Tok, diag::err_expected_ident);
1436       SkipUntil(tok::semi);
1437       return 0;
1438     }
1439 
1440     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1441     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1442     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, ObjCImpDecl,
1443                                   propertyId, 0);
1444 
1445     if (Tok.isNot(tok::comma))
1446       break;
1447     ConsumeToken(); // consume ','
1448   }
1449   if (Tok.isNot(tok::semi)) {
1450     Diag(Tok, diag::err_expected_semi_after) << "@dynamic";
1451     SkipUntil(tok::semi);
1452   }
1453   else
1454     ConsumeToken(); // consume ';'
1455   return 0;
1456 }
1457 
1458 ///  objc-throw-statement:
1459 ///    throw expression[opt];
1460 ///
1461 Parser::OwningStmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1462   OwningExprResult Res;
1463   ConsumeToken(); // consume throw
1464   if (Tok.isNot(tok::semi)) {
1465     Res = ParseExpression();
1466     if (Res.isInvalid()) {
1467       SkipUntil(tok::semi);
1468       return StmtError();
1469     }
1470   }
1471   // consume ';'
1472   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1473   return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1474 }
1475 
1476 /// objc-synchronized-statement:
1477 ///   @synchronized '(' expression ')' compound-statement
1478 ///
1479 Parser::OwningStmtResult
1480 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1481   ConsumeToken(); // consume synchronized
1482   if (Tok.isNot(tok::l_paren)) {
1483     Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1484     return StmtError();
1485   }
1486   ConsumeParen();  // '('
1487   OwningExprResult Res(ParseExpression());
1488   if (Res.isInvalid()) {
1489     SkipUntil(tok::semi);
1490     return StmtError();
1491   }
1492   if (Tok.isNot(tok::r_paren)) {
1493     Diag(Tok, diag::err_expected_lbrace);
1494     return StmtError();
1495   }
1496   ConsumeParen();  // ')'
1497   if (Tok.isNot(tok::l_brace)) {
1498     Diag(Tok, diag::err_expected_lbrace);
1499     return StmtError();
1500   }
1501   // Enter a scope to hold everything within the compound stmt.  Compound
1502   // statements can always hold declarations.
1503   ParseScope BodyScope(this, Scope::DeclScope);
1504 
1505   OwningStmtResult SynchBody(ParseCompoundStatementBody());
1506 
1507   BodyScope.Exit();
1508   if (SynchBody.isInvalid())
1509     SynchBody = Actions.ActOnNullStmt(Tok.getLocation());
1510   return Actions.ActOnObjCAtSynchronizedStmt(atLoc, Res.take(), SynchBody.take());
1511 }
1512 
1513 ///  objc-try-catch-statement:
1514 ///    @try compound-statement objc-catch-list[opt]
1515 ///    @try compound-statement objc-catch-list[opt] @finally compound-statement
1516 ///
1517 ///  objc-catch-list:
1518 ///    @catch ( parameter-declaration ) compound-statement
1519 ///    objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1520 ///  catch-parameter-declaration:
1521 ///     parameter-declaration
1522 ///     '...' [OBJC2]
1523 ///
1524 Parser::OwningStmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1525   bool catch_or_finally_seen = false;
1526 
1527   ConsumeToken(); // consume try
1528   if (Tok.isNot(tok::l_brace)) {
1529     Diag(Tok, diag::err_expected_lbrace);
1530     return StmtError();
1531   }
1532   StmtVector CatchStmts(Actions);
1533   OwningStmtResult FinallyStmt;
1534   ParseScope TryScope(this, Scope::DeclScope);
1535   OwningStmtResult TryBody(ParseCompoundStatementBody());
1536   TryScope.Exit();
1537   if (TryBody.isInvalid())
1538     TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1539 
1540   while (Tok.is(tok::at)) {
1541     // At this point, we need to lookahead to determine if this @ is the start
1542     // of an @catch or @finally.  We don't want to consume the @ token if this
1543     // is an @try or @encode or something else.
1544     Token AfterAt = GetLookAheadToken(1);
1545     if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1546         !AfterAt.isObjCAtKeyword(tok::objc_finally))
1547       break;
1548 
1549     SourceLocation AtCatchFinallyLoc = ConsumeToken();
1550     if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1551       Decl *FirstPart = 0;
1552       ConsumeToken(); // consume catch
1553       if (Tok.is(tok::l_paren)) {
1554         ConsumeParen();
1555         ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1556         if (Tok.isNot(tok::ellipsis)) {
1557           DeclSpec DS;
1558           ParseDeclarationSpecifiers(DS);
1559           // For some odd reason, the name of the exception variable is
1560           // optional. As a result, we need to use "PrototypeContext", because
1561           // we must accept either 'declarator' or 'abstract-declarator' here.
1562           Declarator ParmDecl(DS, Declarator::PrototypeContext);
1563           ParseDeclarator(ParmDecl);
1564 
1565           // Inform the actions module about the declarator, so it
1566           // gets added to the current scope.
1567           FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1568         } else
1569           ConsumeToken(); // consume '...'
1570 
1571         SourceLocation RParenLoc;
1572 
1573         if (Tok.is(tok::r_paren))
1574           RParenLoc = ConsumeParen();
1575         else // Skip over garbage, until we get to ')'.  Eat the ')'.
1576           SkipUntil(tok::r_paren, true, false);
1577 
1578         OwningStmtResult CatchBody(true);
1579         if (Tok.is(tok::l_brace))
1580           CatchBody = ParseCompoundStatementBody();
1581         else
1582           Diag(Tok, diag::err_expected_lbrace);
1583         if (CatchBody.isInvalid())
1584           CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1585 
1586         OwningStmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1587                                                               RParenLoc,
1588                                                               FirstPart,
1589                                                               CatchBody.take());
1590         if (!Catch.isInvalid())
1591           CatchStmts.push_back(Catch.release());
1592 
1593       } else {
1594         Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1595           << "@catch clause";
1596         return StmtError();
1597       }
1598       catch_or_finally_seen = true;
1599     } else {
1600       assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1601       ConsumeToken(); // consume finally
1602       ParseScope FinallyScope(this, Scope::DeclScope);
1603 
1604       OwningStmtResult FinallyBody(true);
1605       if (Tok.is(tok::l_brace))
1606         FinallyBody = ParseCompoundStatementBody();
1607       else
1608         Diag(Tok, diag::err_expected_lbrace);
1609       if (FinallyBody.isInvalid())
1610         FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1611       FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1612                                                    FinallyBody.take());
1613       catch_or_finally_seen = true;
1614       break;
1615     }
1616   }
1617   if (!catch_or_finally_seen) {
1618     Diag(atLoc, diag::err_missing_catch_finally);
1619     return StmtError();
1620   }
1621 
1622   return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1623                                     move_arg(CatchStmts),
1624                                     FinallyStmt.take());
1625 }
1626 
1627 ///   objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1628 ///
1629 Decl *Parser::ParseObjCMethodDefinition() {
1630   Decl *MDecl = ParseObjCMethodPrototype(ObjCImpDecl);
1631 
1632   PrettyStackTraceActionsDecl CrashInfo(MDecl, Tok.getLocation(), Actions,
1633                                         PP.getSourceManager(),
1634                                         "parsing Objective-C method");
1635 
1636   // parse optional ';'
1637   if (Tok.is(tok::semi)) {
1638     if (ObjCImpDecl) {
1639       Diag(Tok, diag::warn_semicolon_before_method_body)
1640         << FixItHint::CreateRemoval(Tok.getLocation());
1641     }
1642     ConsumeToken();
1643   }
1644 
1645   // We should have an opening brace now.
1646   if (Tok.isNot(tok::l_brace)) {
1647     Diag(Tok, diag::err_expected_method_body);
1648 
1649     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1650     SkipUntil(tok::l_brace, true, true);
1651 
1652     // If we didn't find the '{', bail out.
1653     if (Tok.isNot(tok::l_brace))
1654       return 0;
1655   }
1656   SourceLocation BraceLoc = Tok.getLocation();
1657 
1658   // Enter a scope for the method body.
1659   ParseScope BodyScope(this,
1660                        Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
1661 
1662   // Tell the actions module that we have entered a method definition with the
1663   // specified Declarator for the method.
1664   Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
1665 
1666   OwningStmtResult FnBody(ParseCompoundStatementBody());
1667 
1668   // If the function body could not be parsed, make a bogus compoundstmt.
1669   if (FnBody.isInvalid())
1670     FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
1671                                        MultiStmtArg(Actions), false);
1672 
1673   // TODO: Pass argument information.
1674   Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
1675 
1676   // Leave the function body scope.
1677   BodyScope.Exit();
1678 
1679   return MDecl;
1680 }
1681 
1682 Parser::OwningStmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
1683   if (Tok.is(tok::code_completion)) {
1684     Actions.CodeCompleteObjCAtStatement(getCurScope());
1685     ConsumeCodeCompletionToken();
1686     return StmtError();
1687   }
1688 
1689   if (Tok.isObjCAtKeyword(tok::objc_try))
1690     return ParseObjCTryStmt(AtLoc);
1691 
1692   if (Tok.isObjCAtKeyword(tok::objc_throw))
1693     return ParseObjCThrowStmt(AtLoc);
1694 
1695   if (Tok.isObjCAtKeyword(tok::objc_synchronized))
1696     return ParseObjCSynchronizedStmt(AtLoc);
1697 
1698   OwningExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
1699   if (Res.isInvalid()) {
1700     // If the expression is invalid, skip ahead to the next semicolon. Not
1701     // doing this opens us up to the possibility of infinite loops if
1702     // ParseExpression does not consume any tokens.
1703     SkipUntil(tok::semi);
1704     return StmtError();
1705   }
1706 
1707   // Otherwise, eat the semicolon.
1708   ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
1709   return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
1710 }
1711 
1712 Parser::OwningExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
1713   switch (Tok.getKind()) {
1714   case tok::code_completion:
1715     Actions.CodeCompleteObjCAtExpression(getCurScope());
1716     ConsumeCodeCompletionToken();
1717     return ExprError();
1718 
1719   case tok::string_literal:    // primary-expression: string-literal
1720   case tok::wide_string_literal:
1721     return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
1722   default:
1723     if (Tok.getIdentifierInfo() == 0)
1724       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1725 
1726     switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
1727     case tok::objc_encode:
1728       return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
1729     case tok::objc_protocol:
1730       return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
1731     case tok::objc_selector:
1732       return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
1733     default:
1734       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1735     }
1736   }
1737 }
1738 
1739 /// \brirg Parse the receiver of an Objective-C++ message send.
1740 ///
1741 /// This routine parses the receiver of a message send in
1742 /// Objective-C++ either as a type or as an expression. Note that this
1743 /// routine must not be called to parse a send to 'super', since it
1744 /// has no way to return such a result.
1745 ///
1746 /// \param IsExpr Whether the receiver was parsed as an expression.
1747 ///
1748 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
1749 /// IsExpr is true), the parsed expression. If the receiver was parsed
1750 /// as a type (\c IsExpr is false), the parsed type.
1751 ///
1752 /// \returns True if an error occurred during parsing or semantic
1753 /// analysis, in which case the arguments do not have valid
1754 /// values. Otherwise, returns false for a successful parse.
1755 ///
1756 ///   objc-receiver: [C++]
1757 ///     'super' [not parsed here]
1758 ///     expression
1759 ///     simple-type-specifier
1760 ///     typename-specifier
1761 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
1762   if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1763       Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
1764     TryAnnotateTypeOrScopeToken();
1765 
1766   if (!isCXXSimpleTypeSpecifier()) {
1767     //   objc-receiver:
1768     //     expression
1769     OwningExprResult Receiver = ParseExpression();
1770     if (Receiver.isInvalid())
1771       return true;
1772 
1773     IsExpr = true;
1774     TypeOrExpr = Receiver.take();
1775     return false;
1776   }
1777 
1778   // objc-receiver:
1779   //   typename-specifier
1780   //   simple-type-specifier
1781   //   expression (that starts with one of the above)
1782   DeclSpec DS;
1783   ParseCXXSimpleTypeSpecifier(DS);
1784 
1785   if (Tok.is(tok::l_paren)) {
1786     // If we see an opening parentheses at this point, we are
1787     // actually parsing an expression that starts with a
1788     // function-style cast, e.g.,
1789     //
1790     //   postfix-expression:
1791     //     simple-type-specifier ( expression-list [opt] )
1792     //     typename-specifier ( expression-list [opt] )
1793     //
1794     // Parse the remainder of this case, then the (optional)
1795     // postfix-expression suffix, followed by the (optional)
1796     // right-hand side of the binary expression. We have an
1797     // instance method.
1798     OwningExprResult Receiver = ParseCXXTypeConstructExpression(DS);
1799     if (!Receiver.isInvalid())
1800       Receiver = ParsePostfixExpressionSuffix(Receiver.take());
1801     if (!Receiver.isInvalid())
1802       Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
1803     if (Receiver.isInvalid())
1804       return true;
1805 
1806     IsExpr = true;
1807     TypeOrExpr = Receiver.take();
1808     return false;
1809   }
1810 
1811   // We have a class message. Turn the simple-type-specifier or
1812   // typename-specifier we parsed into a type and parse the
1813   // remainder of the class message.
1814   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1815   TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1816   if (Type.isInvalid())
1817     return true;
1818 
1819   IsExpr = false;
1820   TypeOrExpr = Type.get();
1821   return false;
1822 }
1823 
1824 /// \brief Determine whether the parser is currently referring to a an
1825 /// Objective-C message send, using a simplified heuristic to avoid overhead.
1826 ///
1827 /// This routine will only return true for a subset of valid message-send
1828 /// expressions.
1829 bool Parser::isSimpleObjCMessageExpression() {
1830   assert(Tok.is(tok::l_square) && getLang().ObjC1 &&
1831          "Incorrect start for isSimpleObjCMessageExpression");
1832   return GetLookAheadToken(1).is(tok::identifier) &&
1833          GetLookAheadToken(2).is(tok::identifier);
1834 }
1835 
1836 ///   objc-message-expr:
1837 ///     '[' objc-receiver objc-message-args ']'
1838 ///
1839 ///   objc-receiver: [C]
1840 ///     'super'
1841 ///     expression
1842 ///     class-name
1843 ///     type-name
1844 ///
1845 Parser::OwningExprResult Parser::ParseObjCMessageExpression() {
1846   assert(Tok.is(tok::l_square) && "'[' expected");
1847   SourceLocation LBracLoc = ConsumeBracket(); // consume '['
1848 
1849   if (Tok.is(tok::code_completion)) {
1850     Actions.CodeCompleteObjCMessageReceiver(getCurScope());
1851     ConsumeCodeCompletionToken();
1852     SkipUntil(tok::r_square);
1853     return ExprError();
1854   }
1855 
1856   if (getLang().CPlusPlus) {
1857     // We completely separate the C and C++ cases because C++ requires
1858     // more complicated (read: slower) parsing.
1859 
1860     // Handle send to super.
1861     // FIXME: This doesn't benefit from the same typo-correction we
1862     // get in Objective-C.
1863     if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
1864         NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
1865       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 0,
1866                                             0);
1867 
1868     // Parse the receiver, which is either a type or an expression.
1869     bool IsExpr;
1870     void *TypeOrExpr;
1871     if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
1872       SkipUntil(tok::r_square);
1873       return ExprError();
1874     }
1875 
1876     if (IsExpr)
1877       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 0,
1878                                             static_cast<Expr*>(TypeOrExpr));
1879 
1880     return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1881                                           TypeOrExpr, 0);
1882   }
1883 
1884   if (Tok.is(tok::identifier)) {
1885     IdentifierInfo *Name = Tok.getIdentifierInfo();
1886     SourceLocation NameLoc = Tok.getLocation();
1887     TypeTy *ReceiverType;
1888     switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
1889                                        Name == Ident_super,
1890                                        NextToken().is(tok::period),
1891                                        ReceiverType)) {
1892     case Action::ObjCSuperMessage:
1893       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), 0, 0);
1894 
1895     case Action::ObjCClassMessage:
1896       if (!ReceiverType) {
1897         SkipUntil(tok::r_square);
1898         return ExprError();
1899       }
1900 
1901       ConsumeToken(); // the type name
1902 
1903       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1904                                             ReceiverType, 0);
1905 
1906     case Action::ObjCInstanceMessage:
1907       // Fall through to parse an expression.
1908       break;
1909     }
1910   }
1911 
1912   // Otherwise, an arbitrary expression can be the receiver of a send.
1913   OwningExprResult Res(ParseExpression());
1914   if (Res.isInvalid()) {
1915     SkipUntil(tok::r_square);
1916     return move(Res);
1917   }
1918 
1919   return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 0,
1920                                         Res.take());
1921 }
1922 
1923 /// \brief Parse the remainder of an Objective-C message following the
1924 /// '[' objc-receiver.
1925 ///
1926 /// This routine handles sends to super, class messages (sent to a
1927 /// class name), and instance messages (sent to an object), and the
1928 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
1929 /// ReceiverExpr, respectively. Only one of these parameters may have
1930 /// a valid value.
1931 ///
1932 /// \param LBracLoc The location of the opening '['.
1933 ///
1934 /// \param SuperLoc If this is a send to 'super', the location of the
1935 /// 'super' keyword that indicates a send to the superclass.
1936 ///
1937 /// \param ReceiverType If this is a class message, the type of the
1938 /// class we are sending a message to.
1939 ///
1940 /// \param ReceiverExpr If this is an instance message, the expression
1941 /// used to compute the receiver object.
1942 ///
1943 ///   objc-message-args:
1944 ///     objc-selector
1945 ///     objc-keywordarg-list
1946 ///
1947 ///   objc-keywordarg-list:
1948 ///     objc-keywordarg
1949 ///     objc-keywordarg-list objc-keywordarg
1950 ///
1951 ///   objc-keywordarg:
1952 ///     selector-name[opt] ':' objc-keywordexpr
1953 ///
1954 ///   objc-keywordexpr:
1955 ///     nonempty-expr-list
1956 ///
1957 ///   nonempty-expr-list:
1958 ///     assignment-expression
1959 ///     nonempty-expr-list , assignment-expression
1960 ///
1961 Parser::OwningExprResult
1962 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
1963                                        SourceLocation SuperLoc,
1964                                        TypeTy *ReceiverType,
1965                                        ExprArg ReceiverExpr) {
1966   if (Tok.is(tok::code_completion)) {
1967     if (SuperLoc.isValid())
1968       Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0);
1969     else if (ReceiverType)
1970       Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0);
1971     else
1972       Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
1973                                               0, 0);
1974     ConsumeCodeCompletionToken();
1975   }
1976 
1977   // Parse objc-selector
1978   SourceLocation Loc;
1979   IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
1980 
1981   SourceLocation SelectorLoc = Loc;
1982 
1983   llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
1984   ExprVector KeyExprs(Actions);
1985 
1986   if (Tok.is(tok::colon)) {
1987     while (1) {
1988       // Each iteration parses a single keyword argument.
1989       KeyIdents.push_back(selIdent);
1990 
1991       if (Tok.isNot(tok::colon)) {
1992         Diag(Tok, diag::err_expected_colon);
1993         // We must manually skip to a ']', otherwise the expression skipper will
1994         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
1995         // the enclosing expression.
1996         SkipUntil(tok::r_square);
1997         return ExprError();
1998       }
1999 
2000       ConsumeToken(); // Eat the ':'.
2001       ///  Parse the expression after ':'
2002       OwningExprResult Res(ParseAssignmentExpression());
2003       if (Res.isInvalid()) {
2004         // We must manually skip to a ']', otherwise the expression skipper will
2005         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2006         // the enclosing expression.
2007         SkipUntil(tok::r_square);
2008         return move(Res);
2009       }
2010 
2011       // We have a valid expression.
2012       KeyExprs.push_back(Res.release());
2013 
2014       // Code completion after each argument.
2015       if (Tok.is(tok::code_completion)) {
2016         if (SuperLoc.isValid())
2017           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2018                                                KeyIdents.data(),
2019                                                KeyIdents.size());
2020         else if (ReceiverType)
2021           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2022                                                KeyIdents.data(),
2023                                                KeyIdents.size());
2024         else
2025           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2026                                                   KeyIdents.data(),
2027                                                   KeyIdents.size());
2028         ConsumeCodeCompletionToken();
2029       }
2030 
2031       // Check for another keyword selector.
2032       selIdent = ParseObjCSelectorPiece(Loc);
2033       if (!selIdent && Tok.isNot(tok::colon))
2034         break;
2035       // We have a selector or a colon, continue parsing.
2036     }
2037     // Parse the, optional, argument list, comma separated.
2038     while (Tok.is(tok::comma)) {
2039       ConsumeToken(); // Eat the ','.
2040       ///  Parse the expression after ','
2041       OwningExprResult Res(ParseAssignmentExpression());
2042       if (Res.isInvalid()) {
2043         // We must manually skip to a ']', otherwise the expression skipper will
2044         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2045         // the enclosing expression.
2046         SkipUntil(tok::r_square);
2047         return move(Res);
2048       }
2049 
2050       // We have a valid expression.
2051       KeyExprs.push_back(Res.release());
2052     }
2053   } else if (!selIdent) {
2054     Diag(Tok, diag::err_expected_ident); // missing selector name.
2055 
2056     // We must manually skip to a ']', otherwise the expression skipper will
2057     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2058     // the enclosing expression.
2059     SkipUntil(tok::r_square);
2060     return ExprError();
2061   }
2062 
2063   if (Tok.isNot(tok::r_square)) {
2064     if (Tok.is(tok::identifier))
2065       Diag(Tok, diag::err_expected_colon);
2066     else
2067       Diag(Tok, diag::err_expected_rsquare);
2068     // We must manually skip to a ']', otherwise the expression skipper will
2069     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2070     // the enclosing expression.
2071     SkipUntil(tok::r_square);
2072     return ExprError();
2073   }
2074 
2075   SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2076 
2077   unsigned nKeys = KeyIdents.size();
2078   if (nKeys == 0)
2079     KeyIdents.push_back(selIdent);
2080   Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2081 
2082   if (SuperLoc.isValid())
2083     return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2084                                      LBracLoc, SelectorLoc, RBracLoc,
2085                                      Action::MultiExprArg(Actions,
2086                                                           KeyExprs.take(),
2087                                                           KeyExprs.size()));
2088   else if (ReceiverType)
2089     return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2090                                      LBracLoc, SelectorLoc, RBracLoc,
2091                                      Action::MultiExprArg(Actions,
2092                                                           KeyExprs.take(),
2093                                                           KeyExprs.size()));
2094   return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2095                                       LBracLoc, SelectorLoc, RBracLoc,
2096                                       Action::MultiExprArg(Actions,
2097                                                            KeyExprs.take(),
2098                                                            KeyExprs.size()));
2099 }
2100 
2101 Parser::OwningExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2102   OwningExprResult Res(ParseStringLiteralExpression());
2103   if (Res.isInvalid()) return move(Res);
2104 
2105   // @"foo" @"bar" is a valid concatenated string.  Eat any subsequent string
2106   // expressions.  At this point, we know that the only valid thing that starts
2107   // with '@' is an @"".
2108   llvm::SmallVector<SourceLocation, 4> AtLocs;
2109   ExprVector AtStrings(Actions);
2110   AtLocs.push_back(AtLoc);
2111   AtStrings.push_back(Res.release());
2112 
2113   while (Tok.is(tok::at)) {
2114     AtLocs.push_back(ConsumeToken()); // eat the @.
2115 
2116     // Invalid unless there is a string literal.
2117     if (!isTokenStringLiteral())
2118       return ExprError(Diag(Tok, diag::err_objc_concat_string));
2119 
2120     OwningExprResult Lit(ParseStringLiteralExpression());
2121     if (Lit.isInvalid())
2122       return move(Lit);
2123 
2124     AtStrings.push_back(Lit.release());
2125   }
2126 
2127   return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
2128                                               AtStrings.size()));
2129 }
2130 
2131 ///    objc-encode-expression:
2132 ///      @encode ( type-name )
2133 Parser::OwningExprResult
2134 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2135   assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2136 
2137   SourceLocation EncLoc = ConsumeToken();
2138 
2139   if (Tok.isNot(tok::l_paren))
2140     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2141 
2142   SourceLocation LParenLoc = ConsumeParen();
2143 
2144   TypeResult Ty = ParseTypeName();
2145 
2146   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2147 
2148   if (Ty.isInvalid())
2149     return ExprError();
2150 
2151   return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc,
2152                                                  Ty.get(), RParenLoc));
2153 }
2154 
2155 ///     objc-protocol-expression
2156 ///       @protocol ( protocol-name )
2157 Parser::OwningExprResult
2158 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2159   SourceLocation ProtoLoc = ConsumeToken();
2160 
2161   if (Tok.isNot(tok::l_paren))
2162     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2163 
2164   SourceLocation LParenLoc = ConsumeParen();
2165 
2166   if (Tok.isNot(tok::identifier))
2167     return ExprError(Diag(Tok, diag::err_expected_ident));
2168 
2169   IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2170   ConsumeToken();
2171 
2172   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2173 
2174   return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2175                                                    LParenLoc, RParenLoc));
2176 }
2177 
2178 ///     objc-selector-expression
2179 ///       @selector '(' objc-keyword-selector ')'
2180 Parser::OwningExprResult
2181 Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2182   SourceLocation SelectorLoc = ConsumeToken();
2183 
2184   if (Tok.isNot(tok::l_paren))
2185     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2186 
2187   llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
2188   SourceLocation LParenLoc = ConsumeParen();
2189   SourceLocation sLoc;
2190   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2191   if (!SelIdent && Tok.isNot(tok::colon)) // missing selector name.
2192     return ExprError(Diag(Tok, diag::err_expected_ident));
2193 
2194   KeyIdents.push_back(SelIdent);
2195   unsigned nColons = 0;
2196   if (Tok.isNot(tok::r_paren)) {
2197     while (1) {
2198       if (Tok.isNot(tok::colon))
2199         return ExprError(Diag(Tok, diag::err_expected_colon));
2200 
2201       nColons++;
2202       ConsumeToken(); // Eat the ':'.
2203       if (Tok.is(tok::r_paren))
2204         break;
2205       // Check for another keyword selector.
2206       SourceLocation Loc;
2207       SelIdent = ParseObjCSelectorPiece(Loc);
2208       KeyIdents.push_back(SelIdent);
2209       if (!SelIdent && Tok.isNot(tok::colon))
2210         break;
2211     }
2212   }
2213   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2214   Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2215   return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2216                                                    LParenLoc, RParenLoc));
2217  }
2218