]> granicus.if.org Git - clang/blob - lib/Parse/ParseObjc.cpp
[index] Objective-C method declarations and message sends with
[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::colon:
1011     // Empty selector piece uses the location of the ':'.
1012     SelectorLoc = Tok.getLocation();
1013     return nullptr;
1014   case tok::ampamp:
1015   case tok::ampequal:
1016   case tok::amp:
1017   case tok::pipe:
1018   case tok::tilde:
1019   case tok::exclaim:
1020   case tok::exclaimequal:
1021   case tok::pipepipe:
1022   case tok::pipeequal:
1023   case tok::caret:
1024   case tok::caretequal: {
1025     std::string ThisTok(PP.getSpelling(Tok));
1026     if (isLetter(ThisTok[0])) {
1027       IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1028       Tok.setKind(tok::identifier);
1029       SelectorLoc = ConsumeToken();
1030       return II;
1031     }
1032     return nullptr;
1033   }
1034       
1035   case tok::identifier:
1036   case tok::kw_asm:
1037   case tok::kw_auto:
1038   case tok::kw_bool:
1039   case tok::kw_break:
1040   case tok::kw_case:
1041   case tok::kw_catch:
1042   case tok::kw_char:
1043   case tok::kw_class:
1044   case tok::kw_const:
1045   case tok::kw_const_cast:
1046   case tok::kw_continue:
1047   case tok::kw_default:
1048   case tok::kw_delete:
1049   case tok::kw_do:
1050   case tok::kw_double:
1051   case tok::kw_dynamic_cast:
1052   case tok::kw_else:
1053   case tok::kw_enum:
1054   case tok::kw_explicit:
1055   case tok::kw_export:
1056   case tok::kw_extern:
1057   case tok::kw_false:
1058   case tok::kw_float:
1059   case tok::kw_for:
1060   case tok::kw_friend:
1061   case tok::kw_goto:
1062   case tok::kw_if:
1063   case tok::kw_inline:
1064   case tok::kw_int:
1065   case tok::kw_long:
1066   case tok::kw_mutable:
1067   case tok::kw_namespace:
1068   case tok::kw_new:
1069   case tok::kw_operator:
1070   case tok::kw_private:
1071   case tok::kw_protected:
1072   case tok::kw_public:
1073   case tok::kw_register:
1074   case tok::kw_reinterpret_cast:
1075   case tok::kw_restrict:
1076   case tok::kw_return:
1077   case tok::kw_short:
1078   case tok::kw_signed:
1079   case tok::kw_sizeof:
1080   case tok::kw_static:
1081   case tok::kw_static_cast:
1082   case tok::kw_struct:
1083   case tok::kw_switch:
1084   case tok::kw_template:
1085   case tok::kw_this:
1086   case tok::kw_throw:
1087   case tok::kw_true:
1088   case tok::kw_try:
1089   case tok::kw_typedef:
1090   case tok::kw_typeid:
1091   case tok::kw_typename:
1092   case tok::kw_typeof:
1093   case tok::kw_union:
1094   case tok::kw_unsigned:
1095   case tok::kw_using:
1096   case tok::kw_virtual:
1097   case tok::kw_void:
1098   case tok::kw_volatile:
1099   case tok::kw_wchar_t:
1100   case tok::kw_while:
1101   case tok::kw__Bool:
1102   case tok::kw__Complex:
1103   case tok::kw___alignof:
1104   case tok::kw___auto_type:
1105     IdentifierInfo *II = Tok.getIdentifierInfo();
1106     SelectorLoc = ConsumeToken();
1107     return II;
1108   }
1109 }
1110
1111 ///  objc-for-collection-in: 'in'
1112 ///
1113 bool Parser::isTokIdentifier_in() const {
1114   // FIXME: May have to do additional look-ahead to only allow for
1115   // valid tokens following an 'in'; such as an identifier, unary operators,
1116   // '[' etc.
1117   return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
1118           Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1119 }
1120
1121 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1122 /// qualifier list and builds their bitmask representation in the input
1123 /// argument.
1124 ///
1125 ///   objc-type-qualifiers:
1126 ///     objc-type-qualifier
1127 ///     objc-type-qualifiers objc-type-qualifier
1128 ///
1129 ///   objc-type-qualifier:
1130 ///     'in'
1131 ///     'out'
1132 ///     'inout'
1133 ///     'oneway'
1134 ///     'bycopy'
1135 ///     'byref'
1136 ///     'nonnull'
1137 ///     'nullable'
1138 ///     'null_unspecified'
1139 ///
1140 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1141                                         Declarator::TheContext Context) {
1142   assert(Context == Declarator::ObjCParameterContext ||
1143          Context == Declarator::ObjCResultContext);
1144
1145   while (1) {
1146     if (Tok.is(tok::code_completion)) {
1147       Actions.CodeCompleteObjCPassingType(getCurScope(), DS, 
1148                           Context == Declarator::ObjCParameterContext);
1149       return cutOffParsing();
1150     }
1151     
1152     if (Tok.isNot(tok::identifier))
1153       return;
1154
1155     const IdentifierInfo *II = Tok.getIdentifierInfo();
1156     for (unsigned i = 0; i != objc_NumQuals; ++i) {
1157       if (II != ObjCTypeQuals[i] ||
1158           NextToken().is(tok::less) ||
1159           NextToken().is(tok::coloncolon))
1160         continue;
1161
1162       ObjCDeclSpec::ObjCDeclQualifier Qual;
1163       NullabilityKind Nullability;
1164       switch (i) {
1165       default: llvm_unreachable("Unknown decl qualifier");
1166       case objc_in:     Qual = ObjCDeclSpec::DQ_In; break;
1167       case objc_out:    Qual = ObjCDeclSpec::DQ_Out; break;
1168       case objc_inout:  Qual = ObjCDeclSpec::DQ_Inout; break;
1169       case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1170       case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1171       case objc_byref:  Qual = ObjCDeclSpec::DQ_Byref; break;
1172
1173       case objc_nonnull: 
1174         Qual = ObjCDeclSpec::DQ_CSNullability;
1175         Nullability = NullabilityKind::NonNull;
1176         break;
1177
1178       case objc_nullable: 
1179         Qual = ObjCDeclSpec::DQ_CSNullability;
1180         Nullability = NullabilityKind::Nullable;
1181         break;
1182
1183       case objc_null_unspecified: 
1184         Qual = ObjCDeclSpec::DQ_CSNullability;
1185         Nullability = NullabilityKind::Unspecified;
1186         break;
1187       }
1188
1189       // FIXME: Diagnose redundant specifiers.
1190       DS.setObjCDeclQualifier(Qual);
1191       if (Qual == ObjCDeclSpec::DQ_CSNullability)
1192         DS.setNullability(Tok.getLocation(), Nullability);
1193
1194       ConsumeToken();
1195       II = nullptr;
1196       break;
1197     }
1198
1199     // If this wasn't a recognized qualifier, bail out.
1200     if (II) return;
1201   }
1202 }
1203
1204 /// Take all the decl attributes out of the given list and add
1205 /// them to the given attribute set.
1206 static void takeDeclAttributes(ParsedAttributes &attrs,
1207                                AttributeList *list) {
1208   while (list) {
1209     AttributeList *cur = list;
1210     list = cur->getNext();
1211
1212     if (!cur->isUsedAsTypeAttr()) {
1213       // Clear out the next pointer.  We're really completely
1214       // destroying the internal invariants of the declarator here,
1215       // but it doesn't matter because we're done with it.
1216       cur->setNext(nullptr);
1217       attrs.add(cur);
1218     }
1219   }
1220 }
1221
1222 /// takeDeclAttributes - Take all the decl attributes from the given
1223 /// declarator and add them to the given list.
1224 static void takeDeclAttributes(ParsedAttributes &attrs,
1225                                Declarator &D) {
1226   // First, take ownership of all attributes.
1227   attrs.getPool().takeAllFrom(D.getAttributePool());
1228   attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1229
1230   // Now actually move the attributes over.
1231   takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
1232   takeDeclAttributes(attrs, D.getAttributes());
1233   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1234     takeDeclAttributes(attrs,
1235                   const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
1236 }
1237
1238 ///   objc-type-name:
1239 ///     '(' objc-type-qualifiers[opt] type-name ')'
1240 ///     '(' objc-type-qualifiers[opt] ')'
1241 ///
1242 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, 
1243                                      Declarator::TheContext context,
1244                                      ParsedAttributes *paramAttrs) {
1245   assert(context == Declarator::ObjCParameterContext ||
1246          context == Declarator::ObjCResultContext);
1247   assert((paramAttrs != nullptr) ==
1248          (context == Declarator::ObjCParameterContext));
1249
1250   assert(Tok.is(tok::l_paren) && "expected (");
1251
1252   BalancedDelimiterTracker T(*this, tok::l_paren);
1253   T.consumeOpen();
1254
1255   SourceLocation TypeStartLoc = Tok.getLocation();
1256   ObjCDeclContextSwitch ObjCDC(*this);
1257
1258   // Parse type qualifiers, in, inout, etc.
1259   ParseObjCTypeQualifierList(DS, context);
1260
1261   ParsedType Ty;
1262   if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1263     // Parse an abstract declarator.
1264     DeclSpec declSpec(AttrFactory);
1265     declSpec.setObjCQualifiers(&DS);
1266     DeclSpecContext dsContext = DSC_normal;
1267     if (context == Declarator::ObjCResultContext)
1268       dsContext = DSC_objc_method_result;
1269     ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1270     Declarator declarator(declSpec, context);
1271     ParseDeclarator(declarator);
1272
1273     // If that's not invalid, extract a type.
1274     if (!declarator.isInvalidType()) {
1275       // Map a nullability specifier to a context-sensitive keyword attribute.
1276       bool addedToDeclSpec = false;
1277       if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1278         addContextSensitiveTypeNullability(*this, declarator,
1279                                            DS.getNullability(),
1280                                            DS.getNullabilityLoc(),
1281                                            addedToDeclSpec);
1282
1283       TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1284       if (!type.isInvalid())
1285         Ty = type.get();
1286
1287       // If we're parsing a parameter, steal all the decl attributes
1288       // and add them to the decl spec.
1289       if (context == Declarator::ObjCParameterContext)
1290         takeDeclAttributes(*paramAttrs, declarator);
1291     }
1292   }
1293
1294   if (Tok.is(tok::r_paren))
1295     T.consumeClose();
1296   else if (Tok.getLocation() == TypeStartLoc) {
1297     // If we didn't eat any tokens, then this isn't a type.
1298     Diag(Tok, diag::err_expected_type);
1299     SkipUntil(tok::r_paren, StopAtSemi);
1300   } else {
1301     // Otherwise, we found *something*, but didn't get a ')' in the right
1302     // place.  Emit an error then return what we have as the type.
1303     T.consumeClose();
1304   }
1305   return Ty;
1306 }
1307
1308 ///   objc-method-decl:
1309 ///     objc-selector
1310 ///     objc-keyword-selector objc-parmlist[opt]
1311 ///     objc-type-name objc-selector
1312 ///     objc-type-name objc-keyword-selector objc-parmlist[opt]
1313 ///
1314 ///   objc-keyword-selector:
1315 ///     objc-keyword-decl
1316 ///     objc-keyword-selector objc-keyword-decl
1317 ///
1318 ///   objc-keyword-decl:
1319 ///     objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1320 ///     objc-selector ':' objc-keyword-attributes[opt] identifier
1321 ///     ':' objc-type-name objc-keyword-attributes[opt] identifier
1322 ///     ':' objc-keyword-attributes[opt] identifier
1323 ///
1324 ///   objc-parmlist:
1325 ///     objc-parms objc-ellipsis[opt]
1326 ///
1327 ///   objc-parms:
1328 ///     objc-parms , parameter-declaration
1329 ///
1330 ///   objc-ellipsis:
1331 ///     , ...
1332 ///
1333 ///   objc-keyword-attributes:         [OBJC2]
1334 ///     __attribute__((unused))
1335 ///
1336 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1337                                   tok::TokenKind mType,
1338                                   tok::ObjCKeywordKind MethodImplKind,
1339                                   bool MethodDefinition) {
1340   ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1341
1342   if (Tok.is(tok::code_completion)) {
1343     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1344                                        /*ReturnType=*/nullptr);
1345     cutOffParsing();
1346     return nullptr;
1347   }
1348
1349   // Parse the return type if present.
1350   ParsedType ReturnType;
1351   ObjCDeclSpec DSRet;
1352   if (Tok.is(tok::l_paren))
1353     ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext,
1354                                    nullptr);
1355
1356   // If attributes exist before the method, parse them.
1357   ParsedAttributes methodAttrs(AttrFactory);
1358   if (getLangOpts().ObjC2)
1359     MaybeParseGNUAttributes(methodAttrs);
1360
1361   if (Tok.is(tok::code_completion)) {
1362     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 
1363                                        ReturnType);
1364     cutOffParsing();
1365     return nullptr;
1366   }
1367
1368   // Now parse the selector.
1369   SourceLocation selLoc;
1370   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1371
1372   // An unnamed colon is valid.
1373   if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1374     Diag(Tok, diag::err_expected_selector_for_method)
1375       << SourceRange(mLoc, Tok.getLocation());
1376     // Skip until we get a ; or @.
1377     SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1378     return nullptr;
1379   }
1380
1381   SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1382   if (Tok.isNot(tok::colon)) {
1383     // If attributes exist after the method, parse them.
1384     if (getLangOpts().ObjC2)
1385       MaybeParseGNUAttributes(methodAttrs);
1386
1387     Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1388     Decl *Result
1389          = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1390                                           mType, DSRet, ReturnType, 
1391                                           selLoc, Sel, nullptr,
1392                                           CParamInfo.data(), CParamInfo.size(),
1393                                           methodAttrs.getList(), MethodImplKind,
1394                                           false, MethodDefinition);
1395     PD.complete(Result);
1396     return Result;
1397   }
1398
1399   SmallVector<IdentifierInfo *, 12> KeyIdents;
1400   SmallVector<SourceLocation, 12> KeyLocs;
1401   SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1402   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1403                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1404
1405   AttributePool allParamAttrs(AttrFactory);
1406   while (1) {
1407     ParsedAttributes paramAttrs(AttrFactory);
1408     Sema::ObjCArgInfo ArgInfo;
1409
1410     // Each iteration parses a single keyword argument.
1411     if (ExpectAndConsume(tok::colon))
1412       break;
1413
1414     ArgInfo.Type = nullptr;
1415     if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1416       ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1417                                        Declarator::ObjCParameterContext,
1418                                        &paramAttrs);
1419
1420     // If attributes exist before the argument name, parse them.
1421     // Regardless, collect all the attributes we've parsed so far.
1422     ArgInfo.ArgAttrs = nullptr;
1423     if (getLangOpts().ObjC2) {
1424       MaybeParseGNUAttributes(paramAttrs);
1425       ArgInfo.ArgAttrs = paramAttrs.getList();
1426     }
1427
1428     // Code completion for the next piece of the selector.
1429     if (Tok.is(tok::code_completion)) {
1430       KeyIdents.push_back(SelIdent);
1431       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 
1432                                                  mType == tok::minus,
1433                                                  /*AtParameterName=*/true,
1434                                                  ReturnType, KeyIdents);
1435       cutOffParsing();
1436       return nullptr;
1437     }
1438
1439     if (expectIdentifier())
1440       break; // missing argument name.
1441
1442     ArgInfo.Name = Tok.getIdentifierInfo();
1443     ArgInfo.NameLoc = Tok.getLocation();
1444     ConsumeToken(); // Eat the identifier.
1445
1446     ArgInfos.push_back(ArgInfo);
1447     KeyIdents.push_back(SelIdent);
1448     KeyLocs.push_back(selLoc);
1449
1450     // Make sure the attributes persist.
1451     allParamAttrs.takeAllFrom(paramAttrs.getPool());
1452
1453     // Code completion for the next piece of the selector.
1454     if (Tok.is(tok::code_completion)) {
1455       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 
1456                                                  mType == tok::minus,
1457                                                  /*AtParameterName=*/false,
1458                                                  ReturnType, KeyIdents);
1459       cutOffParsing();
1460       return nullptr;
1461     }
1462     
1463     // Check for another keyword selector.
1464     SelIdent = ParseObjCSelectorPiece(selLoc);
1465     if (!SelIdent && Tok.isNot(tok::colon))
1466       break;
1467     if (!SelIdent) {
1468       SourceLocation ColonLoc = Tok.getLocation();
1469       if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1470         Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1471         Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1472         Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1473       }
1474     }
1475     // We have a selector or a colon, continue parsing.
1476   }
1477
1478   bool isVariadic = false;
1479   bool cStyleParamWarned = false;
1480   // Parse the (optional) parameter list.
1481   while (Tok.is(tok::comma)) {
1482     ConsumeToken();
1483     if (Tok.is(tok::ellipsis)) {
1484       isVariadic = true;
1485       ConsumeToken();
1486       break;
1487     }
1488     if (!cStyleParamWarned) {
1489       Diag(Tok, diag::warn_cstyle_param);
1490       cStyleParamWarned = true;
1491     }
1492     DeclSpec DS(AttrFactory);
1493     ParseDeclarationSpecifiers(DS);
1494     // Parse the declarator.
1495     Declarator ParmDecl(DS, Declarator::PrototypeContext);
1496     ParseDeclarator(ParmDecl);
1497     IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1498     Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1499     CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1500                                                     ParmDecl.getIdentifierLoc(), 
1501                                                     Param,
1502                                                     nullptr));
1503   }
1504
1505   // FIXME: Add support for optional parameter list...
1506   // If attributes exist after the method, parse them.
1507   if (getLangOpts().ObjC2)
1508     MaybeParseGNUAttributes(methodAttrs);
1509   
1510   if (KeyIdents.size() == 0)
1511     return nullptr;
1512
1513   Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1514                                                    &KeyIdents[0]);
1515   Decl *Result
1516        = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1517                                         mType, DSRet, ReturnType, 
1518                                         KeyLocs, Sel, &ArgInfos[0], 
1519                                         CParamInfo.data(), CParamInfo.size(),
1520                                         methodAttrs.getList(),
1521                                         MethodImplKind, isVariadic, MethodDefinition);
1522   
1523   PD.complete(Result);
1524   return Result;
1525 }
1526
1527 ///   objc-protocol-refs:
1528 ///     '<' identifier-list '>'
1529 ///
1530 bool Parser::
1531 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1532                             SmallVectorImpl<SourceLocation> &ProtocolLocs,
1533                             bool WarnOnDeclarations, bool ForObjCContainer,
1534                             SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1535                             bool consumeLastToken) {
1536   assert(Tok.is(tok::less) && "expected <");
1537
1538   LAngleLoc = ConsumeToken(); // the "<"
1539
1540   SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1541
1542   while (1) {
1543     if (Tok.is(tok::code_completion)) {
1544       Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1545       cutOffParsing();
1546       return true;
1547     }
1548
1549     if (expectIdentifier()) {
1550       SkipUntil(tok::greater, StopAtSemi);
1551       return true;
1552     }
1553     ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1554                                        Tok.getLocation()));
1555     ProtocolLocs.push_back(Tok.getLocation());
1556     ConsumeToken();
1557
1558     if (!TryConsumeToken(tok::comma))
1559       break;
1560   }
1561
1562   // Consume the '>'.
1563   if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1564                                      /*ObjCGenericList=*/false))
1565     return true;
1566
1567   // Convert the list of protocols identifiers into a list of protocol decls.
1568   Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1569                                   ProtocolIdents, Protocols);
1570   return false;
1571 }
1572
1573 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1574   assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1575   assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1576
1577   SourceLocation lAngleLoc;
1578   SmallVector<Decl *, 8> protocols;
1579   SmallVector<SourceLocation, 8> protocolLocs;
1580   (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1581                                     lAngleLoc, rAngleLoc,
1582                                     /*consumeLastToken=*/true);
1583   TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1584                                                              protocols,
1585                                                              protocolLocs,
1586                                                              rAngleLoc);
1587   if (result.isUsable()) {
1588     Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1589       << FixItHint::CreateInsertion(lAngleLoc, "id")
1590       << SourceRange(lAngleLoc, rAngleLoc);
1591   }
1592
1593   return result;
1594 }
1595
1596 /// Parse Objective-C type arguments or protocol qualifiers.
1597 ///
1598 ///   objc-type-arguments:
1599 ///     '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1600 ///
1601 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1602        ParsedType baseType,
1603        SourceLocation &typeArgsLAngleLoc,
1604        SmallVectorImpl<ParsedType> &typeArgs,
1605        SourceLocation &typeArgsRAngleLoc,
1606        SourceLocation &protocolLAngleLoc,
1607        SmallVectorImpl<Decl *> &protocols,
1608        SmallVectorImpl<SourceLocation> &protocolLocs,
1609        SourceLocation &protocolRAngleLoc,
1610        bool consumeLastToken,
1611        bool warnOnIncompleteProtocols) {
1612   assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1613   SourceLocation lAngleLoc = ConsumeToken();
1614
1615   // Whether all of the elements we've parsed thus far are single
1616   // identifiers, which might be types or might be protocols.
1617   bool allSingleIdentifiers = true;
1618   SmallVector<IdentifierInfo *, 4> identifiers;
1619   SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1620
1621   // Parse a list of comma-separated identifiers, bailing out if we
1622   // see something different.
1623   do {
1624     // Parse a single identifier.
1625     if (Tok.is(tok::identifier) &&
1626         (NextToken().is(tok::comma) ||
1627          NextToken().is(tok::greater) ||
1628          NextToken().is(tok::greatergreater))) {
1629       identifiers.push_back(Tok.getIdentifierInfo());
1630       identifierLocs.push_back(ConsumeToken());
1631       continue;
1632     }
1633
1634     if (Tok.is(tok::code_completion)) {
1635       // FIXME: Also include types here.
1636       SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1637       for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1638         identifierLocPairs.push_back(IdentifierLocPair(identifiers[i], 
1639                                                        identifierLocs[i]));
1640       }
1641
1642       QualType BaseT = Actions.GetTypeFromParser(baseType);
1643       if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1644         Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1645       } else {
1646         Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1647       }
1648       cutOffParsing();
1649       return;
1650     }
1651
1652     allSingleIdentifiers = false;
1653     break;
1654   } while (TryConsumeToken(tok::comma));
1655
1656   // If we parsed an identifier list, semantic analysis sorts out
1657   // whether it refers to protocols or to type arguments.
1658   if (allSingleIdentifiers) {
1659     // Parse the closing '>'.
1660     SourceLocation rAngleLoc;
1661     (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1662                                          /*ObjCGenericList=*/true);
1663
1664     // Let Sema figure out what we parsed.
1665     Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1666                                                   baseType,
1667                                                   lAngleLoc,
1668                                                   identifiers,
1669                                                   identifierLocs,
1670                                                   rAngleLoc,
1671                                                   typeArgsLAngleLoc,
1672                                                   typeArgs,
1673                                                   typeArgsRAngleLoc,
1674                                                   protocolLAngleLoc,
1675                                                   protocols,
1676                                                   protocolRAngleLoc,
1677                                                   warnOnIncompleteProtocols);
1678     return;
1679   }
1680
1681   // We parsed an identifier list but stumbled into non single identifiers, this
1682   // means we might (a) check that what we already parsed is a legitimate type
1683   // (not a protocol or unknown type) and (b) parse the remaining ones, which
1684   // must all be type args.
1685
1686   // Convert the identifiers into type arguments.
1687   bool invalid = false;
1688   IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1689   SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1690   SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1691   SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1692
1693   for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1694     ParsedType typeArg
1695       = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1696     if (typeArg) {
1697       DeclSpec DS(AttrFactory);
1698       const char *prevSpec = nullptr;
1699       unsigned diagID;
1700       DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1701                          typeArg, Actions.getASTContext().getPrintingPolicy());
1702
1703       // Form a declarator to turn this into a type.
1704       Declarator D(DS, Declarator::TypeNameContext);
1705       TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1706       if (fullTypeArg.isUsable()) {
1707         typeArgs.push_back(fullTypeArg.get());
1708         if (!foundValidTypeId) {
1709           foundValidTypeId = identifiers[i];
1710           foundValidTypeSrcLoc = identifierLocs[i];
1711         }
1712       } else {
1713         invalid = true;
1714         unknownTypeArgs.push_back(identifiers[i]);
1715         unknownTypeArgsLoc.push_back(identifierLocs[i]);
1716       }
1717     } else {
1718       invalid = true;
1719       if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1720         unknownTypeArgs.push_back(identifiers[i]);
1721         unknownTypeArgsLoc.push_back(identifierLocs[i]);
1722       } else if (!foundProtocolId) {
1723         foundProtocolId = identifiers[i];
1724         foundProtocolSrcLoc = identifierLocs[i];
1725       }
1726     }
1727   }
1728
1729   // Continue parsing type-names.
1730   do {
1731     Token CurTypeTok = Tok;
1732     TypeResult typeArg = ParseTypeName();
1733
1734     // Consume the '...' for a pack expansion.
1735     SourceLocation ellipsisLoc;
1736     TryConsumeToken(tok::ellipsis, ellipsisLoc);
1737     if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1738       typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1739     }
1740
1741     if (typeArg.isUsable()) {
1742       typeArgs.push_back(typeArg.get());
1743       if (!foundValidTypeId) {
1744         foundValidTypeId = CurTypeTok.getIdentifierInfo();
1745         foundValidTypeSrcLoc = CurTypeTok.getLocation();
1746       }
1747     } else {
1748       invalid = true;
1749     }
1750   } while (TryConsumeToken(tok::comma));
1751
1752   // Diagnose the mix between type args and protocols.
1753   if (foundProtocolId && foundValidTypeId)
1754     Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1755                                          foundValidTypeId,
1756                                          foundValidTypeSrcLoc);
1757
1758   // Diagnose unknown arg types.
1759   ParsedType T;
1760   if (unknownTypeArgs.size())
1761     for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1762       Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1763                                       getCurScope(), nullptr, T);
1764
1765   // Parse the closing '>'.
1766   SourceLocation rAngleLoc;
1767   (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1768                                        /*ObjCGenericList=*/true);
1769
1770   if (invalid) {
1771     typeArgs.clear();
1772     return;
1773   }
1774
1775   // Record left/right angle locations.
1776   typeArgsLAngleLoc = lAngleLoc;
1777   typeArgsRAngleLoc = rAngleLoc;
1778 }
1779
1780 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1781        ParsedType baseType,
1782        SourceLocation &typeArgsLAngleLoc,
1783        SmallVectorImpl<ParsedType> &typeArgs,
1784        SourceLocation &typeArgsRAngleLoc,
1785        SourceLocation &protocolLAngleLoc,
1786        SmallVectorImpl<Decl *> &protocols,
1787        SmallVectorImpl<SourceLocation> &protocolLocs,
1788        SourceLocation &protocolRAngleLoc,
1789        bool consumeLastToken) {
1790   assert(Tok.is(tok::less));
1791
1792   // Parse the first angle-bracket-delimited clause.
1793   parseObjCTypeArgsOrProtocolQualifiers(baseType,
1794                                         typeArgsLAngleLoc,
1795                                         typeArgs,
1796                                         typeArgsRAngleLoc,
1797                                         protocolLAngleLoc,
1798                                         protocols,
1799                                         protocolLocs,
1800                                         protocolRAngleLoc,
1801                                         consumeLastToken,
1802                                         /*warnOnIncompleteProtocols=*/false);
1803   if (Tok.is(tok::eof)) // Nothing else to do here...
1804     return;
1805
1806   // An Objective-C object pointer followed by type arguments
1807   // can then be followed again by a set of protocol references, e.g.,
1808   // \c NSArray<NSView><NSTextDelegate>
1809   if ((consumeLastToken && Tok.is(tok::less)) ||
1810       (!consumeLastToken && NextToken().is(tok::less))) {
1811     // If we aren't consuming the last token, the prior '>' is still hanging
1812     // there. Consume it before we parse the protocol qualifiers.
1813     if (!consumeLastToken)
1814       ConsumeToken();
1815
1816     if (!protocols.empty()) {
1817       SkipUntilFlags skipFlags = SkipUntilFlags();
1818       if (!consumeLastToken)
1819         skipFlags = skipFlags | StopBeforeMatch;
1820       Diag(Tok, diag::err_objc_type_args_after_protocols)
1821         << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1822       SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1823     } else {
1824       ParseObjCProtocolReferences(protocols, protocolLocs, 
1825                                   /*WarnOnDeclarations=*/false,
1826                                   /*ForObjCContainer=*/false,
1827                                   protocolLAngleLoc, protocolRAngleLoc, 
1828                                   consumeLastToken);
1829     }
1830   }
1831 }
1832
1833 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1834              SourceLocation loc,
1835              ParsedType type,
1836              bool consumeLastToken,
1837              SourceLocation &endLoc) {
1838   assert(Tok.is(tok::less));
1839   SourceLocation typeArgsLAngleLoc;
1840   SmallVector<ParsedType, 4> typeArgs;
1841   SourceLocation typeArgsRAngleLoc;
1842   SourceLocation protocolLAngleLoc;
1843   SmallVector<Decl *, 4> protocols;
1844   SmallVector<SourceLocation, 4> protocolLocs;
1845   SourceLocation protocolRAngleLoc;
1846
1847   // Parse type arguments and protocol qualifiers.
1848   parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1849                                          typeArgsRAngleLoc, protocolLAngleLoc,
1850                                          protocols, protocolLocs,
1851                                          protocolRAngleLoc, consumeLastToken);
1852
1853   if (Tok.is(tok::eof))
1854     return true; // Invalid type result.
1855
1856   // Compute the location of the last token.
1857   if (consumeLastToken)
1858     endLoc = PrevTokLocation;
1859   else
1860     endLoc = Tok.getLocation();
1861
1862   return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1863            getCurScope(),
1864            loc,
1865            type,
1866            typeArgsLAngleLoc,
1867            typeArgs,
1868            typeArgsRAngleLoc,
1869            protocolLAngleLoc,
1870            protocols,
1871            protocolLocs,
1872            protocolRAngleLoc);
1873 }
1874
1875 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1876                                  BalancedDelimiterTracker &T,
1877                                  SmallVectorImpl<Decl *> &AllIvarDecls,
1878                                  bool RBraceMissing) {
1879   if (!RBraceMissing)
1880     T.consumeClose();
1881   
1882   Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1883   Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1884   Actions.ActOnObjCContainerFinishDefinition();
1885   // Call ActOnFields() even if we don't have any decls. This is useful
1886   // for code rewriting tools that need to be aware of the empty list.
1887   Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1888                       AllIvarDecls,
1889                       T.getOpenLocation(), T.getCloseLocation(), nullptr);
1890 }
1891
1892 ///   objc-class-instance-variables:
1893 ///     '{' objc-instance-variable-decl-list[opt] '}'
1894 ///
1895 ///   objc-instance-variable-decl-list:
1896 ///     objc-visibility-spec
1897 ///     objc-instance-variable-decl ';'
1898 ///     ';'
1899 ///     objc-instance-variable-decl-list objc-visibility-spec
1900 ///     objc-instance-variable-decl-list objc-instance-variable-decl ';'
1901 ///     objc-instance-variable-decl-list ';'
1902 ///
1903 ///   objc-visibility-spec:
1904 ///     @private
1905 ///     @protected
1906 ///     @public
1907 ///     @package [OBJC2]
1908 ///
1909 ///   objc-instance-variable-decl:
1910 ///     struct-declaration
1911 ///
1912 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1913                                              tok::ObjCKeywordKind visibility,
1914                                              SourceLocation atLoc) {
1915   assert(Tok.is(tok::l_brace) && "expected {");
1916   SmallVector<Decl *, 32> AllIvarDecls;
1917     
1918   ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1919   ObjCDeclContextSwitch ObjCDC(*this);
1920
1921   BalancedDelimiterTracker T(*this, tok::l_brace);
1922   T.consumeOpen();
1923   // While we still have something to read, read the instance variables.
1924   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1925     // Each iteration of this loop reads one objc-instance-variable-decl.
1926
1927     // Check for extraneous top-level semicolon.
1928     if (Tok.is(tok::semi)) {
1929       ConsumeExtraSemi(InstanceVariableList);
1930       continue;
1931     }
1932
1933     // Set the default visibility to private.
1934     if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1935       if (Tok.is(tok::code_completion)) {
1936         Actions.CodeCompleteObjCAtVisibility(getCurScope());
1937         return cutOffParsing();
1938       }
1939       
1940       switch (Tok.getObjCKeywordID()) {
1941       case tok::objc_private:
1942       case tok::objc_public:
1943       case tok::objc_protected:
1944       case tok::objc_package:
1945         visibility = Tok.getObjCKeywordID();
1946         ConsumeToken();
1947         continue;
1948
1949       case tok::objc_end:
1950         Diag(Tok, diag::err_objc_unexpected_atend);
1951         Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1952         Tok.setKind(tok::at);
1953         Tok.setLength(1);
1954         PP.EnterToken(Tok);
1955         HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1956                                          T, AllIvarDecls, true);
1957         return;
1958           
1959       default:
1960         Diag(Tok, diag::err_objc_illegal_visibility_spec);
1961         continue;
1962       }
1963     }
1964
1965     if (Tok.is(tok::code_completion)) {
1966       Actions.CodeCompleteOrdinaryName(getCurScope(), 
1967                                        Sema::PCC_ObjCInstanceVariableList);
1968       return cutOffParsing();
1969     }
1970
1971     auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1972       Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1973       // Install the declarator into the interface decl.
1974       FD.D.setObjCIvar(true);
1975       Decl *Field = Actions.ActOnIvar(
1976           getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1977           FD.BitfieldSize, visibility);
1978       Actions.ActOnObjCContainerFinishDefinition();
1979       if (Field)
1980         AllIvarDecls.push_back(Field);
1981       FD.complete(Field);
1982     };
1983
1984     // Parse all the comma separated declarators.
1985     ParsingDeclSpec DS(*this);
1986     ParseStructDeclaration(DS, ObjCIvarCallback);
1987
1988     if (Tok.is(tok::semi)) {
1989       ConsumeToken();
1990     } else {
1991       Diag(Tok, diag::err_expected_semi_decl_list);
1992       // Skip to end of block or statement
1993       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1994     }
1995   }
1996   HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1997                                    T, AllIvarDecls, false);
1998 }
1999
2000 ///   objc-protocol-declaration:
2001 ///     objc-protocol-definition
2002 ///     objc-protocol-forward-reference
2003 ///
2004 ///   objc-protocol-definition:
2005 ///     \@protocol identifier
2006 ///       objc-protocol-refs[opt]
2007 ///       objc-interface-decl-list
2008 ///     \@end
2009 ///
2010 ///   objc-protocol-forward-reference:
2011 ///     \@protocol identifier-list ';'
2012 ///
2013 ///   "\@protocol identifier ;" should be resolved as "\@protocol
2014 ///   identifier-list ;": objc-interface-decl-list may not start with a
2015 ///   semicolon in the first alternative if objc-protocol-refs are omitted.
2016 Parser::DeclGroupPtrTy 
2017 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2018                                        ParsedAttributes &attrs) {
2019   assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2020          "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2021   ConsumeToken(); // the "protocol" identifier
2022
2023   if (Tok.is(tok::code_completion)) {
2024     Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2025     cutOffParsing();
2026     return nullptr;
2027   }
2028
2029   MaybeSkipAttributes(tok::objc_protocol);
2030
2031   if (expectIdentifier())
2032     return nullptr; // missing protocol name.
2033   // Save the protocol name, then consume it.
2034   IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2035   SourceLocation nameLoc = ConsumeToken();
2036
2037   if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2038     IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2039     return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo,
2040                                                    attrs.getList());
2041   }
2042
2043   CheckNestedObjCContexts(AtLoc);
2044
2045   if (Tok.is(tok::comma)) { // list of forward declarations.
2046     SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2047     ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2048
2049     // Parse the list of forward declarations.
2050     while (1) {
2051       ConsumeToken(); // the ','
2052       if (expectIdentifier()) {
2053         SkipUntil(tok::semi);
2054         return nullptr;
2055       }
2056       ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2057                                                Tok.getLocation()));
2058       ConsumeToken(); // the identifier
2059
2060       if (Tok.isNot(tok::comma))
2061         break;
2062     }
2063     // Consume the ';'.
2064     if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2065       return nullptr;
2066
2067     return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs,
2068                                                    attrs.getList());
2069   }
2070
2071   // Last, and definitely not least, parse a protocol declaration.
2072   SourceLocation LAngleLoc, EndProtoLoc;
2073
2074   SmallVector<Decl *, 8> ProtocolRefs;
2075   SmallVector<SourceLocation, 8> ProtocolLocs;
2076   if (Tok.is(tok::less) &&
2077       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2078                                   LAngleLoc, EndProtoLoc,
2079                                   /*consumeLastToken=*/true))
2080     return nullptr;
2081
2082   Decl *ProtoType =
2083     Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
2084                                         ProtocolRefs.data(),
2085                                         ProtocolRefs.size(),
2086                                         ProtocolLocs.data(),
2087                                         EndProtoLoc, attrs.getList());
2088
2089   ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2090   return Actions.ConvertDeclToDeclGroup(ProtoType);
2091 }
2092
2093 ///   objc-implementation:
2094 ///     objc-class-implementation-prologue
2095 ///     objc-category-implementation-prologue
2096 ///
2097 ///   objc-class-implementation-prologue:
2098 ///     @implementation identifier objc-superclass[opt]
2099 ///       objc-class-instance-variables[opt]
2100 ///
2101 ///   objc-category-implementation-prologue:
2102 ///     @implementation identifier ( identifier )
2103 Parser::DeclGroupPtrTy
2104 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
2105   assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2106          "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2107   CheckNestedObjCContexts(AtLoc);
2108   ConsumeToken(); // the "implementation" identifier
2109
2110   // Code completion after '@implementation'.
2111   if (Tok.is(tok::code_completion)) {
2112     Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2113     cutOffParsing();
2114     return nullptr;
2115   }
2116
2117   MaybeSkipAttributes(tok::objc_implementation);
2118
2119   if (expectIdentifier())
2120     return nullptr; // missing class or category name.
2121   // We have a class or category name - consume it.
2122   IdentifierInfo *nameId = Tok.getIdentifierInfo();
2123   SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2124   Decl *ObjCImpDecl = nullptr;
2125
2126   // Neither a type parameter list nor a list of protocol references is
2127   // permitted here. Parse and diagnose them.
2128   if (Tok.is(tok::less)) {
2129     SourceLocation lAngleLoc, rAngleLoc;
2130     SmallVector<IdentifierLocPair, 8> protocolIdents;
2131     SourceLocation diagLoc = Tok.getLocation();
2132     ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2133     if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2134                                              protocolIdents, rAngleLoc)) {
2135       Diag(diagLoc, diag::err_objc_parameterized_implementation)
2136         << SourceRange(diagLoc, PrevTokLocation);
2137     } else if (lAngleLoc.isValid()) {
2138       Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2139         << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2140     }
2141   }
2142
2143   if (Tok.is(tok::l_paren)) {
2144     // we have a category implementation.
2145     ConsumeParen();
2146     SourceLocation categoryLoc, rparenLoc;
2147     IdentifierInfo *categoryId = nullptr;
2148
2149     if (Tok.is(tok::code_completion)) {
2150       Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2151       cutOffParsing();
2152       return nullptr;
2153     }
2154     
2155     if (Tok.is(tok::identifier)) {
2156       categoryId = Tok.getIdentifierInfo();
2157       categoryLoc = ConsumeToken();
2158     } else {
2159       Diag(Tok, diag::err_expected)
2160           << tok::identifier; // missing category name.
2161       return nullptr;
2162     }
2163     if (Tok.isNot(tok::r_paren)) {
2164       Diag(Tok, diag::err_expected) << tok::r_paren;
2165       SkipUntil(tok::r_paren); // don't stop at ';'
2166       return nullptr;
2167     }
2168     rparenLoc = ConsumeParen();
2169     if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2170       Diag(Tok, diag::err_unexpected_protocol_qualifier);
2171       SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2172       SmallVector<Decl *, 4> protocols;
2173       SmallVector<SourceLocation, 4> protocolLocs;
2174       (void)ParseObjCProtocolReferences(protocols, protocolLocs, 
2175                                         /*warnOnIncompleteProtocols=*/false,
2176                                         /*ForObjCContainer=*/false,
2177                                         protocolLAngleLoc, protocolRAngleLoc,
2178                                         /*consumeLastToken=*/true);
2179     }
2180     ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2181                                     AtLoc, nameId, nameLoc, categoryId,
2182                                     categoryLoc);
2183
2184   } else {
2185     // We have a class implementation
2186     SourceLocation superClassLoc;
2187     IdentifierInfo *superClassId = nullptr;
2188     if (TryConsumeToken(tok::colon)) {
2189       // We have a super class
2190       if (expectIdentifier())
2191         return nullptr; // missing super class name.
2192       superClassId = Tok.getIdentifierInfo();
2193       superClassLoc = ConsumeToken(); // Consume super class name
2194     }
2195     ObjCImpDecl = Actions.ActOnStartClassImplementation(
2196                                     AtLoc, nameId, nameLoc,
2197                                     superClassId, superClassLoc);
2198   
2199     if (Tok.is(tok::l_brace)) // we have ivars
2200       ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2201     else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2202       Diag(Tok, diag::err_unexpected_protocol_qualifier);
2203
2204       SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2205       SmallVector<Decl *, 4> protocols;
2206       SmallVector<SourceLocation, 4> protocolLocs;
2207       (void)ParseObjCProtocolReferences(protocols, protocolLocs, 
2208                                         /*warnOnIncompleteProtocols=*/false,
2209                                         /*ForObjCContainer=*/false,
2210                                         protocolLAngleLoc, protocolRAngleLoc,
2211                                         /*consumeLastToken=*/true);
2212     }
2213   }
2214   assert(ObjCImpDecl);
2215
2216   SmallVector<Decl *, 8> DeclsInGroup;
2217
2218   {
2219     ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2220     while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2221       ParsedAttributesWithRange attrs(AttrFactory);
2222       MaybeParseCXX11Attributes(attrs);
2223       if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2224         DeclGroupRef DG = DGP.get();
2225         DeclsInGroup.append(DG.begin(), DG.end());
2226       }
2227     }
2228   }
2229
2230   return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2231 }
2232
2233 Parser::DeclGroupPtrTy
2234 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2235   assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2236          "ParseObjCAtEndDeclaration(): Expected @end");
2237   ConsumeToken(); // the "end" identifier
2238   if (CurParsedObjCImpl)
2239     CurParsedObjCImpl->finish(atEnd);
2240   else
2241     // missing @implementation
2242     Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2243   return nullptr;
2244 }
2245
2246 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2247   if (!Finished) {
2248     finish(P.Tok.getLocation());
2249     if (P.isEofOrEom()) {
2250       P.Diag(P.Tok, diag::err_objc_missing_end)
2251           << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2252       P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
2253           << Sema::OCK_Implementation;
2254     }
2255   }
2256   P.CurParsedObjCImpl = nullptr;
2257   assert(LateParsedObjCMethods.empty());
2258 }
2259
2260 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2261   assert(!Finished);
2262   P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2263   for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2264     P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 
2265                                true/*Methods*/);
2266
2267   P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2268
2269   if (HasCFunction)
2270     for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2271       P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], 
2272                                  false/*c-functions*/);
2273   
2274   /// \brief Clear and free the cached objc methods.
2275   for (LateParsedObjCMethodContainer::iterator
2276          I = LateParsedObjCMethods.begin(),
2277          E = LateParsedObjCMethods.end(); I != E; ++I)
2278     delete *I;
2279   LateParsedObjCMethods.clear();
2280
2281   Finished = true;
2282 }
2283
2284 ///   compatibility-alias-decl:
2285 ///     @compatibility_alias alias-name  class-name ';'
2286 ///
2287 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2288   assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2289          "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2290   ConsumeToken(); // consume compatibility_alias
2291   if (expectIdentifier())
2292     return nullptr;
2293   IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2294   SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2295   if (expectIdentifier())
2296     return nullptr;
2297   IdentifierInfo *classId = Tok.getIdentifierInfo();
2298   SourceLocation classLoc = ConsumeToken(); // consume class-name;
2299   ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2300   return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2301                                          classId, classLoc);
2302 }
2303
2304 ///   property-synthesis:
2305 ///     @synthesize property-ivar-list ';'
2306 ///
2307 ///   property-ivar-list:
2308 ///     property-ivar
2309 ///     property-ivar-list ',' property-ivar
2310 ///
2311 ///   property-ivar:
2312 ///     identifier
2313 ///     identifier '=' identifier
2314 ///
2315 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2316   assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2317          "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2318   ConsumeToken(); // consume synthesize
2319
2320   while (true) {
2321     if (Tok.is(tok::code_completion)) {
2322       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2323       cutOffParsing();
2324       return nullptr;
2325     }
2326     
2327     if (Tok.isNot(tok::identifier)) {
2328       Diag(Tok, diag::err_synthesized_property_name);
2329       SkipUntil(tok::semi);
2330       return nullptr;
2331     }
2332
2333     IdentifierInfo *propertyIvar = nullptr;
2334     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2335     SourceLocation propertyLoc = ConsumeToken(); // consume property name
2336     SourceLocation propertyIvarLoc;
2337     if (TryConsumeToken(tok::equal)) {
2338       // property '=' ivar-name
2339       if (Tok.is(tok::code_completion)) {
2340         Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2341         cutOffParsing();
2342         return nullptr;
2343       }
2344
2345       if (expectIdentifier())
2346         break;
2347       propertyIvar = Tok.getIdentifierInfo();
2348       propertyIvarLoc = ConsumeToken(); // consume ivar-name
2349     }
2350     Actions.ActOnPropertyImplDecl(
2351         getCurScope(), atLoc, propertyLoc, true,
2352         propertyId, propertyIvar, propertyIvarLoc,
2353         ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2354     if (Tok.isNot(tok::comma))
2355       break;
2356     ConsumeToken(); // consume ','
2357   }
2358   ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2359   return nullptr;
2360 }
2361
2362 ///   property-dynamic:
2363 ///     @dynamic  property-list
2364 ///
2365 ///   property-list:
2366 ///     identifier
2367 ///     property-list ',' identifier
2368 ///
2369 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2370   assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2371          "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2372   ConsumeToken(); // consume dynamic
2373
2374   bool isClassProperty = false;
2375   if (Tok.is(tok::l_paren)) {
2376     ConsumeParen();
2377     const IdentifierInfo *II = Tok.getIdentifierInfo();
2378
2379     if (!II) {
2380       Diag(Tok, diag::err_objc_expected_property_attr) << II;
2381       SkipUntil(tok::r_paren, StopAtSemi);
2382     } else {
2383       SourceLocation AttrName = ConsumeToken(); // consume attribute name
2384       if (II->isStr("class")) {
2385         isClassProperty = true;
2386         if (Tok.isNot(tok::r_paren)) {
2387           Diag(Tok, diag::err_expected) << tok::r_paren;
2388           SkipUntil(tok::r_paren, StopAtSemi);
2389         } else
2390           ConsumeParen();
2391       } else {
2392         Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2393         SkipUntil(tok::r_paren, StopAtSemi);
2394       }
2395     }
2396   }
2397
2398   while (true) {
2399     if (Tok.is(tok::code_completion)) {
2400       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2401       cutOffParsing();
2402       return nullptr;
2403     }
2404
2405     if (expectIdentifier()) {
2406       SkipUntil(tok::semi);
2407       return nullptr;
2408     }
2409     
2410     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2411     SourceLocation propertyLoc = ConsumeToken(); // consume property name
2412     Actions.ActOnPropertyImplDecl(
2413         getCurScope(), atLoc, propertyLoc, false,
2414         propertyId, nullptr, SourceLocation(),
2415         isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2416         ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2417
2418     if (Tok.isNot(tok::comma))
2419       break;
2420     ConsumeToken(); // consume ','
2421   }
2422   ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2423   return nullptr;
2424 }
2425
2426 ///  objc-throw-statement:
2427 ///    throw expression[opt];
2428 ///
2429 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2430   ExprResult Res;
2431   ConsumeToken(); // consume throw
2432   if (Tok.isNot(tok::semi)) {
2433     Res = ParseExpression();
2434     if (Res.isInvalid()) {
2435       SkipUntil(tok::semi);
2436       return StmtError();
2437     }
2438   }
2439   // consume ';'
2440   ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2441   return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2442 }
2443
2444 /// objc-synchronized-statement:
2445 ///   @synchronized '(' expression ')' compound-statement
2446 ///
2447 StmtResult
2448 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2449   ConsumeToken(); // consume synchronized
2450   if (Tok.isNot(tok::l_paren)) {
2451     Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2452     return StmtError();
2453   }
2454
2455   // The operand is surrounded with parentheses.
2456   ConsumeParen();  // '('
2457   ExprResult operand(ParseExpression());
2458
2459   if (Tok.is(tok::r_paren)) {
2460     ConsumeParen();  // ')'
2461   } else {
2462     if (!operand.isInvalid())
2463       Diag(Tok, diag::err_expected) << tok::r_paren;
2464
2465     // Skip forward until we see a left brace, but don't consume it.
2466     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2467   }
2468
2469   // Require a compound statement.
2470   if (Tok.isNot(tok::l_brace)) {
2471     if (!operand.isInvalid())
2472       Diag(Tok, diag::err_expected) << tok::l_brace;
2473     return StmtError();
2474   }
2475
2476   // Check the @synchronized operand now.
2477   if (!operand.isInvalid())
2478     operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2479
2480   // Parse the compound statement within a new scope.
2481   ParseScope bodyScope(this, Scope::DeclScope);
2482   StmtResult body(ParseCompoundStatementBody());
2483   bodyScope.Exit();
2484
2485   // If there was a semantic or parse error earlier with the
2486   // operand, fail now.
2487   if (operand.isInvalid())
2488     return StmtError();
2489
2490   if (body.isInvalid())
2491     body = Actions.ActOnNullStmt(Tok.getLocation());
2492
2493   return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2494 }
2495
2496 ///  objc-try-catch-statement:
2497 ///    @try compound-statement objc-catch-list[opt]
2498 ///    @try compound-statement objc-catch-list[opt] @finally compound-statement
2499 ///
2500 ///  objc-catch-list:
2501 ///    @catch ( parameter-declaration ) compound-statement
2502 ///    objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2503 ///  catch-parameter-declaration:
2504 ///     parameter-declaration
2505 ///     '...' [OBJC2]
2506 ///
2507 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2508   bool catch_or_finally_seen = false;
2509
2510   ConsumeToken(); // consume try
2511   if (Tok.isNot(tok::l_brace)) {
2512     Diag(Tok, diag::err_expected) << tok::l_brace;
2513     return StmtError();
2514   }
2515   StmtVector CatchStmts;
2516   StmtResult FinallyStmt;
2517   ParseScope TryScope(this, Scope::DeclScope);
2518   StmtResult TryBody(ParseCompoundStatementBody());
2519   TryScope.Exit();
2520   if (TryBody.isInvalid())
2521     TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2522
2523   while (Tok.is(tok::at)) {
2524     // At this point, we need to lookahead to determine if this @ is the start
2525     // of an @catch or @finally.  We don't want to consume the @ token if this
2526     // is an @try or @encode or something else.
2527     Token AfterAt = GetLookAheadToken(1);
2528     if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2529         !AfterAt.isObjCAtKeyword(tok::objc_finally))
2530       break;
2531
2532     SourceLocation AtCatchFinallyLoc = ConsumeToken();
2533     if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2534       Decl *FirstPart = nullptr;
2535       ConsumeToken(); // consume catch
2536       if (Tok.is(tok::l_paren)) {
2537         ConsumeParen();
2538         ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
2539         if (Tok.isNot(tok::ellipsis)) {
2540           DeclSpec DS(AttrFactory);
2541           ParseDeclarationSpecifiers(DS);
2542           Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
2543           ParseDeclarator(ParmDecl);
2544
2545           // Inform the actions module about the declarator, so it
2546           // gets added to the current scope.
2547           FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2548         } else
2549           ConsumeToken(); // consume '...'
2550
2551         SourceLocation RParenLoc;
2552
2553         if (Tok.is(tok::r_paren))
2554           RParenLoc = ConsumeParen();
2555         else // Skip over garbage, until we get to ')'.  Eat the ')'.
2556           SkipUntil(tok::r_paren, StopAtSemi);
2557
2558         StmtResult CatchBody(true);
2559         if (Tok.is(tok::l_brace))
2560           CatchBody = ParseCompoundStatementBody();
2561         else
2562           Diag(Tok, diag::err_expected) << tok::l_brace;
2563         if (CatchBody.isInvalid())
2564           CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2565         
2566         StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2567                                                               RParenLoc, 
2568                                                               FirstPart, 
2569                                                               CatchBody.get());
2570         if (!Catch.isInvalid())
2571           CatchStmts.push_back(Catch.get());
2572         
2573       } else {
2574         Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2575           << "@catch clause";
2576         return StmtError();
2577       }
2578       catch_or_finally_seen = true;
2579     } else {
2580       assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2581       ConsumeToken(); // consume finally
2582       ParseScope FinallyScope(this, Scope::DeclScope);
2583
2584       StmtResult FinallyBody(true);
2585       if (Tok.is(tok::l_brace))
2586         FinallyBody = ParseCompoundStatementBody();
2587       else
2588         Diag(Tok, diag::err_expected) << tok::l_brace;
2589       if (FinallyBody.isInvalid())
2590         FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2591       FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2592                                                    FinallyBody.get());
2593       catch_or_finally_seen = true;
2594       break;
2595     }
2596   }
2597   if (!catch_or_finally_seen) {
2598     Diag(atLoc, diag::err_missing_catch_finally);
2599     return StmtError();
2600   }
2601   
2602   return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), 
2603                                     CatchStmts,
2604                                     FinallyStmt.get());
2605 }
2606
2607 /// objc-autoreleasepool-statement:
2608 ///   @autoreleasepool compound-statement
2609 ///
2610 StmtResult
2611 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2612   ConsumeToken(); // consume autoreleasepool
2613   if (Tok.isNot(tok::l_brace)) {
2614     Diag(Tok, diag::err_expected) << tok::l_brace;
2615     return StmtError();
2616   }
2617   // Enter a scope to hold everything within the compound stmt.  Compound
2618   // statements can always hold declarations.
2619   ParseScope BodyScope(this, Scope::DeclScope);
2620
2621   StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2622
2623   BodyScope.Exit();
2624   if (AutoreleasePoolBody.isInvalid())
2625     AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2626   return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, 
2627                                                 AutoreleasePoolBody.get());
2628 }
2629
2630 /// StashAwayMethodOrFunctionBodyTokens -  Consume the tokens and store them 
2631 /// for later parsing.
2632 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2633   if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2634       trySkippingFunctionBody()) {
2635     Actions.ActOnSkippedFunctionBody(MDecl);
2636     return;
2637   }
2638
2639   LexedMethod* LM = new LexedMethod(this, MDecl);
2640   CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2641   CachedTokens &Toks = LM->Toks;
2642   // Begin by storing the '{' or 'try' or ':' token.
2643   Toks.push_back(Tok);
2644   if (Tok.is(tok::kw_try)) {
2645     ConsumeToken();
2646     if (Tok.is(tok::colon)) {
2647       Toks.push_back(Tok);
2648       ConsumeToken();
2649       while (Tok.isNot(tok::l_brace)) {
2650         ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2651         ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2652       }
2653     }
2654     Toks.push_back(Tok); // also store '{'
2655   }
2656   else if (Tok.is(tok::colon)) {
2657     ConsumeToken();
2658     // FIXME: This is wrong, due to C++11 braced initialization.
2659     while (Tok.isNot(tok::l_brace)) {
2660       ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2661       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2662     }
2663     Toks.push_back(Tok); // also store '{'
2664   }
2665   ConsumeBrace();
2666   // Consume everything up to (and including) the matching right brace.
2667   ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2668   while (Tok.is(tok::kw_catch)) {
2669     ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2670     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2671   }
2672 }
2673
2674 ///   objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2675 ///
2676 Decl *Parser::ParseObjCMethodDefinition() {
2677   Decl *MDecl = ParseObjCMethodPrototype();
2678
2679   PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2680                                       "parsing Objective-C method");
2681
2682   // parse optional ';'
2683   if (Tok.is(tok::semi)) {
2684     if (CurParsedObjCImpl) {
2685       Diag(Tok, diag::warn_semicolon_before_method_body)
2686         << FixItHint::CreateRemoval(Tok.getLocation());
2687     }
2688     ConsumeToken();
2689   }
2690
2691   // We should have an opening brace now.
2692   if (Tok.isNot(tok::l_brace)) {
2693     Diag(Tok, diag::err_expected_method_body);
2694
2695     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
2696     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2697
2698     // If we didn't find the '{', bail out.
2699     if (Tok.isNot(tok::l_brace))
2700       return nullptr;
2701   }
2702
2703   if (!MDecl) {
2704     ConsumeBrace();
2705     SkipUntil(tok::r_brace);
2706     return nullptr;
2707   }
2708
2709   // Allow the rest of sema to find private method decl implementations.
2710   Actions.AddAnyMethodToGlobalPool(MDecl);
2711   assert (CurParsedObjCImpl 
2712           && "ParseObjCMethodDefinition - Method out of @implementation");
2713   // Consume the tokens and store them for later parsing.
2714   StashAwayMethodOrFunctionBodyTokens(MDecl);
2715   return MDecl;
2716 }
2717
2718 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2719   if (Tok.is(tok::code_completion)) {
2720     Actions.CodeCompleteObjCAtStatement(getCurScope());
2721     cutOffParsing();
2722     return StmtError();
2723   }
2724   
2725   if (Tok.isObjCAtKeyword(tok::objc_try))
2726     return ParseObjCTryStmt(AtLoc);
2727   
2728   if (Tok.isObjCAtKeyword(tok::objc_throw))
2729     return ParseObjCThrowStmt(AtLoc);
2730   
2731   if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2732     return ParseObjCSynchronizedStmt(AtLoc);
2733
2734   if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2735     return ParseObjCAutoreleasePoolStmt(AtLoc);
2736
2737   if (Tok.isObjCAtKeyword(tok::objc_import) &&
2738       getLangOpts().DebuggerSupport) {
2739     SkipUntil(tok::semi);
2740     return Actions.ActOnNullStmt(Tok.getLocation());
2741   }
2742
2743   ExprStatementTokLoc = AtLoc;
2744   ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2745   if (Res.isInvalid()) {
2746     // If the expression is invalid, skip ahead to the next semicolon. Not
2747     // doing this opens us up to the possibility of infinite loops if
2748     // ParseExpression does not consume any tokens.
2749     SkipUntil(tok::semi);
2750     return StmtError();
2751   }
2752   
2753   // Otherwise, eat the semicolon.
2754   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2755   return Actions.ActOnExprStmt(Res);
2756 }
2757
2758 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2759   switch (Tok.getKind()) {
2760   case tok::code_completion:
2761     Actions.CodeCompleteObjCAtExpression(getCurScope());
2762     cutOffParsing();
2763     return ExprError();
2764
2765   case tok::minus:
2766   case tok::plus: {
2767     tok::TokenKind Kind = Tok.getKind();
2768     SourceLocation OpLoc = ConsumeToken();
2769
2770     if (!Tok.is(tok::numeric_constant)) {
2771       const char *Symbol = nullptr;
2772       switch (Kind) {
2773       case tok::minus: Symbol = "-"; break;
2774       case tok::plus: Symbol = "+"; break;
2775       default: llvm_unreachable("missing unary operator case");
2776       }
2777       Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2778         << Symbol;
2779       return ExprError();
2780     }
2781
2782     ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2783     if (Lit.isInvalid()) {
2784       return Lit;
2785     }
2786     ConsumeToken(); // Consume the literal token.
2787
2788     Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2789     if (Lit.isInvalid())
2790       return Lit;
2791
2792     return ParsePostfixExpressionSuffix(
2793              Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2794   }
2795
2796   case tok::string_literal:    // primary-expression: string-literal
2797   case tok::wide_string_literal:
2798     return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2799
2800   case tok::char_constant:
2801     return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2802       
2803   case tok::numeric_constant:
2804     return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2805
2806   case tok::kw_true:  // Objective-C++, etc.
2807   case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2808     return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2809   case tok::kw_false: // Objective-C++, etc.
2810   case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2811     return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2812     
2813   case tok::l_square:
2814     // Objective-C array literal
2815     return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2816           
2817   case tok::l_brace:
2818     // Objective-C dictionary literal
2819     return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2820           
2821   case tok::l_paren:
2822     // Objective-C boxed expression
2823     return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2824           
2825   default:
2826     if (Tok.getIdentifierInfo() == nullptr)
2827       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2828
2829     switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2830     case tok::objc_encode:
2831       return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2832     case tok::objc_protocol:
2833       return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2834     case tok::objc_selector:
2835       return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2836     case tok::objc_available:
2837       return ParseAvailabilityCheckExpr(AtLoc);
2838       default: {
2839         const char *str = nullptr;
2840         // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2841         // that this is a proper statement where such directives could actually
2842         // occur.
2843         if (GetLookAheadToken(1).is(tok::l_brace) &&
2844             ExprStatementTokLoc == AtLoc) {
2845           char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2846           str =  
2847             ch == 't' ? "try" 
2848                       : (ch == 'f' ? "finally" 
2849                                    : (ch == 'a' ? "autoreleasepool" : nullptr));
2850         }
2851         if (str) {
2852           SourceLocation kwLoc = Tok.getLocation();
2853           return ExprError(Diag(AtLoc, diag::err_unexpected_at) << 
2854                              FixItHint::CreateReplacement(kwLoc, str));
2855         }
2856         else
2857           return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2858       }
2859     }
2860   }
2861 }
2862
2863 /// \brief Parse the receiver of an Objective-C++ message send.
2864 ///
2865 /// This routine parses the receiver of a message send in
2866 /// Objective-C++ either as a type or as an expression. Note that this
2867 /// routine must not be called to parse a send to 'super', since it
2868 /// has no way to return such a result.
2869 /// 
2870 /// \param IsExpr Whether the receiver was parsed as an expression.
2871 ///
2872 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2873 /// IsExpr is true), the parsed expression. If the receiver was parsed
2874 /// as a type (\c IsExpr is false), the parsed type.
2875 ///
2876 /// \returns True if an error occurred during parsing or semantic
2877 /// analysis, in which case the arguments do not have valid
2878 /// values. Otherwise, returns false for a successful parse.
2879 ///
2880 ///   objc-receiver: [C++]
2881 ///     'super' [not parsed here]
2882 ///     expression
2883 ///     simple-type-specifier
2884 ///     typename-specifier
2885 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2886   InMessageExpressionRAIIObject InMessage(*this, true);
2887
2888   if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2889                   tok::annot_cxxscope))
2890     TryAnnotateTypeOrScopeToken();
2891
2892   if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2893     //   objc-receiver:
2894     //     expression
2895     // Make sure any typos in the receiver are corrected or diagnosed, so that
2896     // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2897     // only the things that are valid ObjC receivers?
2898     ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2899     if (Receiver.isInvalid())
2900       return true;
2901
2902     IsExpr = true;
2903     TypeOrExpr = Receiver.get();
2904     return false;
2905   }
2906
2907   // objc-receiver:
2908   //   typename-specifier
2909   //   simple-type-specifier
2910   //   expression (that starts with one of the above)
2911   DeclSpec DS(AttrFactory);
2912   ParseCXXSimpleTypeSpecifier(DS);
2913   
2914   if (Tok.is(tok::l_paren)) {
2915     // If we see an opening parentheses at this point, we are
2916     // actually parsing an expression that starts with a
2917     // function-style cast, e.g.,
2918     //
2919     //   postfix-expression:
2920     //     simple-type-specifier ( expression-list [opt] )
2921     //     typename-specifier ( expression-list [opt] )
2922     //
2923     // Parse the remainder of this case, then the (optional)
2924     // postfix-expression suffix, followed by the (optional)
2925     // right-hand side of the binary expression. We have an
2926     // instance method.
2927     ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2928     if (!Receiver.isInvalid())
2929       Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2930     if (!Receiver.isInvalid())
2931       Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2932     if (Receiver.isInvalid())
2933       return true;
2934
2935     IsExpr = true;
2936     TypeOrExpr = Receiver.get();
2937     return false;
2938   }
2939   
2940   // We have a class message. Turn the simple-type-specifier or
2941   // typename-specifier we parsed into a type and parse the
2942   // remainder of the class message.
2943   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2944   TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2945   if (Type.isInvalid())
2946     return true;
2947
2948   IsExpr = false;
2949   TypeOrExpr = Type.get().getAsOpaquePtr();
2950   return false;
2951 }
2952
2953 /// \brief Determine whether the parser is currently referring to a an
2954 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2955 ///
2956 /// This routine will only return true for a subset of valid message-send
2957 /// expressions.
2958 bool Parser::isSimpleObjCMessageExpression() {
2959   assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2960          "Incorrect start for isSimpleObjCMessageExpression");
2961   return GetLookAheadToken(1).is(tok::identifier) &&
2962          GetLookAheadToken(2).is(tok::identifier);
2963 }
2964
2965 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2966   if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || 
2967       InMessageExpression)
2968     return false;
2969   
2970   ParsedType Type;
2971
2972   if (Tok.is(tok::annot_typename)) 
2973     Type = getTypeAnnotation(Tok);
2974   else if (Tok.is(tok::identifier))
2975     Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), 
2976                                getCurScope());
2977   else
2978     return false;
2979   
2980   if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2981     const Token &AfterNext = GetLookAheadToken(2);
2982     if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2983       if (Tok.is(tok::identifier))
2984         TryAnnotateTypeOrScopeToken();
2985       
2986       return Tok.is(tok::annot_typename);
2987     }
2988   }
2989
2990   return false;
2991 }
2992
2993 ///   objc-message-expr:
2994 ///     '[' objc-receiver objc-message-args ']'
2995 ///
2996 ///   objc-receiver: [C]
2997 ///     'super'
2998 ///     expression
2999 ///     class-name
3000 ///     type-name
3001 ///
3002 ExprResult Parser::ParseObjCMessageExpression() {
3003   assert(Tok.is(tok::l_square) && "'[' expected");
3004   SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3005
3006   if (Tok.is(tok::code_completion)) {
3007     Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3008     cutOffParsing();
3009     return ExprError();
3010   }
3011   
3012   InMessageExpressionRAIIObject InMessage(*this, true);
3013   
3014   if (getLangOpts().CPlusPlus) {
3015     // We completely separate the C and C++ cases because C++ requires
3016     // more complicated (read: slower) parsing. 
3017     
3018     // Handle send to super.  
3019     // FIXME: This doesn't benefit from the same typo-correction we
3020     // get in Objective-C.
3021     if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3022         NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3023       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3024                                             nullptr);
3025
3026     // Parse the receiver, which is either a type or an expression.
3027     bool IsExpr;
3028     void *TypeOrExpr = nullptr;
3029     if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3030       SkipUntil(tok::r_square, StopAtSemi);
3031       return ExprError();
3032     }
3033
3034     if (IsExpr)
3035       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3036                                             static_cast<Expr *>(TypeOrExpr));
3037
3038     return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 
3039                               ParsedType::getFromOpaquePtr(TypeOrExpr),
3040                                           nullptr);
3041   }
3042   
3043   if (Tok.is(tok::identifier)) {
3044     IdentifierInfo *Name = Tok.getIdentifierInfo();
3045     SourceLocation NameLoc = Tok.getLocation();
3046     ParsedType ReceiverType;
3047     switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3048                                        Name == Ident_super,
3049                                        NextToken().is(tok::period),
3050                                        ReceiverType)) {
3051     case Sema::ObjCSuperMessage:
3052       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3053                                             nullptr);
3054
3055     case Sema::ObjCClassMessage:
3056       if (!ReceiverType) {
3057         SkipUntil(tok::r_square, StopAtSemi);
3058         return ExprError();
3059       }
3060
3061       ConsumeToken(); // the type name
3062
3063       // Parse type arguments and protocol qualifiers.
3064       if (Tok.is(tok::less)) {
3065         SourceLocation NewEndLoc;
3066         TypeResult NewReceiverType
3067           = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3068                                                    /*consumeLastToken=*/true,
3069                                                    NewEndLoc);
3070         if (!NewReceiverType.isUsable()) {
3071           SkipUntil(tok::r_square, StopAtSemi);
3072           return ExprError();
3073         }
3074
3075         ReceiverType = NewReceiverType.get();
3076       }
3077
3078       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 
3079                                             ReceiverType, nullptr);
3080
3081     case Sema::ObjCInstanceMessage:
3082       // Fall through to parse an expression.
3083       break;
3084     }
3085   }
3086   
3087   // Otherwise, an arbitrary expression can be the receiver of a send.
3088   ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3089   if (Res.isInvalid()) {
3090     SkipUntil(tok::r_square, StopAtSemi);
3091     return Res;
3092   }
3093
3094   return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3095                                         Res.get());
3096 }
3097
3098 /// \brief Parse the remainder of an Objective-C message following the
3099 /// '[' objc-receiver.
3100 ///
3101 /// This routine handles sends to super, class messages (sent to a
3102 /// class name), and instance messages (sent to an object), and the
3103 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3104 /// ReceiverExpr, respectively. Only one of these parameters may have
3105 /// a valid value.
3106 ///
3107 /// \param LBracLoc The location of the opening '['.
3108 ///
3109 /// \param SuperLoc If this is a send to 'super', the location of the
3110 /// 'super' keyword that indicates a send to the superclass.
3111 ///
3112 /// \param ReceiverType If this is a class message, the type of the
3113 /// class we are sending a message to.
3114 ///
3115 /// \param ReceiverExpr If this is an instance message, the expression
3116 /// used to compute the receiver object.
3117 ///
3118 ///   objc-message-args:
3119 ///     objc-selector
3120 ///     objc-keywordarg-list
3121 ///
3122 ///   objc-keywordarg-list:
3123 ///     objc-keywordarg
3124 ///     objc-keywordarg-list objc-keywordarg
3125 ///
3126 ///   objc-keywordarg:
3127 ///     selector-name[opt] ':' objc-keywordexpr
3128 ///
3129 ///   objc-keywordexpr:
3130 ///     nonempty-expr-list
3131 ///
3132 ///   nonempty-expr-list:
3133 ///     assignment-expression
3134 ///     nonempty-expr-list , assignment-expression
3135 ///
3136 ExprResult
3137 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3138                                        SourceLocation SuperLoc,
3139                                        ParsedType ReceiverType,
3140                                        Expr *ReceiverExpr) {
3141   InMessageExpressionRAIIObject InMessage(*this, true);
3142
3143   if (Tok.is(tok::code_completion)) {
3144     if (SuperLoc.isValid())
3145       Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3146                                            false);
3147     else if (ReceiverType)
3148       Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3149                                            false);
3150     else
3151       Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3152                                               None, false);
3153     cutOffParsing();
3154     return ExprError();
3155   }
3156   
3157   // Parse objc-selector
3158   SourceLocation Loc;
3159   IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3160   
3161   SmallVector<IdentifierInfo *, 12> KeyIdents;
3162   SmallVector<SourceLocation, 12> KeyLocs;
3163   ExprVector KeyExprs;
3164
3165   if (Tok.is(tok::colon)) {
3166     while (1) {
3167       // Each iteration parses a single keyword argument.
3168       KeyIdents.push_back(selIdent);
3169       KeyLocs.push_back(Loc);
3170
3171       if (ExpectAndConsume(tok::colon)) {
3172         // We must manually skip to a ']', otherwise the expression skipper will
3173         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3174         // the enclosing expression.
3175         SkipUntil(tok::r_square, StopAtSemi);
3176         return ExprError();
3177       }
3178
3179       ///  Parse the expression after ':'
3180       
3181       if (Tok.is(tok::code_completion)) {
3182         if (SuperLoc.isValid())
3183           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 
3184                                                KeyIdents,
3185                                                /*AtArgumentEpression=*/true);
3186         else if (ReceiverType)
3187           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3188                                                KeyIdents,
3189                                                /*AtArgumentEpression=*/true);
3190         else
3191           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3192                                                   KeyIdents,
3193                                                   /*AtArgumentEpression=*/true);
3194
3195         cutOffParsing();
3196         return ExprError();
3197       }
3198       
3199       ExprResult Expr;
3200       if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3201         Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3202         Expr = ParseBraceInitializer();
3203       } else
3204         Expr = ParseAssignmentExpression();
3205       
3206       ExprResult Res(Expr);
3207       if (Res.isInvalid()) {
3208         // We must manually skip to a ']', otherwise the expression skipper will
3209         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3210         // the enclosing expression.
3211         SkipUntil(tok::r_square, StopAtSemi);
3212         return Res;
3213       }
3214
3215       // We have a valid expression.
3216       KeyExprs.push_back(Res.get());
3217
3218       // Code completion after each argument.
3219       if (Tok.is(tok::code_completion)) {
3220         if (SuperLoc.isValid())
3221           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 
3222                                                KeyIdents,
3223                                                /*AtArgumentEpression=*/false);
3224         else if (ReceiverType)
3225           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3226                                                KeyIdents,
3227                                                /*AtArgumentEpression=*/false);
3228         else
3229           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3230                                                   KeyIdents,
3231                                                 /*AtArgumentEpression=*/false);
3232         cutOffParsing();
3233         return ExprError();
3234       }
3235             
3236       // Check for another keyword selector.
3237       selIdent = ParseObjCSelectorPiece(Loc);
3238       if (!selIdent && Tok.isNot(tok::colon))
3239         break;
3240       // We have a selector or a colon, continue parsing.
3241     }
3242     // Parse the, optional, argument list, comma separated.
3243     while (Tok.is(tok::comma)) {
3244       SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3245       ///  Parse the expression after ','
3246       ExprResult Res(ParseAssignmentExpression());
3247       if (Tok.is(tok::colon))
3248         Res = Actions.CorrectDelayedTyposInExpr(Res);
3249       if (Res.isInvalid()) {
3250         if (Tok.is(tok::colon)) {
3251           Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3252             FixItHint::CreateRemoval(commaLoc);
3253         }
3254         // We must manually skip to a ']', otherwise the expression skipper will
3255         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3256         // the enclosing expression.
3257         SkipUntil(tok::r_square, StopAtSemi);
3258         return Res;
3259       }
3260
3261       // We have a valid expression.
3262       KeyExprs.push_back(Res.get());
3263     }
3264   } else if (!selIdent) {
3265     Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3266
3267     // We must manually skip to a ']', otherwise the expression skipper will
3268     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3269     // the enclosing expression.
3270     SkipUntil(tok::r_square, StopAtSemi);
3271     return ExprError();
3272   }
3273     
3274   if (Tok.isNot(tok::r_square)) {
3275     Diag(Tok, diag::err_expected)
3276         << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3277     // We must manually skip to a ']', otherwise the expression skipper will
3278     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3279     // the enclosing expression.
3280     SkipUntil(tok::r_square, StopAtSemi);
3281     return ExprError();
3282   }
3283   
3284   SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3285
3286   unsigned nKeys = KeyIdents.size();
3287   if (nKeys == 0) {
3288     KeyIdents.push_back(selIdent);
3289     KeyLocs.push_back(Loc);
3290   }
3291   Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3292
3293   if (SuperLoc.isValid())
3294     return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3295                                      LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3296   else if (ReceiverType)
3297     return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3298                                      LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3299   return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3300                                       LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3301 }
3302
3303 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3304   ExprResult Res(ParseStringLiteralExpression());
3305   if (Res.isInvalid()) return Res;
3306
3307   // @"foo" @"bar" is a valid concatenated string.  Eat any subsequent string
3308   // expressions.  At this point, we know that the only valid thing that starts
3309   // with '@' is an @"".
3310   SmallVector<SourceLocation, 4> AtLocs;
3311   ExprVector AtStrings;
3312   AtLocs.push_back(AtLoc);
3313   AtStrings.push_back(Res.get());
3314
3315   while (Tok.is(tok::at)) {
3316     AtLocs.push_back(ConsumeToken()); // eat the @.
3317
3318     // Invalid unless there is a string literal.
3319     if (!isTokenStringLiteral())
3320       return ExprError(Diag(Tok, diag::err_objc_concat_string));
3321
3322     ExprResult Lit(ParseStringLiteralExpression());
3323     if (Lit.isInvalid())
3324       return Lit;
3325
3326     AtStrings.push_back(Lit.get());
3327   }
3328
3329   return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3330 }
3331
3332 /// ParseObjCBooleanLiteral -
3333 /// objc-scalar-literal : '@' boolean-keyword
3334 ///                        ;
3335 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3336 ///                        ;
3337 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, 
3338                                            bool ArgValue) {
3339   SourceLocation EndLoc = ConsumeToken();             // consume the keyword.
3340   return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3341 }
3342
3343 /// ParseObjCCharacterLiteral -
3344 /// objc-scalar-literal : '@' character-literal
3345 ///                        ;
3346 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3347   ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3348   if (Lit.isInvalid()) {
3349     return Lit;
3350   }
3351   ConsumeToken(); // Consume the literal token.
3352   return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3353 }
3354
3355 /// ParseObjCNumericLiteral -
3356 /// objc-scalar-literal : '@' scalar-literal
3357 ///                        ;
3358 /// scalar-literal : | numeric-constant                 /* any numeric constant. */
3359 ///                    ;
3360 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3361   ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3362   if (Lit.isInvalid()) {
3363     return Lit;
3364   }
3365   ConsumeToken(); // Consume the literal token.
3366   return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3367 }
3368
3369 /// ParseObjCBoxedExpr -
3370 /// objc-box-expression:
3371 ///       @( assignment-expression )
3372 ExprResult
3373 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3374   if (Tok.isNot(tok::l_paren))
3375     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3376
3377   BalancedDelimiterTracker T(*this, tok::l_paren);
3378   T.consumeOpen();
3379   ExprResult ValueExpr(ParseAssignmentExpression());
3380   if (T.consumeClose())
3381     return ExprError();
3382
3383   if (ValueExpr.isInvalid())
3384     return ExprError();
3385
3386   // Wrap the sub-expression in a parenthesized expression, to distinguish
3387   // a boxed expression from a literal.
3388   SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3389   ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3390   return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3391                                     ValueExpr.get());
3392 }
3393
3394 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3395   ExprVector ElementExprs;                   // array elements.
3396   ConsumeBracket(); // consume the l_square.
3397
3398   bool HasInvalidEltExpr = false;
3399   while (Tok.isNot(tok::r_square)) {
3400     // Parse list of array element expressions (all must be id types).
3401     ExprResult Res(ParseAssignmentExpression());
3402     if (Res.isInvalid()) {
3403       // We must manually skip to a ']', otherwise the expression skipper will
3404       // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3405       // the enclosing expression.
3406       SkipUntil(tok::r_square, StopAtSemi);
3407       return Res;
3408     }    
3409     
3410     Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3411     if (Res.isInvalid())
3412       HasInvalidEltExpr = true;
3413
3414     // Parse the ellipsis that indicates a pack expansion.
3415     if (Tok.is(tok::ellipsis))
3416       Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());    
3417     if (Res.isInvalid())
3418       HasInvalidEltExpr = true;
3419
3420     ElementExprs.push_back(Res.get());
3421
3422     if (Tok.is(tok::comma))
3423       ConsumeToken(); // Eat the ','.
3424     else if (Tok.isNot(tok::r_square))
3425       return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3426                                                             << tok::comma);
3427   }
3428   SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3429
3430   if (HasInvalidEltExpr)
3431     return ExprError();
3432
3433   MultiExprArg Args(ElementExprs);
3434   return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3435 }
3436
3437 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3438   SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3439   ConsumeBrace(); // consume the l_square.
3440   bool HasInvalidEltExpr = false;
3441   while (Tok.isNot(tok::r_brace)) {
3442     // Parse the comma separated key : value expressions.
3443     ExprResult KeyExpr;
3444     {
3445       ColonProtectionRAIIObject X(*this);
3446       KeyExpr = ParseAssignmentExpression();
3447       if (KeyExpr.isInvalid()) {
3448         // We must manually skip to a '}', otherwise the expression skipper will
3449         // stop at the '}' when it skips to the ';'.  We want it to skip beyond
3450         // the enclosing expression.
3451         SkipUntil(tok::r_brace, StopAtSemi);
3452         return KeyExpr;
3453       }
3454     }
3455
3456     if (ExpectAndConsume(tok::colon)) {
3457       SkipUntil(tok::r_brace, StopAtSemi);
3458       return ExprError();
3459     }
3460     
3461     ExprResult ValueExpr(ParseAssignmentExpression());
3462     if (ValueExpr.isInvalid()) {
3463       // We must manually skip to a '}', otherwise the expression skipper will
3464       // stop at the '}' when it skips to the ';'.  We want it to skip beyond
3465       // the enclosing expression.
3466       SkipUntil(tok::r_brace, StopAtSemi);
3467       return ValueExpr;
3468     }
3469     
3470     // Check the key and value for possible typos
3471     KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3472     ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3473     if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3474       HasInvalidEltExpr = true;
3475
3476     // Parse the ellipsis that designates this as a pack expansion. Do not
3477     // ActOnPackExpansion here, leave it to template instantiation time where
3478     // we can get better diagnostics.
3479     SourceLocation EllipsisLoc;
3480     if (getLangOpts().CPlusPlus)
3481       TryConsumeToken(tok::ellipsis, EllipsisLoc);
3482
3483     // We have a valid expression. Collect it in a vector so we can
3484     // build the argument list.
3485     ObjCDictionaryElement Element = { 
3486       KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None 
3487     };
3488     Elements.push_back(Element);
3489
3490     if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3491       return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3492                                                             << tok::comma);
3493   }
3494   SourceLocation EndLoc = ConsumeBrace();
3495
3496   if (HasInvalidEltExpr)
3497     return ExprError();
3498   
3499   // Create the ObjCDictionaryLiteral.
3500   return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3501                                             Elements);
3502 }
3503
3504 ///    objc-encode-expression:
3505 ///      \@encode ( type-name )
3506 ExprResult
3507 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3508   assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3509
3510   SourceLocation EncLoc = ConsumeToken();
3511
3512   if (Tok.isNot(tok::l_paren))
3513     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3514
3515   BalancedDelimiterTracker T(*this, tok::l_paren);
3516   T.consumeOpen();
3517
3518   TypeResult Ty = ParseTypeName();
3519
3520   T.consumeClose();
3521
3522   if (Ty.isInvalid())
3523     return ExprError();
3524
3525   return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3526                                            Ty.get(), T.getCloseLocation());
3527 }
3528
3529 ///     objc-protocol-expression
3530 ///       \@protocol ( protocol-name )
3531 ExprResult
3532 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3533   SourceLocation ProtoLoc = ConsumeToken();
3534
3535   if (Tok.isNot(tok::l_paren))
3536     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3537
3538   BalancedDelimiterTracker T(*this, tok::l_paren);
3539   T.consumeOpen();
3540
3541   if (expectIdentifier())
3542     return ExprError();
3543
3544   IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3545   SourceLocation ProtoIdLoc = ConsumeToken();
3546
3547   T.consumeClose();
3548
3549   return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3550                                              T.getOpenLocation(), ProtoIdLoc,
3551                                              T.getCloseLocation());
3552 }
3553
3554 ///     objc-selector-expression
3555 ///       @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3556 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3557   SourceLocation SelectorLoc = ConsumeToken();
3558
3559   if (Tok.isNot(tok::l_paren))
3560     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3561
3562   SmallVector<IdentifierInfo *, 12> KeyIdents;
3563   SourceLocation sLoc;
3564   
3565   BalancedDelimiterTracker T(*this, tok::l_paren);
3566   T.consumeOpen();
3567   bool HasOptionalParen = Tok.is(tok::l_paren);
3568   if (HasOptionalParen)
3569     ConsumeParen();
3570   
3571   if (Tok.is(tok::code_completion)) {
3572     Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3573     cutOffParsing();
3574     return ExprError();
3575   }
3576   
3577   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3578   if (!SelIdent &&  // missing selector name.
3579       Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3580     return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3581
3582   KeyIdents.push_back(SelIdent);
3583   
3584   unsigned nColons = 0;
3585   if (Tok.isNot(tok::r_paren)) {
3586     while (1) {
3587       if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3588         ++nColons;
3589         KeyIdents.push_back(nullptr);
3590       } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3591         return ExprError();
3592       ++nColons;
3593
3594       if (Tok.is(tok::r_paren))
3595         break;
3596       
3597       if (Tok.is(tok::code_completion)) {
3598         Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3599         cutOffParsing();
3600         return ExprError();
3601       }
3602
3603       // Check for another keyword selector.
3604       SourceLocation Loc;
3605       SelIdent = ParseObjCSelectorPiece(Loc);
3606       KeyIdents.push_back(SelIdent);
3607       if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3608         break;
3609     }
3610   }
3611   if (HasOptionalParen && Tok.is(tok::r_paren))
3612     ConsumeParen(); // ')'
3613   T.consumeClose();
3614   Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3615   return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3616                                              T.getOpenLocation(),
3617                                              T.getCloseLocation(),
3618                                              !HasOptionalParen);
3619 }
3620
3621 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3622   // MCDecl might be null due to error in method or c-function  prototype, etc.
3623   Decl *MCDecl = LM.D;
3624   bool skip = MCDecl && 
3625               ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3626               (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3627   if (skip)
3628     return;
3629   
3630   // Save the current token position.
3631   SourceLocation OrigLoc = Tok.getLocation();
3632
3633   assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3634   // Store an artificial EOF token to ensure that we don't run off the end of
3635   // the method's body when we come to parse it.
3636   Token Eof;
3637   Eof.startToken();
3638   Eof.setKind(tok::eof);
3639   Eof.setEofData(MCDecl);
3640   Eof.setLocation(OrigLoc);
3641   LM.Toks.push_back(Eof);
3642   // Append the current token at the end of the new token stream so that it
3643   // doesn't get lost.
3644   LM.Toks.push_back(Tok);
3645   PP.EnterTokenStream(LM.Toks, true);
3646
3647   // Consume the previously pushed token.
3648   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3649     
3650   assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && 
3651          "Inline objective-c method not starting with '{' or 'try' or ':'");
3652   // Enter a scope for the method or c-function body.
3653   ParseScope BodyScope(this,
3654                        parseMethod
3655                        ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
3656                        : Scope::FnScope|Scope::DeclScope);
3657     
3658   // Tell the actions module that we have entered a method or c-function definition 
3659   // with the specified Declarator for the method/function.
3660   if (parseMethod)
3661     Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3662   else
3663     Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3664   if (Tok.is(tok::kw_try))
3665     ParseFunctionTryBlock(MCDecl, BodyScope);
3666   else {
3667     if (Tok.is(tok::colon))
3668       ParseConstructorInitializer(MCDecl);
3669     else
3670       Actions.ActOnDefaultCtorInitializers(MCDecl);
3671     ParseFunctionStatementBody(MCDecl, BodyScope);
3672   }
3673
3674   if (Tok.getLocation() != OrigLoc) {
3675     // Due to parsing error, we either went over the cached tokens or
3676     // there are still cached tokens left. If it's the latter case skip the
3677     // leftover tokens.
3678     // Since this is an uncommon situation that should be avoided, use the
3679     // expensive isBeforeInTranslationUnit call.
3680     if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3681                                                      OrigLoc))
3682       while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3683         ConsumeAnyToken();
3684   }
3685   // Clean up the remaining EOF token.
3686   ConsumeAnyToken();
3687 }