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