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