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