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