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