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"
16 #include "clang/Basic/CharInfo.h"
19 #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  /// \brief 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  StmtResult FinallyBody(true);
2589  if (Tok.is(tok::l_brace))
2590  FinallyBody = ParseCompoundStatementBody();
2591  else
2592  Diag(Tok, diag::err_expected) << tok::l_brace;
2593  if (FinallyBody.isInvalid())
2594  FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2595  FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2596  FinallyBody.get());
2597  catch_or_finally_seen = true;
2598  break;
2599  }
2600  }
2601  if (!catch_or_finally_seen) {
2602  Diag(atLoc, diag::err_missing_catch_finally);
2603  return StmtError();
2604  }
2605 
2606  return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2607  CatchStmts,
2608  FinallyStmt.get());
2609 }
2610 
2611 /// objc-autoreleasepool-statement:
2612 /// @autoreleasepool compound-statement
2613 ///
2614 StmtResult
2615 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2616  ConsumeToken(); // consume autoreleasepool
2617  if (Tok.isNot(tok::l_brace)) {
2618  Diag(Tok, diag::err_expected) << tok::l_brace;
2619  return StmtError();
2620  }
2621  // Enter a scope to hold everything within the compound stmt. Compound
2622  // statements can always hold declarations.
2623  ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2624 
2625  StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2626 
2627  BodyScope.Exit();
2628  if (AutoreleasePoolBody.isInvalid())
2629  AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2630  return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2631  AutoreleasePoolBody.get());
2632 }
2633 
2634 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2635 /// for later parsing.
2636 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2637  if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2638  trySkippingFunctionBody()) {
2639  Actions.ActOnSkippedFunctionBody(MDecl);
2640  return;
2641  }
2642 
2643  LexedMethod* LM = new LexedMethod(this, MDecl);
2644  CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2645  CachedTokens &Toks = LM->Toks;
2646  // Begin by storing the '{' or 'try' or ':' token.
2647  Toks.push_back(Tok);
2648  if (Tok.is(tok::kw_try)) {
2649  ConsumeToken();
2650  if (Tok.is(tok::colon)) {
2651  Toks.push_back(Tok);
2652  ConsumeToken();
2653  while (Tok.isNot(tok::l_brace)) {
2654  ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2655  ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2656  }
2657  }
2658  Toks.push_back(Tok); // also store '{'
2659  }
2660  else if (Tok.is(tok::colon)) {
2661  ConsumeToken();
2662  // FIXME: This is wrong, due to C++11 braced initialization.
2663  while (Tok.isNot(tok::l_brace)) {
2664  ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2665  ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2666  }
2667  Toks.push_back(Tok); // also store '{'
2668  }
2669  ConsumeBrace();
2670  // Consume everything up to (and including) the matching right brace.
2671  ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2672  while (Tok.is(tok::kw_catch)) {
2673  ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2674  ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2675  }
2676 }
2677 
2678 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2679 ///
2680 Decl *Parser::ParseObjCMethodDefinition() {
2681  Decl *MDecl = ParseObjCMethodPrototype();
2682 
2683  PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2684  "parsing Objective-C method");
2685 
2686  // parse optional ';'
2687  if (Tok.is(tok::semi)) {
2688  if (CurParsedObjCImpl) {
2689  Diag(Tok, diag::warn_semicolon_before_method_body)
2690  << FixItHint::CreateRemoval(Tok.getLocation());
2691  }
2692  ConsumeToken();
2693  }
2694 
2695  // We should have an opening brace now.
2696  if (Tok.isNot(tok::l_brace)) {
2697  Diag(Tok, diag::err_expected_method_body);
2698 
2699  // Skip over garbage, until we get to '{'. Don't eat the '{'.
2700  SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2701 
2702  // If we didn't find the '{', bail out.
2703  if (Tok.isNot(tok::l_brace))
2704  return nullptr;
2705  }
2706 
2707  if (!MDecl) {
2708  ConsumeBrace();
2709  SkipUntil(tok::r_brace);
2710  return nullptr;
2711  }
2712 
2713  // Allow the rest of sema to find private method decl implementations.
2714  Actions.AddAnyMethodToGlobalPool(MDecl);
2715  assert (CurParsedObjCImpl
2716  && "ParseObjCMethodDefinition - Method out of @implementation");
2717  // Consume the tokens and store them for later parsing.
2718  StashAwayMethodOrFunctionBodyTokens(MDecl);
2719  return MDecl;
2720 }
2721 
2722 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2723  if (Tok.is(tok::code_completion)) {
2724  Actions.CodeCompleteObjCAtStatement(getCurScope());
2725  cutOffParsing();
2726  return StmtError();
2727  }
2728 
2729  if (Tok.isObjCAtKeyword(tok::objc_try))
2730  return ParseObjCTryStmt(AtLoc);
2731 
2732  if (Tok.isObjCAtKeyword(tok::objc_throw))
2733  return ParseObjCThrowStmt(AtLoc);
2734 
2735  if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2736  return ParseObjCSynchronizedStmt(AtLoc);
2737 
2738  if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2739  return ParseObjCAutoreleasePoolStmt(AtLoc);
2740 
2741  if (Tok.isObjCAtKeyword(tok::objc_import) &&
2742  getLangOpts().DebuggerSupport) {
2743  SkipUntil(tok::semi);
2744  return Actions.ActOnNullStmt(Tok.getLocation());
2745  }
2746 
2747  ExprStatementTokLoc = AtLoc;
2748  ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2749  if (Res.isInvalid()) {
2750  // If the expression is invalid, skip ahead to the next semicolon. Not
2751  // doing this opens us up to the possibility of infinite loops if
2752  // ParseExpression does not consume any tokens.
2753  SkipUntil(tok::semi);
2754  return StmtError();
2755  }
2756 
2757  // Otherwise, eat the semicolon.
2758  ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2759  return Actions.ActOnExprStmt(Res);
2760 }
2761 
2762 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2763  switch (Tok.getKind()) {
2764  case tok::code_completion:
2765  Actions.CodeCompleteObjCAtExpression(getCurScope());
2766  cutOffParsing();
2767  return ExprError();
2768 
2769  case tok::minus:
2770  case tok::plus: {
2771  tok::TokenKind Kind = Tok.getKind();
2772  SourceLocation OpLoc = ConsumeToken();
2773 
2774  if (!Tok.is(tok::numeric_constant)) {
2775  const char *Symbol = nullptr;
2776  switch (Kind) {
2777  case tok::minus: Symbol = "-"; break;
2778  case tok::plus: Symbol = "+"; break;
2779  default: llvm_unreachable("missing unary operator case");
2780  }
2781  Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2782  << Symbol;
2783  return ExprError();
2784  }
2785 
2786  ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2787  if (Lit.isInvalid()) {
2788  return Lit;
2789  }
2790  ConsumeToken(); // Consume the literal token.
2791 
2792  Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2793  if (Lit.isInvalid())
2794  return Lit;
2795 
2796  return ParsePostfixExpressionSuffix(
2797  Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2798  }
2799 
2800  case tok::string_literal: // primary-expression: string-literal
2801  case tok::wide_string_literal:
2802  return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2803 
2804  case tok::char_constant:
2805  return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2806 
2807  case tok::numeric_constant:
2808  return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2809 
2810  case tok::kw_true: // Objective-C++, etc.
2811  case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2812  return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2813  case tok::kw_false: // Objective-C++, etc.
2814  case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2815  return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2816 
2817  case tok::l_square:
2818  // Objective-C array literal
2819  return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2820 
2821  case tok::l_brace:
2822  // Objective-C dictionary literal
2823  return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2824 
2825  case tok::l_paren:
2826  // Objective-C boxed expression
2827  return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2828 
2829  default:
2830  if (Tok.getIdentifierInfo() == nullptr)
2831  return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2832 
2833  switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2834  case tok::objc_encode:
2835  return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2836  case tok::objc_protocol:
2837  return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2838  case tok::objc_selector:
2839  return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2840  case tok::objc_available:
2841  return ParseAvailabilityCheckExpr(AtLoc);
2842  default: {
2843  const char *str = nullptr;
2844  // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2845  // that this is a proper statement where such directives could actually
2846  // occur.
2847  if (GetLookAheadToken(1).is(tok::l_brace) &&
2848  ExprStatementTokLoc == AtLoc) {
2849  char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2850  str =
2851  ch == 't' ? "try"
2852  : (ch == 'f' ? "finally"
2853  : (ch == 'a' ? "autoreleasepool" : nullptr));
2854  }
2855  if (str) {
2856  SourceLocation kwLoc = Tok.getLocation();
2857  return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2858  FixItHint::CreateReplacement(kwLoc, str));
2859  }
2860  else
2861  return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2862  }
2863  }
2864  }
2865 }
2866 
2867 /// \brief Parse the receiver of an Objective-C++ message send.
2868 ///
2869 /// This routine parses the receiver of a message send in
2870 /// Objective-C++ either as a type or as an expression. Note that this
2871 /// routine must not be called to parse a send to 'super', since it
2872 /// has no way to return such a result.
2873 ///
2874 /// \param IsExpr Whether the receiver was parsed as an expression.
2875 ///
2876 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2877 /// IsExpr is true), the parsed expression. If the receiver was parsed
2878 /// as a type (\c IsExpr is false), the parsed type.
2879 ///
2880 /// \returns True if an error occurred during parsing or semantic
2881 /// analysis, in which case the arguments do not have valid
2882 /// values. Otherwise, returns false for a successful parse.
2883 ///
2884 /// objc-receiver: [C++]
2885 /// 'super' [not parsed here]
2886 /// expression
2887 /// simple-type-specifier
2888 /// typename-specifier
2889 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2890  InMessageExpressionRAIIObject InMessage(*this, true);
2891 
2892  if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2893  tok::annot_cxxscope))
2895 
2896  if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2897  // objc-receiver:
2898  // expression
2899  // Make sure any typos in the receiver are corrected or diagnosed, so that
2900  // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2901  // only the things that are valid ObjC receivers?
2902  ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2903  if (Receiver.isInvalid())
2904  return true;
2905 
2906  IsExpr = true;
2907  TypeOrExpr = Receiver.get();
2908  return false;
2909  }
2910 
2911  // objc-receiver:
2912  // typename-specifier
2913  // simple-type-specifier
2914  // expression (that starts with one of the above)
2915  DeclSpec DS(AttrFactory);
2916  ParseCXXSimpleTypeSpecifier(DS);
2917 
2918  if (Tok.is(tok::l_paren)) {
2919  // If we see an opening parentheses at this point, we are
2920  // actually parsing an expression that starts with a
2921  // function-style cast, e.g.,
2922  //
2923  // postfix-expression:
2924  // simple-type-specifier ( expression-list [opt] )
2925  // typename-specifier ( expression-list [opt] )
2926  //
2927  // Parse the remainder of this case, then the (optional)
2928  // postfix-expression suffix, followed by the (optional)
2929  // right-hand side of the binary expression. We have an
2930  // instance method.
2931  ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2932  if (!Receiver.isInvalid())
2933  Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2934  if (!Receiver.isInvalid())
2935  Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2936  if (Receiver.isInvalid())
2937  return true;
2938 
2939  IsExpr = true;
2940  TypeOrExpr = Receiver.get();
2941  return false;
2942  }
2943 
2944  // We have a class message. Turn the simple-type-specifier or
2945  // typename-specifier we parsed into a type and parse the
2946  // remainder of the class message.
2947  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2948  TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2949  if (Type.isInvalid())
2950  return true;
2951 
2952  IsExpr = false;
2953  TypeOrExpr = Type.get().getAsOpaquePtr();
2954  return false;
2955 }
2956 
2957 /// \brief Determine whether the parser is currently referring to a an
2958 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2959 ///
2960 /// This routine will only return true for a subset of valid message-send
2961 /// expressions.
2962 bool Parser::isSimpleObjCMessageExpression() {
2963  assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2964  "Incorrect start for isSimpleObjCMessageExpression");
2965  return GetLookAheadToken(1).is(tok::identifier) &&
2966  GetLookAheadToken(2).is(tok::identifier);
2967 }
2968 
2969 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2970  if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2971  InMessageExpression)
2972  return false;
2973 
2974  ParsedType Type;
2975 
2976  if (Tok.is(tok::annot_typename))
2977  Type = getTypeAnnotation(Tok);
2978  else if (Tok.is(tok::identifier))
2979  Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2980  getCurScope());
2981  else
2982  return false;
2983 
2984  if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2985  const Token &AfterNext = GetLookAheadToken(2);
2986  if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2987  if (Tok.is(tok::identifier))
2989 
2990  return Tok.is(tok::annot_typename);
2991  }
2992  }
2993 
2994  return false;
2995 }
2996 
2997 /// objc-message-expr:
2998 /// '[' objc-receiver objc-message-args ']'
2999 ///
3000 /// objc-receiver: [C]
3001 /// 'super'
3002 /// expression
3003 /// class-name
3004 /// type-name
3005 ///
3006 ExprResult Parser::ParseObjCMessageExpression() {
3007  assert(Tok.is(tok::l_square) && "'[' expected");
3008  SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3009 
3010  if (Tok.is(tok::code_completion)) {
3011  Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3012  cutOffParsing();
3013  return ExprError();
3014  }
3015 
3016  InMessageExpressionRAIIObject InMessage(*this, true);
3017 
3018  if (getLangOpts().CPlusPlus) {
3019  // We completely separate the C and C++ cases because C++ requires
3020  // more complicated (read: slower) parsing.
3021 
3022  // Handle send to super.
3023  // FIXME: This doesn't benefit from the same typo-correction we
3024  // get in Objective-C.
3025  if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3026  NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3027  return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3028  nullptr);
3029 
3030  // Parse the receiver, which is either a type or an expression.
3031  bool IsExpr;
3032  void *TypeOrExpr = nullptr;
3033  if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3034  SkipUntil(tok::r_square, StopAtSemi);
3035  return ExprError();
3036  }
3037 
3038  if (IsExpr)
3039  return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3040  static_cast<Expr *>(TypeOrExpr));
3041 
3042  return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3043  ParsedType::getFromOpaquePtr(TypeOrExpr),
3044  nullptr);
3045  }
3046 
3047  if (Tok.is(tok::identifier)) {
3048  IdentifierInfo *Name = Tok.getIdentifierInfo();
3049  SourceLocation NameLoc = Tok.getLocation();
3050  ParsedType ReceiverType;
3051  switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3052  Name == Ident_super,
3053  NextToken().is(tok::period),
3054  ReceiverType)) {
3056  return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3057  nullptr);
3058 
3060  if (!ReceiverType) {
3061  SkipUntil(tok::r_square, StopAtSemi);
3062  return ExprError();
3063  }
3064 
3065  ConsumeToken(); // the type name
3066 
3067  // Parse type arguments and protocol qualifiers.
3068  if (Tok.is(tok::less)) {
3069  SourceLocation NewEndLoc;
3070  TypeResult NewReceiverType
3071  = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3072  /*consumeLastToken=*/true,
3073  NewEndLoc);
3074  if (!NewReceiverType.isUsable()) {
3075  SkipUntil(tok::r_square, StopAtSemi);
3076  return ExprError();
3077  }
3078 
3079  ReceiverType = NewReceiverType.get();
3080  }
3081 
3082  return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3083  ReceiverType, nullptr);
3084 
3086  // Fall through to parse an expression.
3087  break;
3088  }
3089  }
3090 
3091  // Otherwise, an arbitrary expression can be the receiver of a send.
3092  ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3093  if (Res.isInvalid()) {
3094  SkipUntil(tok::r_square, StopAtSemi);
3095  return Res;
3096  }
3097 
3098  return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3099  Res.get());
3100 }
3101 
3102 /// \brief Parse the remainder of an Objective-C message following the
3103 /// '[' objc-receiver.
3104 ///
3105 /// This routine handles sends to super, class messages (sent to a
3106 /// class name), and instance messages (sent to an object), and the
3107 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3108 /// ReceiverExpr, respectively. Only one of these parameters may have
3109 /// a valid value.
3110 ///
3111 /// \param LBracLoc The location of the opening '['.
3112 ///
3113 /// \param SuperLoc If this is a send to 'super', the location of the
3114 /// 'super' keyword that indicates a send to the superclass.
3115 ///
3116 /// \param ReceiverType If this is a class message, the type of the
3117 /// class we are sending a message to.
3118 ///
3119 /// \param ReceiverExpr If this is an instance message, the expression
3120 /// used to compute the receiver object.
3121 ///
3122 /// objc-message-args:
3123 /// objc-selector
3124 /// objc-keywordarg-list
3125 ///
3126 /// objc-keywordarg-list:
3127 /// objc-keywordarg
3128 /// objc-keywordarg-list objc-keywordarg
3129 ///
3130 /// objc-keywordarg:
3131 /// selector-name[opt] ':' objc-keywordexpr
3132 ///
3133 /// objc-keywordexpr:
3134 /// nonempty-expr-list
3135 ///
3136 /// nonempty-expr-list:
3137 /// assignment-expression
3138 /// nonempty-expr-list , assignment-expression
3139 ///
3140 ExprResult
3141 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3142  SourceLocation SuperLoc,
3143  ParsedType ReceiverType,
3144  Expr *ReceiverExpr) {
3145  InMessageExpressionRAIIObject InMessage(*this, true);
3146 
3147  if (Tok.is(tok::code_completion)) {
3148  if (SuperLoc.isValid())
3149  Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3150  false);
3151  else if (ReceiverType)
3152  Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3153  false);
3154  else
3155  Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3156  None, false);
3157  cutOffParsing();
3158  return ExprError();
3159  }
3160 
3161  // Parse objc-selector
3162  SourceLocation Loc;
3163  IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3164 
3167  ExprVector KeyExprs;
3168 
3169  if (Tok.is(tok::colon)) {
3170  while (1) {
3171  // Each iteration parses a single keyword argument.
3172  KeyIdents.push_back(selIdent);
3173  KeyLocs.push_back(Loc);
3174 
3175  if (ExpectAndConsume(tok::colon)) {
3176  // We must manually skip to a ']', otherwise the expression skipper will
3177  // stop at the ']' when it skips to the ';'. We want it to skip beyond
3178  // the enclosing expression.
3179  SkipUntil(tok::r_square, StopAtSemi);
3180  return ExprError();
3181  }
3182 
3183  /// Parse the expression after ':'
3184 
3185  if (Tok.is(tok::code_completion)) {
3186  if (SuperLoc.isValid())
3187  Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3188  KeyIdents,
3189  /*AtArgumentEpression=*/true);
3190  else if (ReceiverType)
3191  Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3192  KeyIdents,
3193  /*AtArgumentEpression=*/true);
3194  else
3195  Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3196  KeyIdents,
3197  /*AtArgumentEpression=*/true);
3198 
3199  cutOffParsing();
3200  return ExprError();
3201  }
3202 
3203  ExprResult Expr;
3204  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3205  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3206  Expr = ParseBraceInitializer();
3207  } else
3208  Expr = ParseAssignmentExpression();
3209 
3210  ExprResult Res(Expr);
3211  if (Res.isInvalid()) {
3212  // We must manually skip to a ']', otherwise the expression skipper will
3213  // stop at the ']' when it skips to the ';'. We want it to skip beyond
3214  // the enclosing expression.
3215  SkipUntil(tok::r_square, StopAtSemi);
3216  return Res;
3217  }
3218 
3219  // We have a valid expression.
3220  KeyExprs.push_back(Res.get());
3221 
3222  // Code completion after each argument.
3223  if (Tok.is(tok::code_completion)) {
3224  if (SuperLoc.isValid())
3225  Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3226  KeyIdents,
3227  /*AtArgumentEpression=*/false);
3228  else if (ReceiverType)
3229  Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3230  KeyIdents,
3231  /*AtArgumentEpression=*/false);
3232  else
3233  Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3234  KeyIdents,
3235  /*AtArgumentEpression=*/false);
3236  cutOffParsing();
3237  return ExprError();
3238  }
3239 
3240  // Check for another keyword selector.
3241  selIdent = ParseObjCSelectorPiece(Loc);
3242  if (!selIdent && Tok.isNot(tok::colon))
3243  break;
3244  // We have a selector or a colon, continue parsing.
3245  }
3246  // Parse the, optional, argument list, comma separated.
3247  while (Tok.is(tok::comma)) {
3248  SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3249  /// Parse the expression after ','
3251  if (Tok.is(tok::colon))
3252  Res = Actions.CorrectDelayedTyposInExpr(Res);
3253  if (Res.isInvalid()) {
3254  if (Tok.is(tok::colon)) {
3255  Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3256  FixItHint::CreateRemoval(commaLoc);
3257  }
3258  // We must manually skip to a ']', otherwise the expression skipper will
3259  // stop at the ']' when it skips to the ';'. We want it to skip beyond
3260  // the enclosing expression.
3261  SkipUntil(tok::r_square, StopAtSemi);
3262  return Res;
3263  }
3264 
3265  // We have a valid expression.
3266  KeyExprs.push_back(Res.get());
3267  }
3268  } else if (!selIdent) {
3269  Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
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 ExprError();
3276  }
3277 
3278  if (Tok.isNot(tok::r_square)) {
3279  Diag(Tok, diag::err_expected)
3280  << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3281  // We must manually skip to a ']', otherwise the expression skipper will
3282  // stop at the ']' when it skips to the ';'. We want it to skip beyond
3283  // the enclosing expression.
3284  SkipUntil(tok::r_square, StopAtSemi);
3285  return ExprError();
3286  }
3287 
3288  SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3289 
3290  unsigned nKeys = KeyIdents.size();
3291  if (nKeys == 0) {
3292  KeyIdents.push_back(selIdent);
3293  KeyLocs.push_back(Loc);
3294  }
3295  Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3296 
3297  if (SuperLoc.isValid())
3298  return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3299  LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3300  else if (ReceiverType)
3301  return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3302  LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3303  return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3304  LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3305 }
3306 
3307 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3308  ExprResult Res(ParseStringLiteralExpression());
3309  if (Res.isInvalid()) return Res;
3310 
3311  // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3312  // expressions. At this point, we know that the only valid thing that starts
3313  // with '@' is an @"".
3315  ExprVector AtStrings;
3316  AtLocs.push_back(AtLoc);
3317  AtStrings.push_back(Res.get());
3318 
3319  while (Tok.is(tok::at)) {
3320  AtLocs.push_back(ConsumeToken()); // eat the @.
3321 
3322  // Invalid unless there is a string literal.
3323  if (!isTokenStringLiteral())
3324  return ExprError(Diag(Tok, diag::err_objc_concat_string));
3325 
3326  ExprResult Lit(ParseStringLiteralExpression());
3327  if (Lit.isInvalid())
3328  return Lit;
3329 
3330  AtStrings.push_back(Lit.get());
3331  }
3332 
3333  return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3334 }
3335 
3336 /// ParseObjCBooleanLiteral -
3337 /// objc-scalar-literal : '@' boolean-keyword
3338 /// ;
3339 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3340 /// ;
3341 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3342  bool ArgValue) {
3343  SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3344  return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3345 }
3346 
3347 /// ParseObjCCharacterLiteral -
3348 /// objc-scalar-literal : '@' character-literal
3349 /// ;
3350 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3351  ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3352  if (Lit.isInvalid()) {
3353  return Lit;
3354  }
3355  ConsumeToken(); // Consume the literal token.
3356  return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3357 }
3358 
3359 /// ParseObjCNumericLiteral -
3360 /// objc-scalar-literal : '@' scalar-literal
3361 /// ;
3362 /// scalar-literal : | numeric-constant /* any numeric constant. */
3363 /// ;
3364 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3365  ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3366  if (Lit.isInvalid()) {
3367  return Lit;
3368  }
3369  ConsumeToken(); // Consume the literal token.
3370  return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3371 }
3372 
3373 /// ParseObjCBoxedExpr -
3374 /// objc-box-expression:
3375 /// @( assignment-expression )
3376 ExprResult
3377 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3378  if (Tok.isNot(tok::l_paren))
3379  return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3380 
3381  BalancedDelimiterTracker T(*this, tok::l_paren);
3382  T.consumeOpen();
3384  if (T.consumeClose())
3385  return ExprError();
3386 
3387  if (ValueExpr.isInvalid())
3388  return ExprError();
3389 
3390  // Wrap the sub-expression in a parenthesized expression, to distinguish
3391  // a boxed expression from a literal.
3392  SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3393  ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3394  return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3395  ValueExpr.get());
3396 }
3397 
3398 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3399  ExprVector ElementExprs; // array elements.
3400  ConsumeBracket(); // consume the l_square.
3401 
3402  bool HasInvalidEltExpr = false;
3403  while (Tok.isNot(tok::r_square)) {
3404  // Parse list of array element expressions (all must be id types).
3406  if (Res.isInvalid()) {
3407  // We must manually skip to a ']', otherwise the expression skipper will
3408  // stop at the ']' when it skips to the ';'. We want it to skip beyond
3409  // the enclosing expression.
3410  SkipUntil(tok::r_square, StopAtSemi);
3411  return Res;
3412  }
3413 
3414  Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3415  if (Res.isInvalid())
3416  HasInvalidEltExpr = true;
3417 
3418  // Parse the ellipsis that indicates a pack expansion.
3419  if (Tok.is(tok::ellipsis))
3420  Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3421  if (Res.isInvalid())
3422  HasInvalidEltExpr = true;
3423 
3424  ElementExprs.push_back(Res.get());
3425 
3426  if (Tok.is(tok::comma))
3427  ConsumeToken(); // Eat the ','.
3428  else if (Tok.isNot(tok::r_square))
3429  return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3430  << tok::comma);
3431  }
3432  SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3433 
3434  if (HasInvalidEltExpr)
3435  return ExprError();
3436 
3437  MultiExprArg Args(ElementExprs);
3438  return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3439 }
3440 
3441 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3442  SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3443  ConsumeBrace(); // consume the l_square.
3444  bool HasInvalidEltExpr = false;
3445  while (Tok.isNot(tok::r_brace)) {
3446  // Parse the comma separated key : value expressions.
3447  ExprResult KeyExpr;
3448  {
3450  KeyExpr = ParseAssignmentExpression();
3451  if (KeyExpr.isInvalid()) {
3452  // We must manually skip to a '}', otherwise the expression skipper will
3453  // stop at the '}' when it skips to the ';'. We want it to skip beyond
3454  // the enclosing expression.
3455  SkipUntil(tok::r_brace, StopAtSemi);
3456  return KeyExpr;
3457  }
3458  }
3459 
3460  if (ExpectAndConsume(tok::colon)) {
3461  SkipUntil(tok::r_brace, StopAtSemi);
3462  return ExprError();
3463  }
3464 
3466  if (ValueExpr.isInvalid()) {
3467  // We must manually skip to a '}', otherwise the expression skipper will
3468  // stop at the '}' when it skips to the ';'. We want it to skip beyond
3469  // the enclosing expression.
3470  SkipUntil(tok::r_brace, StopAtSemi);
3471  return ValueExpr;
3472  }
3473 
3474  // Check the key and value for possible typos
3475  KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3476  ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3477  if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3478  HasInvalidEltExpr = true;
3479 
3480  // Parse the ellipsis that designates this as a pack expansion. Do not
3481  // ActOnPackExpansion here, leave it to template instantiation time where
3482  // we can get better diagnostics.
3483  SourceLocation EllipsisLoc;
3484  if (getLangOpts().CPlusPlus)
3485  TryConsumeToken(tok::ellipsis, EllipsisLoc);
3486 
3487  // We have a valid expression. Collect it in a vector so we can
3488  // build the argument list.
3489  ObjCDictionaryElement Element = {
3490  KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3491  };
3492  Elements.push_back(Element);
3493 
3494  if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3495  return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3496  << tok::comma);
3497  }
3498  SourceLocation EndLoc = ConsumeBrace();
3499 
3500  if (HasInvalidEltExpr)
3501  return ExprError();
3502 
3503  // Create the ObjCDictionaryLiteral.
3504  return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3505  Elements);
3506 }
3507 
3508 /// objc-encode-expression:
3509 /// \@encode ( type-name )
3510 ExprResult
3511 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3512  assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3513 
3514  SourceLocation EncLoc = ConsumeToken();
3515 
3516  if (Tok.isNot(tok::l_paren))
3517  return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3518 
3519  BalancedDelimiterTracker T(*this, tok::l_paren);
3520  T.consumeOpen();
3521 
3522  TypeResult Ty = ParseTypeName();
3523 
3524  T.consumeClose();
3525 
3526  if (Ty.isInvalid())
3527  return ExprError();
3528 
3529  return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3530  Ty.get(), T.getCloseLocation());
3531 }
3532 
3533 /// objc-protocol-expression
3534 /// \@protocol ( protocol-name )
3535 ExprResult
3536 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3537  SourceLocation ProtoLoc = ConsumeToken();
3538 
3539  if (Tok.isNot(tok::l_paren))
3540  return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3541 
3542  BalancedDelimiterTracker T(*this, tok::l_paren);
3543  T.consumeOpen();
3544 
3545  if (expectIdentifier())
3546  return ExprError();
3547 
3548  IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3549  SourceLocation ProtoIdLoc = ConsumeToken();
3550 
3551  T.consumeClose();
3552 
3553  return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3554  T.getOpenLocation(), ProtoIdLoc,
3555  T.getCloseLocation());
3556 }
3557 
3558 /// objc-selector-expression
3559 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3560 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3561  SourceLocation SelectorLoc = ConsumeToken();
3562 
3563  if (Tok.isNot(tok::l_paren))
3564  return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3565 
3567  SourceLocation sLoc;
3568 
3569  BalancedDelimiterTracker T(*this, tok::l_paren);
3570  T.consumeOpen();
3571  bool HasOptionalParen = Tok.is(tok::l_paren);
3572  if (HasOptionalParen)
3573  ConsumeParen();
3574 
3575  if (Tok.is(tok::code_completion)) {
3576  Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3577  cutOffParsing();
3578  return ExprError();
3579  }
3580 
3581  IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3582  if (!SelIdent && // missing selector name.
3583  Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3584  return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3585 
3586  KeyIdents.push_back(SelIdent);
3587 
3588  unsigned nColons = 0;
3589  if (Tok.isNot(tok::r_paren)) {
3590  while (1) {
3591  if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3592  ++nColons;
3593  KeyIdents.push_back(nullptr);
3594  } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3595  return ExprError();
3596  ++nColons;
3597 
3598  if (Tok.is(tok::r_paren))
3599  break;
3600 
3601  if (Tok.is(tok::code_completion)) {
3602  Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3603  cutOffParsing();
3604  return ExprError();
3605  }
3606 
3607  // Check for another keyword selector.
3608  SourceLocation Loc;
3609  SelIdent = ParseObjCSelectorPiece(Loc);
3610  KeyIdents.push_back(SelIdent);
3611  if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3612  break;
3613  }
3614  }
3615  if (HasOptionalParen && Tok.is(tok::r_paren))
3616  ConsumeParen(); // ')'
3617  T.consumeClose();
3618  Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3619  return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3620  T.getOpenLocation(),
3621  T.getCloseLocation(),
3622  !HasOptionalParen);
3623 }
3624 
3625 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3626  // MCDecl might be null due to error in method or c-function prototype, etc.
3627  Decl *MCDecl = LM.D;
3628  bool skip = MCDecl &&
3629  ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3630  (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3631  if (skip)
3632  return;
3633 
3634  // Save the current token position.
3635  SourceLocation OrigLoc = Tok.getLocation();
3636 
3637  assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3638  // Store an artificial EOF token to ensure that we don't run off the end of
3639  // the method's body when we come to parse it.
3640  Token Eof;
3641  Eof.startToken();
3642  Eof.setKind(tok::eof);
3643  Eof.setEofData(MCDecl);
3644  Eof.setLocation(OrigLoc);
3645  LM.Toks.push_back(Eof);
3646  // Append the current token at the end of the new token stream so that it
3647  // doesn't get lost.
3648  LM.Toks.push_back(Tok);
3649  PP.EnterTokenStream(LM.Toks, true);
3650 
3651  // Consume the previously pushed token.
3652  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3653 
3654  assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3655  "Inline objective-c method not starting with '{' or 'try' or ':'");
3656  // Enter a scope for the method or c-function body.
3657  ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
3660 
3661  // Tell the actions module that we have entered a method or c-function definition
3662  // with the specified Declarator for the method/function.
3663  if (parseMethod)
3664  Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3665  else
3666  Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3667  if (Tok.is(tok::kw_try))
3668  ParseFunctionTryBlock(MCDecl, BodyScope);
3669  else {
3670  if (Tok.is(tok::colon))
3671  ParseConstructorInitializer(MCDecl);
3672  else
3673  Actions.ActOnDefaultCtorInitializers(MCDecl);
3674  ParseFunctionStatementBody(MCDecl, BodyScope);
3675  }
3676 
3677  if (Tok.getLocation() != OrigLoc) {
3678  // Due to parsing error, we either went over the cached tokens or
3679  // there are still cached tokens left. If it's the latter case skip the
3680  // leftover tokens.
3681  // Since this is an uncommon situation that should be avoided, use the
3682  // expensive isBeforeInTranslationUnit call.
3683  if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3684  OrigLoc))
3685  while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3686  ConsumeAnyToken();
3687  }
3688  // Clean up the remaining EOF token.
3689  ConsumeAnyToken();
3690 }
AttributePool & getAttributePool() const
Definition: DeclSpec.h:1851
Defines the clang::ASTContext interface.
bool isUsedAsTypeAttr() const
AttributeList * ArgAttrs
ArgAttrs - Attribute list for this argument.
Definition: Sema.h:8091
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:653
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:809
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:2153
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:282
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:822
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:765
StringRef P
The base class of the type hierarchy.
Definition: Type.h:1356
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:1124
Wrapper for void* pointer.
Definition: Ownership.h:51
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
void setObjCQualifiers(ObjCDeclSpec *quals)
Definition: DeclSpec.h:755
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:268
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1753
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:10154
friend class ObjCDeclContextSwitch
Definition: Parser.h:61
const IdentifierInfo * getSetterName() const
Definition: DeclSpec.h:857
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:8143
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:10180
bool isInvalidType() const
Definition: DeclSpec.h:2419
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:732
PtrTy get() const
Definition: Ownership.h:174
bool isNot(T Kind) const
Definition: FormatToken.h:318
Whether values of this type can be null is (explicitly) unspecified.
ObjCContainerKind
Definition: Sema.h:7848
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2149
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:2111
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1849
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:275
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:311
void setSetterName(IdentifierInfo *name, SourceLocation loc)
Definition: DeclSpec.h:860
SourceLocation NameLoc
Definition: Sema.h:8084
Expr - This represents one expression.
Definition: Expr.h:106
const FunctionProtoType * T
The message is an instance message.
Definition: Sema.h:8140
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:10151
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:1712
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:10157
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
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:827
A class for parsing a DeclSpec.
Context-sensitive version of a keyword attribute.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclBase.h:408
ObjCDeclQualifier
ObjCDeclQualifier - Qualifier used on types in method declarations.
Definition: DeclSpec.h:773
void CodeCompleteObjCAtDirective(Scope *S)
const AttributeList * getAttributes() const
Definition: DeclSpec.h:2381
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:302
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:819
The message is sent to &#39;super&#39;.
Definition: Sema.h:8138
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
AttributeList *& getAttrListRef()
Definition: DeclSpec.h:1519
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:8088
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:1515
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:812
void add(AttributeList *newAttr)
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:72
SourceLocation getNullabilityLoc() const
Definition: DeclSpec.h:834
void setNullability(SourceLocation loc, NullabilityKind kind)
Definition: DeclSpec.h:841
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:742
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2117
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13401
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:1842
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:849
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed...
Definition: DeclSpec.h:1202
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:852
void enter(ObjCTypeParamList *P)
Definition: ParseObjc.cpp:111
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const
Definition: FormatToken.h:336
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:92
AttributePool & getAttributePool() const
Definition: DeclSpec.h:711
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:45
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:738
IdentifierInfo * Name
Definition: Sema.h:8083
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