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