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