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