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