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