1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Objective-C portions of the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/PrettyDeclStackTrace.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Parse/RAIIObjectsForParser.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
25 using namespace clang;
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);
35 Diag(Tok, diag::err_objc_postfix_attribute);
36 ParseGNUAttributes(attrs);
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
48 Parser::DeclGroupPtrTy
49 Parser::ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs) {
50 SourceLocation AtLoc = ConsumeToken(); // the "@"
52 if (Tok.is(tok::code_completion)) {
53 Actions.CodeCompleteObjCAtDirective(getCurScope());
58 Decl *SingleDecl = nullptr;
59 switch (Tok.getObjCKeywordID()) {
61 return ParseObjCAtClassDeclaration(AtLoc);
62 case tok::objc_interface:
63 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, Attrs);
65 case tok::objc_protocol:
66 return ParseObjCAtProtocolDeclaration(AtLoc, Attrs);
67 case tok::objc_implementation:
68 return ParseObjCAtImplementationDeclaration(AtLoc);
70 return ParseObjCAtEndDeclaration(AtLoc);
71 case tok::objc_compatibility_alias:
72 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
74 case tok::objc_synthesize:
75 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
77 case tok::objc_dynamic:
78 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
80 case tok::objc_import:
81 if (getLangOpts().Modules || getLangOpts().DebuggerSupport) {
82 SingleDecl = ParseModuleImport(AtLoc);
85 Diag(AtLoc, diag::err_atimport);
87 return Actions.ConvertDeclToDeclGroup(nullptr);
89 Diag(AtLoc, diag::err_unexpected_at);
94 return Actions.ConvertDeclToDeclGroup(SingleDecl);
97 /// Class to handle popping type parameters when leaving the scope.
98 class Parser::ObjCTypeParamListScope {
101 ObjCTypeParamList *Params;
104 ObjCTypeParamListScope(Sema &Actions, Scope *S)
105 : Actions(Actions), S(S), Params(nullptr) {}
107 ~ObjCTypeParamListScope() {
111 void enter(ObjCTypeParamList *P) {
118 Actions.popObjCTypeParamList(S, Params);
124 /// objc-class-declaration:
125 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
127 /// objc-class-forward-decl:
128 /// identifier objc-type-parameter-list[opt]
130 Parser::DeclGroupPtrTy
131 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
132 ConsumeToken(); // the identifier "class"
133 SmallVector<IdentifierInfo *, 8> ClassNames;
134 SmallVector<SourceLocation, 8> ClassLocs;
135 SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
138 MaybeSkipAttributes(tok::objc_class);
139 if (expectIdentifier()) {
140 SkipUntil(tok::semi);
141 return Actions.ConvertDeclToDeclGroup(nullptr);
143 ClassNames.push_back(Tok.getIdentifierInfo());
144 ClassLocs.push_back(Tok.getLocation());
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))
157 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
158 return Actions.ConvertDeclToDeclGroup(nullptr);
160 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
166 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
168 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
169 if (ock == Sema::OCK_None)
172 Decl *Decl = Actions.getObjCDeclContext();
173 if (CurParsedObjCImpl) {
174 CurParsedObjCImpl->finish(AtLoc);
176 Actions.ActOnAtEnd(getCurScope(), AtLoc);
178 Diag(AtLoc, diag::err_objc_missing_end)
179 << FixItHint::CreateInsertion(AtLoc, "@end\n");
181 Diag(Decl->getBeginLoc(), diag::note_objc_container_start) << (int)ock;
186 /// objc-class-interface-attributes[opt] objc-class-interface
187 /// objc-category-interface
189 /// objc-class-interface:
190 /// '@' 'interface' identifier objc-type-parameter-list[opt]
191 /// objc-superclass[opt] objc-protocol-refs[opt]
192 /// objc-class-instance-variables[opt]
193 /// objc-interface-decl-list
196 /// objc-category-interface:
197 /// '@' 'interface' identifier objc-type-parameter-list[opt]
198 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
199 /// objc-interface-decl-list
203 /// ':' identifier objc-type-arguments[opt]
205 /// objc-class-interface-attributes:
206 /// __attribute__((visibility("default")))
207 /// __attribute__((visibility("hidden")))
208 /// __attribute__((deprecated))
209 /// __attribute__((unavailable))
210 /// __attribute__((objc_exception)) - used by NSException on 64-bit
211 /// __attribute__((objc_root_class))
213 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
214 ParsedAttributes &attrs) {
215 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
216 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
217 CheckNestedObjCContexts(AtLoc);
218 ConsumeToken(); // the "interface" identifier
220 // Code completion after '@interface'.
221 if (Tok.is(tok::code_completion)) {
222 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
227 MaybeSkipAttributes(tok::objc_interface);
229 if (expectIdentifier())
230 return nullptr; // missing class or category name.
232 // We have a class or category name - consume it.
233 IdentifierInfo *nameId = Tok.getIdentifierInfo();
234 SourceLocation nameLoc = ConsumeToken();
236 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
237 // case, LAngleLoc will be valid and ProtocolIdents will capture the
238 // protocol references (that have not yet been resolved).
239 SourceLocation LAngleLoc, EndProtoLoc;
240 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
241 ObjCTypeParamList *typeParameterList = nullptr;
242 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
243 if (Tok.is(tok::less))
244 typeParameterList = parseObjCTypeParamListOrProtocolRefs(
245 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
247 if (Tok.is(tok::l_paren) &&
248 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
250 BalancedDelimiterTracker T(*this, tok::l_paren);
253 SourceLocation categoryLoc;
254 IdentifierInfo *categoryId = nullptr;
255 if (Tok.is(tok::code_completion)) {
256 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
261 // For ObjC2, the category name is optional (not an error).
262 if (Tok.is(tok::identifier)) {
263 categoryId = Tok.getIdentifierInfo();
264 categoryLoc = ConsumeToken();
266 else if (!getLangOpts().ObjC) {
267 Diag(Tok, diag::err_expected)
268 << tok::identifier; // missing category name.
273 if (T.getCloseLocation().isInvalid())
276 // Next, we need to check for any protocol references.
277 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
278 SmallVector<Decl *, 8> ProtocolRefs;
279 SmallVector<SourceLocation, 8> ProtocolLocs;
280 if (Tok.is(tok::less) &&
281 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
282 LAngleLoc, EndProtoLoc,
283 /*consumeLastToken=*/true))
286 Decl *CategoryType = Actions.ActOnStartCategoryInterface(
287 AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
288 ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
291 if (Tok.is(tok::l_brace))
292 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
294 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
298 // Parse a class interface.
299 IdentifierInfo *superClassId = nullptr;
300 SourceLocation superClassLoc;
301 SourceLocation typeArgsLAngleLoc;
302 SmallVector<ParsedType, 4> typeArgs;
303 SourceLocation typeArgsRAngleLoc;
304 SmallVector<Decl *, 4> protocols;
305 SmallVector<SourceLocation, 4> protocolLocs;
306 if (Tok.is(tok::colon)) { // a super class is specified.
309 // Code completion of superclass names.
310 if (Tok.is(tok::code_completion)) {
311 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
316 if (expectIdentifier())
317 return nullptr; // missing super class name.
318 superClassId = Tok.getIdentifierInfo();
319 superClassLoc = ConsumeToken();
321 // Type arguments for the superclass or protocol conformances.
322 if (Tok.is(tok::less)) {
323 parseObjCTypeArgsOrProtocolQualifiers(
324 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
325 protocols, protocolLocs, EndProtoLoc,
326 /*consumeLastToken=*/true,
327 /*warnOnIncompleteProtocols=*/true);
328 if (Tok.is(tok::eof))
333 // Next, we need to check for any protocol references.
334 if (LAngleLoc.isValid()) {
335 if (!ProtocolIdents.empty()) {
336 // We already parsed the protocols named when we thought we had a
337 // type parameter list. Translate them into actual protocol references.
338 for (const auto &pair : ProtocolIdents) {
339 protocolLocs.push_back(pair.second);
341 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
342 /*ForObjCContainer=*/true,
343 ProtocolIdents, protocols);
345 } else if (protocols.empty() && Tok.is(tok::less) &&
346 ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
347 LAngleLoc, EndProtoLoc,
348 /*consumeLastToken=*/true)) {
352 if (Tok.isNot(tok::less))
353 Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
354 superClassId, superClassLoc);
356 Decl *ClsType = Actions.ActOnStartClassInterface(
357 getCurScope(), AtLoc, nameId, nameLoc, typeParameterList, superClassId,
358 superClassLoc, typeArgs,
359 SourceRange(typeArgsLAngleLoc, typeArgsRAngleLoc), protocols.data(),
360 protocols.size(), protocolLocs.data(), EndProtoLoc, attrs);
362 if (Tok.is(tok::l_brace))
363 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
365 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
370 /// Add an attribute for a context-sensitive type nullability to the given
372 static void addContextSensitiveTypeNullability(Parser &P,
374 NullabilityKind nullability,
375 SourceLocation nullabilityLoc,
376 bool &addedToDeclSpec) {
377 // Create the attribute.
378 auto getNullabilityAttr = [&](AttributePool &Pool) -> ParsedAttr * {
379 return Pool.create(P.getNullabilityKeyword(nullability),
380 SourceRange(nullabilityLoc), nullptr, SourceLocation(),
381 nullptr, 0, ParsedAttr::AS_ContextSensitiveKeyword);
384 if (D.getNumTypeObjects() > 0) {
385 // Add the attribute to the declarator chunk nearest the declarator.
386 D.getTypeObject(0).getAttrs().addAtEnd(
387 getNullabilityAttr(D.getAttributePool()));
388 } else if (!addedToDeclSpec) {
389 // Otherwise, just put it on the declaration specifiers (if one
390 // isn't there already).
391 D.getMutableDeclSpec().getAttributes().addAtEnd(
392 getNullabilityAttr(D.getMutableDeclSpec().getAttributes().getPool()));
393 addedToDeclSpec = true;
397 /// Parse an Objective-C type parameter list, if present, or capture
398 /// the locations of the protocol identifiers for a list of protocol
401 /// objc-type-parameter-list:
402 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
404 /// objc-type-parameter:
405 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
407 /// objc-type-parameter-bound:
410 /// objc-type-parameter-variance:
412 /// '__contravariant'
414 /// \param lAngleLoc The location of the starting '<'.
416 /// \param protocolIdents Will capture the list of identifiers, if the
417 /// angle brackets contain a list of protocol references rather than a
418 /// type parameter list.
420 /// \param rAngleLoc The location of the ending '>'.
421 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
422 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
423 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
424 SourceLocation &rAngleLoc, bool mayBeProtocolList) {
425 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
427 // Within the type parameter list, don't treat '>' as an operator.
428 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
430 // Local function to "flush" the protocol identifiers, turning them into
432 SmallVector<Decl *, 4> typeParams;
433 auto makeProtocolIdentsIntoTypeParameters = [&]() {
435 for (const auto &pair : protocolIdents) {
436 DeclResult typeParam = Actions.actOnObjCTypeParam(
437 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
438 index++, pair.first, pair.second, SourceLocation(), nullptr);
439 if (typeParam.isUsable())
440 typeParams.push_back(typeParam.get());
443 protocolIdents.clear();
444 mayBeProtocolList = false;
447 bool invalid = false;
448 lAngleLoc = ConsumeToken();
451 // Parse the variance, if any.
452 SourceLocation varianceLoc;
453 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
454 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
455 variance = Tok.is(tok::kw___covariant)
456 ? ObjCTypeParamVariance::Covariant
457 : ObjCTypeParamVariance::Contravariant;
458 varianceLoc = ConsumeToken();
460 // Once we've seen a variance specific , we know this is not a
461 // list of protocol references.
462 if (mayBeProtocolList) {
463 // Up until now, we have been queuing up parameters because they
464 // might be protocol references. Turn them into parameters now.
465 makeProtocolIdentsIntoTypeParameters();
469 // Parse the identifier.
470 if (!Tok.is(tok::identifier)) {
472 if (Tok.is(tok::code_completion)) {
473 // FIXME: If these aren't protocol references, we'll need different
475 Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
478 // FIXME: Better recovery here?.
482 Diag(Tok, diag::err_objc_expected_type_parameter);
487 IdentifierInfo *paramName = Tok.getIdentifierInfo();
488 SourceLocation paramLoc = ConsumeToken();
490 // If there is a bound, parse it.
491 SourceLocation colonLoc;
492 TypeResult boundType;
493 if (TryConsumeToken(tok::colon, colonLoc)) {
494 // Once we've seen a bound, we know this is not a list of protocol
496 if (mayBeProtocolList) {
497 // Up until now, we have been queuing up parameters because they
498 // might be protocol references. Turn them into parameters now.
499 makeProtocolIdentsIntoTypeParameters();
503 boundType = ParseTypeName();
504 if (boundType.isInvalid())
506 } else if (mayBeProtocolList) {
507 // If this could still be a protocol list, just capture the identifier.
508 // We don't want to turn it into a parameter.
509 protocolIdents.push_back(std::make_pair(paramName, paramLoc));
513 // Create the type parameter.
514 DeclResult typeParam = Actions.actOnObjCTypeParam(
515 getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
516 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
517 if (typeParam.isUsable())
518 typeParams.push_back(typeParam.get());
519 } while (TryConsumeToken(tok::comma));
523 SkipUntil(tok::greater, tok::at, StopBeforeMatch);
524 if (Tok.is(tok::greater))
526 } else if (ParseGreaterThanInTemplateList(rAngleLoc,
527 /*ConsumeLastToken=*/true,
528 /*ObjCGenericList=*/true)) {
529 Diag(lAngleLoc, diag::note_matching) << "'<'";
530 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
531 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
532 tok::comma, tok::semi },
534 if (Tok.is(tok::greater))
538 if (mayBeProtocolList) {
539 // A type parameter list must be followed by either a ':' (indicating the
540 // presence of a superclass) or a '(' (indicating that this is a category
541 // or extension). This disambiguates between an objc-type-parameter-list
542 // and a objc-protocol-refs.
543 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
544 // Returning null indicates that we don't have a type parameter list.
545 // The results the caller needs to handle the protocol references are
546 // captured in the reference parameters already.
550 // We have a type parameter list that looks like a list of protocol
551 // references. Turn that parameter list into type parameters.
552 makeProtocolIdentsIntoTypeParameters();
555 // Form the type parameter list and enter its scope.
556 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
563 // Clear out the angle locations; they're used by the caller to indicate
564 // whether there are any protocol references.
565 lAngleLoc = SourceLocation();
566 rAngleLoc = SourceLocation();
567 return invalid ? nullptr : list;
570 /// Parse an objc-type-parameter-list.
571 ObjCTypeParamList *Parser::parseObjCTypeParamList() {
572 SourceLocation lAngleLoc;
573 SmallVector<IdentifierLocPair, 1> protocolIdents;
574 SourceLocation rAngleLoc;
576 ObjCTypeParamListScope Scope(Actions, getCurScope());
577 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
579 /*mayBeProtocolList=*/false);
582 /// objc-interface-decl-list:
584 /// objc-interface-decl-list objc-property-decl [OBJC2]
585 /// objc-interface-decl-list objc-method-requirement [OBJC2]
586 /// objc-interface-decl-list objc-method-proto ';'
587 /// objc-interface-decl-list declaration
588 /// objc-interface-decl-list ';'
590 /// objc-method-requirement: [OBJC2]
594 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
596 SmallVector<Decl *, 32> allMethods;
597 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
598 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
603 // If this is a method prototype, parse it.
604 if (Tok.isOneOf(tok::minus, tok::plus)) {
605 if (Decl *methodPrototype =
606 ParseObjCMethodPrototype(MethodImplKind, false))
607 allMethods.push_back(methodPrototype);
608 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
609 // method definitions.
610 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
611 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
612 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
613 if (Tok.is(tok::semi))
618 if (Tok.is(tok::l_paren)) {
619 Diag(Tok, diag::err_expected_minus_or_plus);
620 ParseObjCMethodDecl(Tok.getLocation(),
622 MethodImplKind, false);
625 // Ignore excess semicolons.
626 if (Tok.is(tok::semi)) {
631 // If we got to the end of the file, exit the loop.
635 // Code completion within an Objective-C interface.
636 if (Tok.is(tok::code_completion)) {
637 Actions.CodeCompleteOrdinaryName(getCurScope(),
638 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
639 : Sema::PCC_ObjCInterface);
640 return cutOffParsing();
643 // If we don't have an @ directive, parse it as a function definition.
644 if (Tok.isNot(tok::at)) {
645 // The code below does not consume '}'s because it is afraid of eating the
646 // end of a namespace. Because of the way this code is structured, an
647 // erroneous r_brace would cause an infinite loop if not handled here.
648 if (Tok.is(tok::r_brace))
650 ParsedAttributesWithRange attrs(AttrFactory);
651 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
655 // Otherwise, we have an @ directive, eat the @.
656 SourceLocation AtLoc = ConsumeToken(); // the "@"
657 if (Tok.is(tok::code_completion)) {
658 Actions.CodeCompleteObjCAtDirective(getCurScope());
659 return cutOffParsing();
662 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
664 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
665 AtEnd.setBegin(AtLoc);
666 AtEnd.setEnd(Tok.getLocation());
668 } else if (DirectiveKind == tok::objc_not_keyword) {
669 Diag(Tok, diag::err_objc_unknown_at);
670 SkipUntil(tok::semi);
674 // Eat the identifier.
677 switch (DirectiveKind) {
679 // FIXME: If someone forgets an @end on a protocol, this loop will
680 // continue to eat up tons of stuff and spew lots of nonsense errors. It
681 // would probably be better to bail out if we saw an @class or @interface
682 // or something like that.
683 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
684 // Skip until we see an '@' or '}' or ';'.
685 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
688 case tok::objc_implementation:
689 case tok::objc_interface:
690 Diag(AtLoc, diag::err_objc_missing_end)
691 << FixItHint::CreateInsertion(AtLoc, "@end\n");
692 Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
693 << (int)Actions.getObjCContainerKind();
697 case tok::objc_required:
698 case tok::objc_optional:
699 // This is only valid on protocols.
700 // FIXME: Should this check for ObjC2 being enabled?
701 if (contextKey != tok::objc_protocol)
702 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
704 MethodImplKind = DirectiveKind;
707 case tok::objc_property:
708 if (!getLangOpts().ObjC)
709 Diag(AtLoc, diag::err_objc_properties_require_objc2);
712 SourceLocation LParenLoc;
713 // Parse property attribute list, if any.
714 if (Tok.is(tok::l_paren)) {
715 LParenLoc = Tok.getLocation();
716 ParseObjCPropertyAttribute(OCDS);
719 bool addedToDeclSpec = false;
720 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
721 if (FD.D.getIdentifier() == nullptr) {
722 Diag(AtLoc, diag::err_objc_property_requires_field_name)
723 << FD.D.getSourceRange();
726 if (FD.BitfieldSize) {
727 Diag(AtLoc, diag::err_objc_property_bitfield)
728 << FD.D.getSourceRange();
732 // Map a nullability property attribute to a context-sensitive keyword
734 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
735 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
736 OCDS.getNullabilityLoc(),
739 // Install the property declarator into interfaceDecl.
740 IdentifierInfo *SelName =
741 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
743 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
744 IdentifierInfo *SetterName = OCDS.getSetterName();
747 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
749 SetterSel = SelectorTable::constructSetterSelector(
750 PP.getIdentifierTable(), PP.getSelectorTable(),
751 FD.D.getIdentifier());
752 Decl *Property = Actions.ActOnProperty(
753 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
756 FD.complete(Property);
759 // Parse all the comma separated declarators.
760 ParsingDeclSpec DS(*this);
761 ParseStructDeclaration(DS, ObjCPropertyCallback);
763 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
768 // We break out of the big loop in two cases: when we see @end or when we see
769 // EOF. In the former case, eat the @end. In the later case, emit an error.
770 if (Tok.is(tok::code_completion)) {
771 Actions.CodeCompleteObjCAtDirective(getCurScope());
772 return cutOffParsing();
773 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
774 ConsumeToken(); // the "end" identifier
776 Diag(Tok, diag::err_objc_missing_end)
777 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
778 Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
779 << (int)Actions.getObjCContainerKind();
780 AtEnd.setBegin(Tok.getLocation());
781 AtEnd.setEnd(Tok.getLocation());
784 // Insert collected methods declarations into the @interface object.
785 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
786 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
789 /// Diagnose redundant or conflicting nullability information.
790 static void diagnoseRedundantPropertyNullability(Parser &P,
792 NullabilityKind nullability,
793 SourceLocation nullabilityLoc){
794 if (DS.getNullability() == nullability) {
795 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
796 << DiagNullabilityKind(nullability, true)
797 << SourceRange(DS.getNullabilityLoc());
801 P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
802 << DiagNullabilityKind(nullability, true)
803 << DiagNullabilityKind(DS.getNullability(), true)
804 << SourceRange(DS.getNullabilityLoc());
807 /// Parse property attribute declarations.
809 /// property-attr-decl: '(' property-attrlist ')'
810 /// property-attrlist:
811 /// property-attribute
812 /// property-attrlist ',' property-attribute
813 /// property-attribute:
814 /// getter '=' identifier
815 /// setter '=' identifier ':'
825 /// unsafe_unretained
832 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
833 assert(Tok.getKind() == tok::l_paren);
834 BalancedDelimiterTracker T(*this, tok::l_paren);
838 if (Tok.is(tok::code_completion)) {
839 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
840 return cutOffParsing();
842 const IdentifierInfo *II = Tok.getIdentifierInfo();
844 // If this is not an identifier at all, bail out early.
850 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
852 if (II->isStr("readonly"))
853 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
854 else if (II->isStr("assign"))
855 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
856 else if (II->isStr("unsafe_unretained"))
857 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
858 else if (II->isStr("readwrite"))
859 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
860 else if (II->isStr("retain"))
861 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
862 else if (II->isStr("strong"))
863 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
864 else if (II->isStr("copy"))
865 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
866 else if (II->isStr("nonatomic"))
867 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
868 else if (II->isStr("atomic"))
869 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
870 else if (II->isStr("weak"))
871 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
872 else if (II->isStr("getter") || II->isStr("setter")) {
873 bool IsSetter = II->getNameStart()[0] == 's';
875 // getter/setter require extra treatment.
876 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
877 diag::err_objc_expected_equal_for_getter;
879 if (ExpectAndConsume(tok::equal, DiagID)) {
880 SkipUntil(tok::r_paren, StopAtSemi);
884 if (Tok.is(tok::code_completion)) {
886 Actions.CodeCompleteObjCPropertySetter(getCurScope());
888 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
889 return cutOffParsing();
892 SourceLocation SelLoc;
893 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
896 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
898 SkipUntil(tok::r_paren, StopAtSemi);
903 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
904 DS.setSetterName(SelIdent, SelLoc);
906 if (ExpectAndConsume(tok::colon,
907 diag::err_expected_colon_after_setter_name)) {
908 SkipUntil(tok::r_paren, StopAtSemi);
912 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
913 DS.setGetterName(SelIdent, SelLoc);
915 } else if (II->isStr("nonnull")) {
916 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
917 diagnoseRedundantPropertyNullability(*this, DS,
918 NullabilityKind::NonNull,
920 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
921 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
922 } else if (II->isStr("nullable")) {
923 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
924 diagnoseRedundantPropertyNullability(*this, DS,
925 NullabilityKind::Nullable,
927 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
928 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
929 } else if (II->isStr("null_unspecified")) {
930 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
931 diagnoseRedundantPropertyNullability(*this, DS,
932 NullabilityKind::Unspecified,
934 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
935 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
936 } else if (II->isStr("null_resettable")) {
937 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
938 diagnoseRedundantPropertyNullability(*this, DS,
939 NullabilityKind::Unspecified,
941 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
942 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
944 // Also set the null_resettable bit.
945 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable);
946 } else if (II->isStr("class")) {
947 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class);
949 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
950 SkipUntil(tok::r_paren, StopAtSemi);
954 if (Tok.isNot(tok::comma))
963 /// objc-method-proto:
964 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
965 /// objc-class-method objc-method-decl objc-method-attributes[opt]
967 /// objc-instance-method: '-'
968 /// objc-class-method: '+'
970 /// objc-method-attributes: [OBJC2]
971 /// __attribute__((deprecated))
973 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
974 bool MethodDefinition) {
975 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
977 tok::TokenKind methodType = Tok.getKind();
978 SourceLocation mLoc = ConsumeToken();
979 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
981 // Since this rule is used for both method declarations and definitions,
982 // the caller is (optionally) responsible for consuming the ';'.
989 /// enum struct union if else while do for switch case default
990 /// break continue return goto asm sizeof typeof __alignof
991 /// unsigned long const short volatile signed restrict _Complex
992 /// in out inout bycopy byref oneway int char float double void _Bool
994 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
996 switch (Tok.getKind()) {
1000 // Empty selector piece uses the location of the ':'.
1001 SelectorLoc = Tok.getLocation();
1009 case tok::exclaimequal:
1011 case tok::pipeequal:
1013 case tok::caretequal: {
1014 std::string ThisTok(PP.getSpelling(Tok));
1015 if (isLetter(ThisTok[0])) {
1016 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1017 Tok.setKind(tok::identifier);
1018 SelectorLoc = ConsumeToken();
1024 case tok::identifier:
1034 case tok::kw_const_cast:
1035 case tok::kw_continue:
1036 case tok::kw_default:
1037 case tok::kw_delete:
1039 case tok::kw_double:
1040 case tok::kw_dynamic_cast:
1043 case tok::kw_explicit:
1044 case tok::kw_export:
1045 case tok::kw_extern:
1049 case tok::kw_friend:
1052 case tok::kw_inline:
1055 case tok::kw_mutable:
1056 case tok::kw_namespace:
1058 case tok::kw_operator:
1059 case tok::kw_private:
1060 case tok::kw_protected:
1061 case tok::kw_public:
1062 case tok::kw_register:
1063 case tok::kw_reinterpret_cast:
1064 case tok::kw_restrict:
1065 case tok::kw_return:
1067 case tok::kw_signed:
1068 case tok::kw_sizeof:
1069 case tok::kw_static:
1070 case tok::kw_static_cast:
1071 case tok::kw_struct:
1072 case tok::kw_switch:
1073 case tok::kw_template:
1078 case tok::kw_typedef:
1079 case tok::kw_typeid:
1080 case tok::kw_typename:
1081 case tok::kw_typeof:
1083 case tok::kw_unsigned:
1085 case tok::kw_virtual:
1087 case tok::kw_volatile:
1088 case tok::kw_wchar_t:
1091 case tok::kw__Complex:
1092 case tok::kw___alignof:
1093 case tok::kw___auto_type:
1094 IdentifierInfo *II = Tok.getIdentifierInfo();
1095 SelectorLoc = ConsumeToken();
1100 /// objc-for-collection-in: 'in'
1102 bool Parser::isTokIdentifier_in() const {
1103 // FIXME: May have to do additional look-ahead to only allow for
1104 // valid tokens following an 'in'; such as an identifier, unary operators,
1106 return (getLangOpts().ObjC && Tok.is(tok::identifier) &&
1107 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1110 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1111 /// qualifier list and builds their bitmask representation in the input
1114 /// objc-type-qualifiers:
1115 /// objc-type-qualifier
1116 /// objc-type-qualifiers objc-type-qualifier
1118 /// objc-type-qualifier:
1127 /// 'null_unspecified'
1129 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1130 DeclaratorContext Context) {
1131 assert(Context == DeclaratorContext::ObjCParameterContext ||
1132 Context == DeclaratorContext::ObjCResultContext);
1135 if (Tok.is(tok::code_completion)) {
1136 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
1137 Context == DeclaratorContext::ObjCParameterContext);
1138 return cutOffParsing();
1141 if (Tok.isNot(tok::identifier))
1144 const IdentifierInfo *II = Tok.getIdentifierInfo();
1145 for (unsigned i = 0; i != objc_NumQuals; ++i) {
1146 if (II != ObjCTypeQuals[i] ||
1147 NextToken().is(tok::less) ||
1148 NextToken().is(tok::coloncolon))
1151 ObjCDeclSpec::ObjCDeclQualifier Qual;
1152 NullabilityKind Nullability;
1154 default: llvm_unreachable("Unknown decl qualifier");
1155 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
1156 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
1157 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
1158 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1159 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1160 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
1163 Qual = ObjCDeclSpec::DQ_CSNullability;
1164 Nullability = NullabilityKind::NonNull;
1168 Qual = ObjCDeclSpec::DQ_CSNullability;
1169 Nullability = NullabilityKind::Nullable;
1172 case objc_null_unspecified:
1173 Qual = ObjCDeclSpec::DQ_CSNullability;
1174 Nullability = NullabilityKind::Unspecified;
1178 // FIXME: Diagnose redundant specifiers.
1179 DS.setObjCDeclQualifier(Qual);
1180 if (Qual == ObjCDeclSpec::DQ_CSNullability)
1181 DS.setNullability(Tok.getLocation(), Nullability);
1188 // If this wasn't a recognized qualifier, bail out.
1193 /// Take all the decl attributes out of the given list and add
1194 /// them to the given attribute set.
1195 static void takeDeclAttributes(ParsedAttributesView &attrs,
1196 ParsedAttributesView &from) {
1197 for (auto &AL : llvm::reverse(from)) {
1198 if (!AL.isUsedAsTypeAttr()) {
1200 attrs.addAtEnd(&AL);
1205 /// takeDeclAttributes - Take all the decl attributes from the given
1206 /// declarator and add them to the given list.
1207 static void takeDeclAttributes(ParsedAttributes &attrs,
1209 // First, take ownership of all attributes.
1210 attrs.getPool().takeAllFrom(D.getAttributePool());
1211 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1213 // Now actually move the attributes over.
1214 takeDeclAttributes(attrs, D.getMutableDeclSpec().getAttributes());
1215 takeDeclAttributes(attrs, D.getAttributes());
1216 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1217 takeDeclAttributes(attrs, D.getTypeObject(i).getAttrs());
1221 /// '(' objc-type-qualifiers[opt] type-name ')'
1222 /// '(' objc-type-qualifiers[opt] ')'
1224 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1225 DeclaratorContext context,
1226 ParsedAttributes *paramAttrs) {
1227 assert(context == DeclaratorContext::ObjCParameterContext ||
1228 context == DeclaratorContext::ObjCResultContext);
1229 assert((paramAttrs != nullptr) ==
1230 (context == DeclaratorContext::ObjCParameterContext));
1232 assert(Tok.is(tok::l_paren) && "expected (");
1234 BalancedDelimiterTracker T(*this, tok::l_paren);
1237 SourceLocation TypeStartLoc = Tok.getLocation();
1238 ObjCDeclContextSwitch ObjCDC(*this);
1240 // Parse type qualifiers, in, inout, etc.
1241 ParseObjCTypeQualifierList(DS, context);
1244 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1245 // Parse an abstract declarator.
1246 DeclSpec declSpec(AttrFactory);
1247 declSpec.setObjCQualifiers(&DS);
1248 DeclSpecContext dsContext = DeclSpecContext::DSC_normal;
1249 if (context == DeclaratorContext::ObjCResultContext)
1250 dsContext = DeclSpecContext::DSC_objc_method_result;
1251 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1252 Declarator declarator(declSpec, context);
1253 ParseDeclarator(declarator);
1255 // If that's not invalid, extract a type.
1256 if (!declarator.isInvalidType()) {
1257 // Map a nullability specifier to a context-sensitive keyword attribute.
1258 bool addedToDeclSpec = false;
1259 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1260 addContextSensitiveTypeNullability(*this, declarator,
1261 DS.getNullability(),
1262 DS.getNullabilityLoc(),
1265 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1266 if (!type.isInvalid())
1269 // If we're parsing a parameter, steal all the decl attributes
1270 // and add them to the decl spec.
1271 if (context == DeclaratorContext::ObjCParameterContext)
1272 takeDeclAttributes(*paramAttrs, declarator);
1276 if (Tok.is(tok::r_paren))
1278 else if (Tok.getLocation() == TypeStartLoc) {
1279 // If we didn't eat any tokens, then this isn't a type.
1280 Diag(Tok, diag::err_expected_type);
1281 SkipUntil(tok::r_paren, StopAtSemi);
1283 // Otherwise, we found *something*, but didn't get a ')' in the right
1284 // place. Emit an error then return what we have as the type.
1290 /// objc-method-decl:
1292 /// objc-keyword-selector objc-parmlist[opt]
1293 /// objc-type-name objc-selector
1294 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1296 /// objc-keyword-selector:
1297 /// objc-keyword-decl
1298 /// objc-keyword-selector objc-keyword-decl
1300 /// objc-keyword-decl:
1301 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1302 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1303 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1304 /// ':' objc-keyword-attributes[opt] identifier
1307 /// objc-parms objc-ellipsis[opt]
1310 /// objc-parms , parameter-declaration
1315 /// objc-keyword-attributes: [OBJC2]
1316 /// __attribute__((unused))
1318 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1319 tok::TokenKind mType,
1320 tok::ObjCKeywordKind MethodImplKind,
1321 bool MethodDefinition) {
1322 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1324 if (Tok.is(tok::code_completion)) {
1325 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1326 /*ReturnType=*/nullptr);
1331 // Parse the return type if present.
1332 ParsedType ReturnType;
1334 if (Tok.is(tok::l_paren))
1335 ReturnType = ParseObjCTypeName(DSRet, DeclaratorContext::ObjCResultContext,
1338 // If attributes exist before the method, parse them.
1339 ParsedAttributes methodAttrs(AttrFactory);
1340 if (getLangOpts().ObjC)
1341 MaybeParseGNUAttributes(methodAttrs);
1342 MaybeParseCXX11Attributes(methodAttrs);
1344 if (Tok.is(tok::code_completion)) {
1345 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1351 // Now parse the selector.
1352 SourceLocation selLoc;
1353 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1355 // An unnamed colon is valid.
1356 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1357 Diag(Tok, diag::err_expected_selector_for_method)
1358 << SourceRange(mLoc, Tok.getLocation());
1359 // Skip until we get a ; or @.
1360 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1364 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1365 if (Tok.isNot(tok::colon)) {
1366 // If attributes exist after the method, parse them.
1367 if (getLangOpts().ObjC)
1368 MaybeParseGNUAttributes(methodAttrs);
1369 MaybeParseCXX11Attributes(methodAttrs);
1371 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1372 Decl *Result = Actions.ActOnMethodDeclaration(
1373 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType,
1374 selLoc, Sel, nullptr, CParamInfo.data(), CParamInfo.size(), methodAttrs,
1375 MethodImplKind, false, MethodDefinition);
1376 PD.complete(Result);
1380 SmallVector<IdentifierInfo *, 12> KeyIdents;
1381 SmallVector<SourceLocation, 12> KeyLocs;
1382 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1383 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1384 Scope::FunctionDeclarationScope | Scope::DeclScope);
1386 AttributePool allParamAttrs(AttrFactory);
1388 ParsedAttributes paramAttrs(AttrFactory);
1389 Sema::ObjCArgInfo ArgInfo;
1391 // Each iteration parses a single keyword argument.
1392 if (ExpectAndConsume(tok::colon))
1395 ArgInfo.Type = nullptr;
1396 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1397 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1398 DeclaratorContext::ObjCParameterContext,
1401 // If attributes exist before the argument name, parse them.
1402 // Regardless, collect all the attributes we've parsed so far.
1403 if (getLangOpts().ObjC)
1404 MaybeParseGNUAttributes(paramAttrs);
1405 MaybeParseCXX11Attributes(paramAttrs);
1406 ArgInfo.ArgAttrs = paramAttrs;
1408 // Code completion for the next piece of the selector.
1409 if (Tok.is(tok::code_completion)) {
1410 KeyIdents.push_back(SelIdent);
1411 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1412 mType == tok::minus,
1413 /*AtParameterName=*/true,
1414 ReturnType, KeyIdents);
1419 if (expectIdentifier())
1420 break; // missing argument name.
1422 ArgInfo.Name = Tok.getIdentifierInfo();
1423 ArgInfo.NameLoc = Tok.getLocation();
1424 ConsumeToken(); // Eat the identifier.
1426 ArgInfos.push_back(ArgInfo);
1427 KeyIdents.push_back(SelIdent);
1428 KeyLocs.push_back(selLoc);
1430 // Make sure the attributes persist.
1431 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1433 // Code completion for the next piece of the selector.
1434 if (Tok.is(tok::code_completion)) {
1435 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1436 mType == tok::minus,
1437 /*AtParameterName=*/false,
1438 ReturnType, KeyIdents);
1443 // Check for another keyword selector.
1444 SelIdent = ParseObjCSelectorPiece(selLoc);
1445 if (!SelIdent && Tok.isNot(tok::colon))
1448 SourceLocation ColonLoc = Tok.getLocation();
1449 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1450 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1451 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1452 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1455 // We have a selector or a colon, continue parsing.
1458 bool isVariadic = false;
1459 bool cStyleParamWarned = false;
1460 // Parse the (optional) parameter list.
1461 while (Tok.is(tok::comma)) {
1463 if (Tok.is(tok::ellipsis)) {
1468 if (!cStyleParamWarned) {
1469 Diag(Tok, diag::warn_cstyle_param);
1470 cStyleParamWarned = true;
1472 DeclSpec DS(AttrFactory);
1473 ParseDeclarationSpecifiers(DS);
1474 // Parse the declarator.
1475 Declarator ParmDecl(DS, DeclaratorContext::PrototypeContext);
1476 ParseDeclarator(ParmDecl);
1477 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1478 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1479 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1480 ParmDecl.getIdentifierLoc(),
1485 // FIXME: Add support for optional parameter list...
1486 // If attributes exist after the method, parse them.
1487 if (getLangOpts().ObjC)
1488 MaybeParseGNUAttributes(methodAttrs);
1489 MaybeParseCXX11Attributes(methodAttrs);
1491 if (KeyIdents.size() == 0)
1494 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1496 Decl *Result = Actions.ActOnMethodDeclaration(
1497 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, KeyLocs,
1498 Sel, &ArgInfos[0], CParamInfo.data(), CParamInfo.size(), methodAttrs,
1499 MethodImplKind, isVariadic, MethodDefinition);
1501 PD.complete(Result);
1505 /// objc-protocol-refs:
1506 /// '<' identifier-list '>'
1509 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1510 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1511 bool WarnOnDeclarations, bool ForObjCContainer,
1512 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1513 bool consumeLastToken) {
1514 assert(Tok.is(tok::less) && "expected <");
1516 LAngleLoc = ConsumeToken(); // the "<"
1518 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1521 if (Tok.is(tok::code_completion)) {
1522 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1527 if (expectIdentifier()) {
1528 SkipUntil(tok::greater, StopAtSemi);
1531 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1532 Tok.getLocation()));
1533 ProtocolLocs.push_back(Tok.getLocation());
1536 if (!TryConsumeToken(tok::comma))
1541 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1542 /*ObjCGenericList=*/false))
1545 // Convert the list of protocols identifiers into a list of protocol decls.
1546 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1547 ProtocolIdents, Protocols);
1551 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1552 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1553 assert(getLangOpts().ObjC && "Protocol qualifiers only exist in Objective-C");
1555 SourceLocation lAngleLoc;
1556 SmallVector<Decl *, 8> protocols;
1557 SmallVector<SourceLocation, 8> protocolLocs;
1558 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1559 lAngleLoc, rAngleLoc,
1560 /*consumeLastToken=*/true);
1561 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1565 if (result.isUsable()) {
1566 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1567 << FixItHint::CreateInsertion(lAngleLoc, "id")
1568 << SourceRange(lAngleLoc, rAngleLoc);
1574 /// Parse Objective-C type arguments or protocol qualifiers.
1576 /// objc-type-arguments:
1577 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1579 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1580 ParsedType baseType,
1581 SourceLocation &typeArgsLAngleLoc,
1582 SmallVectorImpl<ParsedType> &typeArgs,
1583 SourceLocation &typeArgsRAngleLoc,
1584 SourceLocation &protocolLAngleLoc,
1585 SmallVectorImpl<Decl *> &protocols,
1586 SmallVectorImpl<SourceLocation> &protocolLocs,
1587 SourceLocation &protocolRAngleLoc,
1588 bool consumeLastToken,
1589 bool warnOnIncompleteProtocols) {
1590 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1591 SourceLocation lAngleLoc = ConsumeToken();
1593 // Whether all of the elements we've parsed thus far are single
1594 // identifiers, which might be types or might be protocols.
1595 bool allSingleIdentifiers = true;
1596 SmallVector<IdentifierInfo *, 4> identifiers;
1597 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1599 // Parse a list of comma-separated identifiers, bailing out if we
1600 // see something different.
1602 // Parse a single identifier.
1603 if (Tok.is(tok::identifier) &&
1604 (NextToken().is(tok::comma) ||
1605 NextToken().is(tok::greater) ||
1606 NextToken().is(tok::greatergreater))) {
1607 identifiers.push_back(Tok.getIdentifierInfo());
1608 identifierLocs.push_back(ConsumeToken());
1612 if (Tok.is(tok::code_completion)) {
1613 // FIXME: Also include types here.
1614 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1615 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1616 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1617 identifierLocs[i]));
1620 QualType BaseT = Actions.GetTypeFromParser(baseType);
1621 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1622 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1624 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1630 allSingleIdentifiers = false;
1632 } while (TryConsumeToken(tok::comma));
1634 // If we parsed an identifier list, semantic analysis sorts out
1635 // whether it refers to protocols or to type arguments.
1636 if (allSingleIdentifiers) {
1637 // Parse the closing '>'.
1638 SourceLocation rAngleLoc;
1639 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1640 /*ObjCGenericList=*/true);
1642 // Let Sema figure out what we parsed.
1643 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1655 warnOnIncompleteProtocols);
1659 // We parsed an identifier list but stumbled into non single identifiers, this
1660 // means we might (a) check that what we already parsed is a legitimate type
1661 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1662 // must all be type args.
1664 // Convert the identifiers into type arguments.
1665 bool invalid = false;
1666 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1667 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1668 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1669 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1671 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1673 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1675 DeclSpec DS(AttrFactory);
1676 const char *prevSpec = nullptr;
1678 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1679 typeArg, Actions.getASTContext().getPrintingPolicy());
1681 // Form a declarator to turn this into a type.
1682 Declarator D(DS, DeclaratorContext::TypeNameContext);
1683 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1684 if (fullTypeArg.isUsable()) {
1685 typeArgs.push_back(fullTypeArg.get());
1686 if (!foundValidTypeId) {
1687 foundValidTypeId = identifiers[i];
1688 foundValidTypeSrcLoc = identifierLocs[i];
1692 unknownTypeArgs.push_back(identifiers[i]);
1693 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1697 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1698 unknownTypeArgs.push_back(identifiers[i]);
1699 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1700 } else if (!foundProtocolId) {
1701 foundProtocolId = identifiers[i];
1702 foundProtocolSrcLoc = identifierLocs[i];
1707 // Continue parsing type-names.
1709 Token CurTypeTok = Tok;
1710 TypeResult typeArg = ParseTypeName();
1712 // Consume the '...' for a pack expansion.
1713 SourceLocation ellipsisLoc;
1714 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1715 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1716 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1719 if (typeArg.isUsable()) {
1720 typeArgs.push_back(typeArg.get());
1721 if (!foundValidTypeId) {
1722 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1723 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1728 } while (TryConsumeToken(tok::comma));
1730 // Diagnose the mix between type args and protocols.
1731 if (foundProtocolId && foundValidTypeId)
1732 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1734 foundValidTypeSrcLoc);
1736 // Diagnose unknown arg types.
1738 if (unknownTypeArgs.size())
1739 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1740 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1741 getCurScope(), nullptr, T);
1743 // Parse the closing '>'.
1744 SourceLocation rAngleLoc;
1745 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1746 /*ObjCGenericList=*/true);
1753 // Record left/right angle locations.
1754 typeArgsLAngleLoc = lAngleLoc;
1755 typeArgsRAngleLoc = rAngleLoc;
1758 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1759 ParsedType baseType,
1760 SourceLocation &typeArgsLAngleLoc,
1761 SmallVectorImpl<ParsedType> &typeArgs,
1762 SourceLocation &typeArgsRAngleLoc,
1763 SourceLocation &protocolLAngleLoc,
1764 SmallVectorImpl<Decl *> &protocols,
1765 SmallVectorImpl<SourceLocation> &protocolLocs,
1766 SourceLocation &protocolRAngleLoc,
1767 bool consumeLastToken) {
1768 assert(Tok.is(tok::less));
1770 // Parse the first angle-bracket-delimited clause.
1771 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1780 /*warnOnIncompleteProtocols=*/false);
1781 if (Tok.is(tok::eof)) // Nothing else to do here...
1784 // An Objective-C object pointer followed by type arguments
1785 // can then be followed again by a set of protocol references, e.g.,
1786 // \c NSArray<NSView><NSTextDelegate>
1787 if ((consumeLastToken && Tok.is(tok::less)) ||
1788 (!consumeLastToken && NextToken().is(tok::less))) {
1789 // If we aren't consuming the last token, the prior '>' is still hanging
1790 // there. Consume it before we parse the protocol qualifiers.
1791 if (!consumeLastToken)
1794 if (!protocols.empty()) {
1795 SkipUntilFlags skipFlags = SkipUntilFlags();
1796 if (!consumeLastToken)
1797 skipFlags = skipFlags | StopBeforeMatch;
1798 Diag(Tok, diag::err_objc_type_args_after_protocols)
1799 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1800 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1802 ParseObjCProtocolReferences(protocols, protocolLocs,
1803 /*WarnOnDeclarations=*/false,
1804 /*ForObjCContainer=*/false,
1805 protocolLAngleLoc, protocolRAngleLoc,
1811 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1814 bool consumeLastToken,
1815 SourceLocation &endLoc) {
1816 assert(Tok.is(tok::less));
1817 SourceLocation typeArgsLAngleLoc;
1818 SmallVector<ParsedType, 4> typeArgs;
1819 SourceLocation typeArgsRAngleLoc;
1820 SourceLocation protocolLAngleLoc;
1821 SmallVector<Decl *, 4> protocols;
1822 SmallVector<SourceLocation, 4> protocolLocs;
1823 SourceLocation protocolRAngleLoc;
1825 // Parse type arguments and protocol qualifiers.
1826 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1827 typeArgsRAngleLoc, protocolLAngleLoc,
1828 protocols, protocolLocs,
1829 protocolRAngleLoc, consumeLastToken);
1831 if (Tok.is(tok::eof))
1832 return true; // Invalid type result.
1834 // Compute the location of the last token.
1835 if (consumeLastToken)
1836 endLoc = PrevTokLocation;
1838 endLoc = Tok.getLocation();
1840 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1853 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1854 BalancedDelimiterTracker &T,
1855 SmallVectorImpl<Decl *> &AllIvarDecls,
1856 bool RBraceMissing) {
1860 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1861 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1862 Actions.ActOnObjCContainerFinishDefinition();
1863 // Call ActOnFields() even if we don't have any decls. This is useful
1864 // for code rewriting tools that need to be aware of the empty list.
1865 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, AllIvarDecls,
1866 T.getOpenLocation(), T.getCloseLocation(),
1867 ParsedAttributesView());
1870 /// objc-class-instance-variables:
1871 /// '{' objc-instance-variable-decl-list[opt] '}'
1873 /// objc-instance-variable-decl-list:
1874 /// objc-visibility-spec
1875 /// objc-instance-variable-decl ';'
1877 /// objc-instance-variable-decl-list objc-visibility-spec
1878 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1879 /// objc-instance-variable-decl-list ';'
1881 /// objc-visibility-spec:
1885 /// @package [OBJC2]
1887 /// objc-instance-variable-decl:
1888 /// struct-declaration
1890 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1891 tok::ObjCKeywordKind visibility,
1892 SourceLocation atLoc) {
1893 assert(Tok.is(tok::l_brace) && "expected {");
1894 SmallVector<Decl *, 32> AllIvarDecls;
1896 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1897 ObjCDeclContextSwitch ObjCDC(*this);
1899 BalancedDelimiterTracker T(*this, tok::l_brace);
1901 // While we still have something to read, read the instance variables.
1902 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1903 // Each iteration of this loop reads one objc-instance-variable-decl.
1905 // Check for extraneous top-level semicolon.
1906 if (Tok.is(tok::semi)) {
1907 ConsumeExtraSemi(InstanceVariableList);
1911 // Set the default visibility to private.
1912 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1913 if (Tok.is(tok::code_completion)) {
1914 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1915 return cutOffParsing();
1918 switch (Tok.getObjCKeywordID()) {
1919 case tok::objc_private:
1920 case tok::objc_public:
1921 case tok::objc_protected:
1922 case tok::objc_package:
1923 visibility = Tok.getObjCKeywordID();
1928 Diag(Tok, diag::err_objc_unexpected_atend);
1929 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1930 Tok.setKind(tok::at);
1933 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1934 T, AllIvarDecls, true);
1938 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1943 if (Tok.is(tok::code_completion)) {
1944 Actions.CodeCompleteOrdinaryName(getCurScope(),
1945 Sema::PCC_ObjCInstanceVariableList);
1946 return cutOffParsing();
1949 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1950 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1951 // Install the declarator into the interface decl.
1952 FD.D.setObjCIvar(true);
1953 Decl *Field = Actions.ActOnIvar(
1954 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1955 FD.BitfieldSize, visibility);
1956 Actions.ActOnObjCContainerFinishDefinition();
1958 AllIvarDecls.push_back(Field);
1962 // Parse all the comma separated declarators.
1963 ParsingDeclSpec DS(*this);
1964 ParseStructDeclaration(DS, ObjCIvarCallback);
1966 if (Tok.is(tok::semi)) {
1969 Diag(Tok, diag::err_expected_semi_decl_list);
1970 // Skip to end of block or statement
1971 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1974 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1975 T, AllIvarDecls, false);
1978 /// objc-protocol-declaration:
1979 /// objc-protocol-definition
1980 /// objc-protocol-forward-reference
1982 /// objc-protocol-definition:
1983 /// \@protocol identifier
1984 /// objc-protocol-refs[opt]
1985 /// objc-interface-decl-list
1988 /// objc-protocol-forward-reference:
1989 /// \@protocol identifier-list ';'
1991 /// "\@protocol identifier ;" should be resolved as "\@protocol
1992 /// identifier-list ;": objc-interface-decl-list may not start with a
1993 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1994 Parser::DeclGroupPtrTy
1995 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1996 ParsedAttributes &attrs) {
1997 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1998 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1999 ConsumeToken(); // the "protocol" identifier
2001 if (Tok.is(tok::code_completion)) {
2002 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2007 MaybeSkipAttributes(tok::objc_protocol);
2009 if (expectIdentifier())
2010 return nullptr; // missing protocol name.
2011 // Save the protocol name, then consume it.
2012 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2013 SourceLocation nameLoc = ConsumeToken();
2015 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2016 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2017 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo, attrs);
2020 CheckNestedObjCContexts(AtLoc);
2022 if (Tok.is(tok::comma)) { // list of forward declarations.
2023 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2024 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2026 // Parse the list of forward declarations.
2028 ConsumeToken(); // the ','
2029 if (expectIdentifier()) {
2030 SkipUntil(tok::semi);
2033 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2034 Tok.getLocation()));
2035 ConsumeToken(); // the identifier
2037 if (Tok.isNot(tok::comma))
2041 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2044 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs, attrs);
2047 // Last, and definitely not least, parse a protocol declaration.
2048 SourceLocation LAngleLoc, EndProtoLoc;
2050 SmallVector<Decl *, 8> ProtocolRefs;
2051 SmallVector<SourceLocation, 8> ProtocolLocs;
2052 if (Tok.is(tok::less) &&
2053 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2054 LAngleLoc, EndProtoLoc,
2055 /*consumeLastToken=*/true))
2058 Decl *ProtoType = Actions.ActOnStartProtocolInterface(
2059 AtLoc, protocolName, nameLoc, ProtocolRefs.data(), ProtocolRefs.size(),
2060 ProtocolLocs.data(), EndProtoLoc, attrs);
2062 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2063 return Actions.ConvertDeclToDeclGroup(ProtoType);
2066 /// objc-implementation:
2067 /// objc-class-implementation-prologue
2068 /// objc-category-implementation-prologue
2070 /// objc-class-implementation-prologue:
2071 /// @implementation identifier objc-superclass[opt]
2072 /// objc-class-instance-variables[opt]
2074 /// objc-category-implementation-prologue:
2075 /// @implementation identifier ( identifier )
2076 Parser::DeclGroupPtrTy
2077 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
2078 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2079 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2080 CheckNestedObjCContexts(AtLoc);
2081 ConsumeToken(); // the "implementation" identifier
2083 // Code completion after '@implementation'.
2084 if (Tok.is(tok::code_completion)) {
2085 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2090 MaybeSkipAttributes(tok::objc_implementation);
2092 if (expectIdentifier())
2093 return nullptr; // missing class or category name.
2094 // We have a class or category name - consume it.
2095 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2096 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2097 Decl *ObjCImpDecl = nullptr;
2099 // Neither a type parameter list nor a list of protocol references is
2100 // permitted here. Parse and diagnose them.
2101 if (Tok.is(tok::less)) {
2102 SourceLocation lAngleLoc, rAngleLoc;
2103 SmallVector<IdentifierLocPair, 8> protocolIdents;
2104 SourceLocation diagLoc = Tok.getLocation();
2105 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2106 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2107 protocolIdents, rAngleLoc)) {
2108 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2109 << SourceRange(diagLoc, PrevTokLocation);
2110 } else if (lAngleLoc.isValid()) {
2111 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2112 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2116 if (Tok.is(tok::l_paren)) {
2117 // we have a category implementation.
2119 SourceLocation categoryLoc, rparenLoc;
2120 IdentifierInfo *categoryId = nullptr;
2122 if (Tok.is(tok::code_completion)) {
2123 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2128 if (Tok.is(tok::identifier)) {
2129 categoryId = Tok.getIdentifierInfo();
2130 categoryLoc = ConsumeToken();
2132 Diag(Tok, diag::err_expected)
2133 << tok::identifier; // missing category name.
2136 if (Tok.isNot(tok::r_paren)) {
2137 Diag(Tok, diag::err_expected) << tok::r_paren;
2138 SkipUntil(tok::r_paren); // don't stop at ';'
2141 rparenLoc = ConsumeParen();
2142 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2143 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2144 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2145 SmallVector<Decl *, 4> protocols;
2146 SmallVector<SourceLocation, 4> protocolLocs;
2147 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2148 /*warnOnIncompleteProtocols=*/false,
2149 /*ForObjCContainer=*/false,
2150 protocolLAngleLoc, protocolRAngleLoc,
2151 /*consumeLastToken=*/true);
2153 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2154 AtLoc, nameId, nameLoc, categoryId,
2158 // We have a class implementation
2159 SourceLocation superClassLoc;
2160 IdentifierInfo *superClassId = nullptr;
2161 if (TryConsumeToken(tok::colon)) {
2162 // We have a super class
2163 if (expectIdentifier())
2164 return nullptr; // missing super class name.
2165 superClassId = Tok.getIdentifierInfo();
2166 superClassLoc = ConsumeToken(); // Consume super class name
2168 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2169 AtLoc, nameId, nameLoc,
2170 superClassId, superClassLoc);
2172 if (Tok.is(tok::l_brace)) // we have ivars
2173 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2174 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2175 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2177 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2178 SmallVector<Decl *, 4> protocols;
2179 SmallVector<SourceLocation, 4> protocolLocs;
2180 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2181 /*warnOnIncompleteProtocols=*/false,
2182 /*ForObjCContainer=*/false,
2183 protocolLAngleLoc, protocolRAngleLoc,
2184 /*consumeLastToken=*/true);
2187 assert(ObjCImpDecl);
2189 SmallVector<Decl *, 8> DeclsInGroup;
2192 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2193 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2194 ParsedAttributesWithRange attrs(AttrFactory);
2195 MaybeParseCXX11Attributes(attrs);
2196 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2197 DeclGroupRef DG = DGP.get();
2198 DeclsInGroup.append(DG.begin(), DG.end());
2203 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2206 Parser::DeclGroupPtrTy
2207 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2208 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2209 "ParseObjCAtEndDeclaration(): Expected @end");
2210 ConsumeToken(); // the "end" identifier
2211 if (CurParsedObjCImpl)
2212 CurParsedObjCImpl->finish(atEnd);
2214 // missing @implementation
2215 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2219 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2221 finish(P.Tok.getLocation());
2222 if (P.isEofOrEom()) {
2223 P.Diag(P.Tok, diag::err_objc_missing_end)
2224 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2225 P.Diag(Dcl->getBeginLoc(), diag::note_objc_container_start)
2226 << Sema::OCK_Implementation;
2229 P.CurParsedObjCImpl = nullptr;
2230 assert(LateParsedObjCMethods.empty());
2233 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2235 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2236 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2237 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2240 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2243 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2244 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2245 false/*c-functions*/);
2247 /// Clear and free the cached objc methods.
2248 for (LateParsedObjCMethodContainer::iterator
2249 I = LateParsedObjCMethods.begin(),
2250 E = LateParsedObjCMethods.end(); I != E; ++I)
2252 LateParsedObjCMethods.clear();
2257 /// compatibility-alias-decl:
2258 /// @compatibility_alias alias-name class-name ';'
2260 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2261 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2262 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2263 ConsumeToken(); // consume compatibility_alias
2264 if (expectIdentifier())
2266 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2267 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2268 if (expectIdentifier())
2270 IdentifierInfo *classId = Tok.getIdentifierInfo();
2271 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2272 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2273 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2277 /// property-synthesis:
2278 /// @synthesize property-ivar-list ';'
2280 /// property-ivar-list:
2282 /// property-ivar-list ',' property-ivar
2286 /// identifier '=' identifier
2288 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2289 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2290 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2291 ConsumeToken(); // consume synthesize
2294 if (Tok.is(tok::code_completion)) {
2295 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2300 if (Tok.isNot(tok::identifier)) {
2301 Diag(Tok, diag::err_synthesized_property_name);
2302 SkipUntil(tok::semi);
2306 IdentifierInfo *propertyIvar = nullptr;
2307 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2308 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2309 SourceLocation propertyIvarLoc;
2310 if (TryConsumeToken(tok::equal)) {
2311 // property '=' ivar-name
2312 if (Tok.is(tok::code_completion)) {
2313 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2318 if (expectIdentifier())
2320 propertyIvar = Tok.getIdentifierInfo();
2321 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2323 Actions.ActOnPropertyImplDecl(
2324 getCurScope(), atLoc, propertyLoc, true,
2325 propertyId, propertyIvar, propertyIvarLoc,
2326 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2327 if (Tok.isNot(tok::comma))
2329 ConsumeToken(); // consume ','
2331 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2335 /// property-dynamic:
2336 /// @dynamic property-list
2340 /// property-list ',' identifier
2342 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2343 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2344 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2345 ConsumeToken(); // consume dynamic
2347 bool isClassProperty = false;
2348 if (Tok.is(tok::l_paren)) {
2350 const IdentifierInfo *II = Tok.getIdentifierInfo();
2353 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2354 SkipUntil(tok::r_paren, StopAtSemi);
2356 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2357 if (II->isStr("class")) {
2358 isClassProperty = true;
2359 if (Tok.isNot(tok::r_paren)) {
2360 Diag(Tok, diag::err_expected) << tok::r_paren;
2361 SkipUntil(tok::r_paren, StopAtSemi);
2365 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2366 SkipUntil(tok::r_paren, StopAtSemi);
2372 if (Tok.is(tok::code_completion)) {
2373 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2378 if (expectIdentifier()) {
2379 SkipUntil(tok::semi);
2383 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2384 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2385 Actions.ActOnPropertyImplDecl(
2386 getCurScope(), atLoc, propertyLoc, false,
2387 propertyId, nullptr, SourceLocation(),
2388 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2389 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2391 if (Tok.isNot(tok::comma))
2393 ConsumeToken(); // consume ','
2395 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2399 /// objc-throw-statement:
2400 /// throw expression[opt];
2402 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2404 ConsumeToken(); // consume throw
2405 if (Tok.isNot(tok::semi)) {
2406 Res = ParseExpression();
2407 if (Res.isInvalid()) {
2408 SkipUntil(tok::semi);
2413 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2414 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2417 /// objc-synchronized-statement:
2418 /// @synchronized '(' expression ')' compound-statement
2421 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2422 ConsumeToken(); // consume synchronized
2423 if (Tok.isNot(tok::l_paren)) {
2424 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2428 // The operand is surrounded with parentheses.
2429 ConsumeParen(); // '('
2430 ExprResult operand(ParseExpression());
2432 if (Tok.is(tok::r_paren)) {
2433 ConsumeParen(); // ')'
2435 if (!operand.isInvalid())
2436 Diag(Tok, diag::err_expected) << tok::r_paren;
2438 // Skip forward until we see a left brace, but don't consume it.
2439 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2442 // Require a compound statement.
2443 if (Tok.isNot(tok::l_brace)) {
2444 if (!operand.isInvalid())
2445 Diag(Tok, diag::err_expected) << tok::l_brace;
2449 // Check the @synchronized operand now.
2450 if (!operand.isInvalid())
2451 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2453 // Parse the compound statement within a new scope.
2454 ParseScope bodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2455 StmtResult body(ParseCompoundStatementBody());
2458 // If there was a semantic or parse error earlier with the
2459 // operand, fail now.
2460 if (operand.isInvalid())
2463 if (body.isInvalid())
2464 body = Actions.ActOnNullStmt(Tok.getLocation());
2466 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2469 /// objc-try-catch-statement:
2470 /// @try compound-statement objc-catch-list[opt]
2471 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2473 /// objc-catch-list:
2474 /// @catch ( parameter-declaration ) compound-statement
2475 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2476 /// catch-parameter-declaration:
2477 /// parameter-declaration
2480 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2481 bool catch_or_finally_seen = false;
2483 ConsumeToken(); // consume try
2484 if (Tok.isNot(tok::l_brace)) {
2485 Diag(Tok, diag::err_expected) << tok::l_brace;
2488 StmtVector CatchStmts;
2489 StmtResult FinallyStmt;
2490 ParseScope TryScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2491 StmtResult TryBody(ParseCompoundStatementBody());
2493 if (TryBody.isInvalid())
2494 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2496 while (Tok.is(tok::at)) {
2497 // At this point, we need to lookahead to determine if this @ is the start
2498 // of an @catch or @finally. We don't want to consume the @ token if this
2499 // is an @try or @encode or something else.
2500 Token AfterAt = GetLookAheadToken(1);
2501 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2502 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2505 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2506 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2507 Decl *FirstPart = nullptr;
2508 ConsumeToken(); // consume catch
2509 if (Tok.is(tok::l_paren)) {
2511 ParseScope CatchScope(this, Scope::DeclScope |
2512 Scope::CompoundStmtScope |
2513 Scope::AtCatchScope);
2514 if (Tok.isNot(tok::ellipsis)) {
2515 DeclSpec DS(AttrFactory);
2516 ParseDeclarationSpecifiers(DS);
2517 Declarator ParmDecl(DS, DeclaratorContext::ObjCCatchContext);
2518 ParseDeclarator(ParmDecl);
2520 // Inform the actions module about the declarator, so it
2521 // gets added to the current scope.
2522 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2524 ConsumeToken(); // consume '...'
2526 SourceLocation RParenLoc;
2528 if (Tok.is(tok::r_paren))
2529 RParenLoc = ConsumeParen();
2530 else // Skip over garbage, until we get to ')'. Eat the ')'.
2531 SkipUntil(tok::r_paren, StopAtSemi);
2533 StmtResult CatchBody(true);
2534 if (Tok.is(tok::l_brace))
2535 CatchBody = ParseCompoundStatementBody();
2537 Diag(Tok, diag::err_expected) << tok::l_brace;
2538 if (CatchBody.isInvalid())
2539 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2541 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2545 if (!Catch.isInvalid())
2546 CatchStmts.push_back(Catch.get());
2549 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2553 catch_or_finally_seen = true;
2555 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2556 ConsumeToken(); // consume finally
2557 ParseScope FinallyScope(this,
2558 Scope::DeclScope | Scope::CompoundStmtScope);
2560 bool ShouldCapture =
2561 getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2563 Actions.ActOnCapturedRegionStart(Tok.getLocation(), getCurScope(),
2564 CR_ObjCAtFinally, 1);
2566 StmtResult FinallyBody(true);
2567 if (Tok.is(tok::l_brace))
2568 FinallyBody = ParseCompoundStatementBody();
2570 Diag(Tok, diag::err_expected) << tok::l_brace;
2572 if (FinallyBody.isInvalid()) {
2573 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2575 Actions.ActOnCapturedRegionError();
2576 } else if (ShouldCapture) {
2577 FinallyBody = Actions.ActOnCapturedRegionEnd(FinallyBody.get());
2580 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2582 catch_or_finally_seen = true;
2586 if (!catch_or_finally_seen) {
2587 Diag(atLoc, diag::err_missing_catch_finally);
2591 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2596 /// objc-autoreleasepool-statement:
2597 /// @autoreleasepool compound-statement
2600 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2601 ConsumeToken(); // consume autoreleasepool
2602 if (Tok.isNot(tok::l_brace)) {
2603 Diag(Tok, diag::err_expected) << tok::l_brace;
2606 // Enter a scope to hold everything within the compound stmt. Compound
2607 // statements can always hold declarations.
2608 ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2610 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2613 if (AutoreleasePoolBody.isInvalid())
2614 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2615 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2616 AutoreleasePoolBody.get());
2619 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2620 /// for later parsing.
2621 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2622 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2623 trySkippingFunctionBody()) {
2624 Actions.ActOnSkippedFunctionBody(MDecl);
2628 LexedMethod* LM = new LexedMethod(this, MDecl);
2629 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2630 CachedTokens &Toks = LM->Toks;
2631 // Begin by storing the '{' or 'try' or ':' token.
2632 Toks.push_back(Tok);
2633 if (Tok.is(tok::kw_try)) {
2635 if (Tok.is(tok::colon)) {
2636 Toks.push_back(Tok);
2638 while (Tok.isNot(tok::l_brace)) {
2639 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2640 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2643 Toks.push_back(Tok); // also store '{'
2645 else if (Tok.is(tok::colon)) {
2647 // FIXME: This is wrong, due to C++11 braced initialization.
2648 while (Tok.isNot(tok::l_brace)) {
2649 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2650 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2652 Toks.push_back(Tok); // also store '{'
2655 // Consume everything up to (and including) the matching right brace.
2656 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2657 while (Tok.is(tok::kw_catch)) {
2658 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2659 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2663 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2665 Decl *Parser::ParseObjCMethodDefinition() {
2666 Decl *MDecl = ParseObjCMethodPrototype();
2668 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, MDecl, Tok.getLocation(),
2669 "parsing Objective-C method");
2671 // parse optional ';'
2672 if (Tok.is(tok::semi)) {
2673 if (CurParsedObjCImpl) {
2674 Diag(Tok, diag::warn_semicolon_before_method_body)
2675 << FixItHint::CreateRemoval(Tok.getLocation());
2680 // We should have an opening brace now.
2681 if (Tok.isNot(tok::l_brace)) {
2682 Diag(Tok, diag::err_expected_method_body);
2684 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2685 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2687 // If we didn't find the '{', bail out.
2688 if (Tok.isNot(tok::l_brace))
2694 SkipUntil(tok::r_brace);
2698 // Allow the rest of sema to find private method decl implementations.
2699 Actions.AddAnyMethodToGlobalPool(MDecl);
2700 assert (CurParsedObjCImpl
2701 && "ParseObjCMethodDefinition - Method out of @implementation");
2702 // Consume the tokens and store them for later parsing.
2703 StashAwayMethodOrFunctionBodyTokens(MDecl);
2707 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2708 if (Tok.is(tok::code_completion)) {
2709 Actions.CodeCompleteObjCAtStatement(getCurScope());
2714 if (Tok.isObjCAtKeyword(tok::objc_try))
2715 return ParseObjCTryStmt(AtLoc);
2717 if (Tok.isObjCAtKeyword(tok::objc_throw))
2718 return ParseObjCThrowStmt(AtLoc);
2720 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2721 return ParseObjCSynchronizedStmt(AtLoc);
2723 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2724 return ParseObjCAutoreleasePoolStmt(AtLoc);
2726 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2727 getLangOpts().DebuggerSupport) {
2728 SkipUntil(tok::semi);
2729 return Actions.ActOnNullStmt(Tok.getLocation());
2732 ExprStatementTokLoc = AtLoc;
2733 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2734 if (Res.isInvalid()) {
2735 // If the expression is invalid, skip ahead to the next semicolon. Not
2736 // doing this opens us up to the possibility of infinite loops if
2737 // ParseExpression does not consume any tokens.
2738 SkipUntil(tok::semi);
2742 // Otherwise, eat the semicolon.
2743 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2744 return Actions.ActOnExprStmt(Res, isExprValueDiscarded());
2747 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2748 switch (Tok.getKind()) {
2749 case tok::code_completion:
2750 Actions.CodeCompleteObjCAtExpression(getCurScope());
2756 tok::TokenKind Kind = Tok.getKind();
2757 SourceLocation OpLoc = ConsumeToken();
2759 if (!Tok.is(tok::numeric_constant)) {
2760 const char *Symbol = nullptr;
2762 case tok::minus: Symbol = "-"; break;
2763 case tok::plus: Symbol = "+"; break;
2764 default: llvm_unreachable("missing unary operator case");
2766 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2771 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2772 if (Lit.isInvalid()) {
2775 ConsumeToken(); // Consume the literal token.
2777 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2778 if (Lit.isInvalid())
2781 return ParsePostfixExpressionSuffix(
2782 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2785 case tok::string_literal: // primary-expression: string-literal
2786 case tok::wide_string_literal:
2787 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2789 case tok::char_constant:
2790 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2792 case tok::numeric_constant:
2793 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2795 case tok::kw_true: // Objective-C++, etc.
2796 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2797 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2798 case tok::kw_false: // Objective-C++, etc.
2799 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2800 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2803 // Objective-C array literal
2804 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2807 // Objective-C dictionary literal
2808 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2811 // Objective-C boxed expression
2812 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2815 if (Tok.getIdentifierInfo() == nullptr)
2816 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2818 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2819 case tok::objc_encode:
2820 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2821 case tok::objc_protocol:
2822 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2823 case tok::objc_selector:
2824 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2825 case tok::objc_available:
2826 return ParseAvailabilityCheckExpr(AtLoc);
2828 const char *str = nullptr;
2829 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2830 // that this is a proper statement where such directives could actually
2832 if (GetLookAheadToken(1).is(tok::l_brace) &&
2833 ExprStatementTokLoc == AtLoc) {
2834 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2837 : (ch == 'f' ? "finally"
2838 : (ch == 'a' ? "autoreleasepool" : nullptr));
2841 SourceLocation kwLoc = Tok.getLocation();
2842 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2843 FixItHint::CreateReplacement(kwLoc, str));
2846 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2852 /// Parse the receiver of an Objective-C++ message send.
2854 /// This routine parses the receiver of a message send in
2855 /// Objective-C++ either as a type or as an expression. Note that this
2856 /// routine must not be called to parse a send to 'super', since it
2857 /// has no way to return such a result.
2859 /// \param IsExpr Whether the receiver was parsed as an expression.
2861 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2862 /// IsExpr is true), the parsed expression. If the receiver was parsed
2863 /// as a type (\c IsExpr is false), the parsed type.
2865 /// \returns True if an error occurred during parsing or semantic
2866 /// analysis, in which case the arguments do not have valid
2867 /// values. Otherwise, returns false for a successful parse.
2869 /// objc-receiver: [C++]
2870 /// 'super' [not parsed here]
2872 /// simple-type-specifier
2873 /// typename-specifier
2874 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2875 InMessageExpressionRAIIObject InMessage(*this, true);
2877 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2878 tok::annot_cxxscope))
2879 TryAnnotateTypeOrScopeToken();
2881 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2884 // Make sure any typos in the receiver are corrected or diagnosed, so that
2885 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2886 // only the things that are valid ObjC receivers?
2887 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2888 if (Receiver.isInvalid())
2892 TypeOrExpr = Receiver.get();
2897 // typename-specifier
2898 // simple-type-specifier
2899 // expression (that starts with one of the above)
2900 DeclSpec DS(AttrFactory);
2901 ParseCXXSimpleTypeSpecifier(DS);
2903 if (Tok.is(tok::l_paren)) {
2904 // If we see an opening parentheses at this point, we are
2905 // actually parsing an expression that starts with a
2906 // function-style cast, e.g.,
2908 // postfix-expression:
2909 // simple-type-specifier ( expression-list [opt] )
2910 // typename-specifier ( expression-list [opt] )
2912 // Parse the remainder of this case, then the (optional)
2913 // postfix-expression suffix, followed by the (optional)
2914 // right-hand side of the binary expression. We have an
2916 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2917 if (!Receiver.isInvalid())
2918 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2919 if (!Receiver.isInvalid())
2920 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2921 if (Receiver.isInvalid())
2925 TypeOrExpr = Receiver.get();
2929 // We have a class message. Turn the simple-type-specifier or
2930 // typename-specifier we parsed into a type and parse the
2931 // remainder of the class message.
2932 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2933 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2934 if (Type.isInvalid())
2938 TypeOrExpr = Type.get().getAsOpaquePtr();
2942 /// Determine whether the parser is currently referring to a an
2943 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2945 /// This routine will only return true for a subset of valid message-send
2947 bool Parser::isSimpleObjCMessageExpression() {
2948 assert(Tok.is(tok::l_square) && getLangOpts().ObjC &&
2949 "Incorrect start for isSimpleObjCMessageExpression");
2950 return GetLookAheadToken(1).is(tok::identifier) &&
2951 GetLookAheadToken(2).is(tok::identifier);
2954 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2955 if (!getLangOpts().ObjC || !NextToken().is(tok::identifier) ||
2956 InMessageExpression)
2961 if (Tok.is(tok::annot_typename))
2962 Type = getTypeAnnotation(Tok);
2963 else if (Tok.is(tok::identifier))
2964 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2969 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2970 const Token &AfterNext = GetLookAheadToken(2);
2971 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2972 if (Tok.is(tok::identifier))
2973 TryAnnotateTypeOrScopeToken();
2975 return Tok.is(tok::annot_typename);
2982 /// objc-message-expr:
2983 /// '[' objc-receiver objc-message-args ']'
2985 /// objc-receiver: [C]
2991 ExprResult Parser::ParseObjCMessageExpression() {
2992 assert(Tok.is(tok::l_square) && "'[' expected");
2993 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2995 if (Tok.is(tok::code_completion)) {
2996 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3001 InMessageExpressionRAIIObject InMessage(*this, true);
3003 if (getLangOpts().CPlusPlus) {
3004 // We completely separate the C and C++ cases because C++ requires
3005 // more complicated (read: slower) parsing.
3007 // Handle send to super.
3008 // FIXME: This doesn't benefit from the same typo-correction we
3009 // get in Objective-C.
3010 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3011 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3012 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3015 // Parse the receiver, which is either a type or an expression.
3017 void *TypeOrExpr = nullptr;
3018 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3019 SkipUntil(tok::r_square, StopAtSemi);
3024 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3025 static_cast<Expr *>(TypeOrExpr));
3027 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3028 ParsedType::getFromOpaquePtr(TypeOrExpr),
3032 if (Tok.is(tok::identifier)) {
3033 IdentifierInfo *Name = Tok.getIdentifierInfo();
3034 SourceLocation NameLoc = Tok.getLocation();
3035 ParsedType ReceiverType;
3036 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3037 Name == Ident_super,
3038 NextToken().is(tok::period),
3040 case Sema::ObjCSuperMessage:
3041 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3044 case Sema::ObjCClassMessage:
3045 if (!ReceiverType) {
3046 SkipUntil(tok::r_square, StopAtSemi);
3050 ConsumeToken(); // the type name
3052 // Parse type arguments and protocol qualifiers.
3053 if (Tok.is(tok::less)) {
3054 SourceLocation NewEndLoc;
3055 TypeResult NewReceiverType
3056 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3057 /*consumeLastToken=*/true,
3059 if (!NewReceiverType.isUsable()) {
3060 SkipUntil(tok::r_square, StopAtSemi);
3064 ReceiverType = NewReceiverType.get();
3067 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3068 ReceiverType, nullptr);
3070 case Sema::ObjCInstanceMessage:
3071 // Fall through to parse an expression.
3076 // Otherwise, an arbitrary expression can be the receiver of a send.
3077 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3078 if (Res.isInvalid()) {
3079 SkipUntil(tok::r_square, StopAtSemi);
3083 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3087 /// Parse the remainder of an Objective-C message following the
3088 /// '[' objc-receiver.
3090 /// This routine handles sends to super, class messages (sent to a
3091 /// class name), and instance messages (sent to an object), and the
3092 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3093 /// ReceiverExpr, respectively. Only one of these parameters may have
3096 /// \param LBracLoc The location of the opening '['.
3098 /// \param SuperLoc If this is a send to 'super', the location of the
3099 /// 'super' keyword that indicates a send to the superclass.
3101 /// \param ReceiverType If this is a class message, the type of the
3102 /// class we are sending a message to.
3104 /// \param ReceiverExpr If this is an instance message, the expression
3105 /// used to compute the receiver object.
3107 /// objc-message-args:
3109 /// objc-keywordarg-list
3111 /// objc-keywordarg-list:
3113 /// objc-keywordarg-list objc-keywordarg
3115 /// objc-keywordarg:
3116 /// selector-name[opt] ':' objc-keywordexpr
3118 /// objc-keywordexpr:
3119 /// nonempty-expr-list
3121 /// nonempty-expr-list:
3122 /// assignment-expression
3123 /// nonempty-expr-list , assignment-expression
3126 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3127 SourceLocation SuperLoc,
3128 ParsedType ReceiverType,
3129 Expr *ReceiverExpr) {
3130 InMessageExpressionRAIIObject InMessage(*this, true);
3132 if (Tok.is(tok::code_completion)) {
3133 if (SuperLoc.isValid())
3134 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3136 else if (ReceiverType)
3137 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3140 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3146 // Parse objc-selector
3148 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3150 SmallVector<IdentifierInfo *, 12> KeyIdents;
3151 SmallVector<SourceLocation, 12> KeyLocs;
3152 ExprVector KeyExprs;
3154 if (Tok.is(tok::colon)) {
3156 // Each iteration parses a single keyword argument.
3157 KeyIdents.push_back(selIdent);
3158 KeyLocs.push_back(Loc);
3160 if (ExpectAndConsume(tok::colon)) {
3161 // We must manually skip to a ']', otherwise the expression skipper will
3162 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3163 // the enclosing expression.
3164 SkipUntil(tok::r_square, StopAtSemi);
3168 /// Parse the expression after ':'
3170 if (Tok.is(tok::code_completion)) {
3171 if (SuperLoc.isValid())
3172 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3174 /*AtArgumentEpression=*/true);
3175 else if (ReceiverType)
3176 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3178 /*AtArgumentEpression=*/true);
3180 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3182 /*AtArgumentEpression=*/true);
3189 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3190 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3191 Expr = ParseBraceInitializer();
3193 Expr = ParseAssignmentExpression();
3195 ExprResult Res(Expr);
3196 if (Res.isInvalid()) {
3197 // We must manually skip to a ']', otherwise the expression skipper will
3198 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3199 // the enclosing expression.
3200 SkipUntil(tok::r_square, StopAtSemi);
3204 // We have a valid expression.
3205 KeyExprs.push_back(Res.get());
3207 // Code completion after each argument.
3208 if (Tok.is(tok::code_completion)) {
3209 if (SuperLoc.isValid())
3210 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3212 /*AtArgumentEpression=*/false);
3213 else if (ReceiverType)
3214 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3216 /*AtArgumentEpression=*/false);
3218 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3220 /*AtArgumentEpression=*/false);
3225 // Check for another keyword selector.
3226 selIdent = ParseObjCSelectorPiece(Loc);
3227 if (!selIdent && Tok.isNot(tok::colon))
3229 // We have a selector or a colon, continue parsing.
3231 // Parse the, optional, argument list, comma separated.
3232 while (Tok.is(tok::comma)) {
3233 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3234 /// Parse the expression after ','
3235 ExprResult Res(ParseAssignmentExpression());
3236 if (Tok.is(tok::colon))
3237 Res = Actions.CorrectDelayedTyposInExpr(Res);
3238 if (Res.isInvalid()) {
3239 if (Tok.is(tok::colon)) {
3240 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3241 FixItHint::CreateRemoval(commaLoc);
3243 // We must manually skip to a ']', otherwise the expression skipper will
3244 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3245 // the enclosing expression.
3246 SkipUntil(tok::r_square, StopAtSemi);
3250 // We have a valid expression.
3251 KeyExprs.push_back(Res.get());
3253 } else if (!selIdent) {
3254 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3256 // We must manually skip to a ']', otherwise the expression skipper will
3257 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3258 // the enclosing expression.
3259 SkipUntil(tok::r_square, StopAtSemi);
3263 if (Tok.isNot(tok::r_square)) {
3264 Diag(Tok, diag::err_expected)
3265 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3266 // We must manually skip to a ']', otherwise the expression skipper will
3267 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3268 // the enclosing expression.
3269 SkipUntil(tok::r_square, StopAtSemi);
3273 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3275 unsigned nKeys = KeyIdents.size();
3277 KeyIdents.push_back(selIdent);
3278 KeyLocs.push_back(Loc);
3280 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3282 if (SuperLoc.isValid())
3283 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3284 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3285 else if (ReceiverType)
3286 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3287 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3288 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3289 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3292 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3293 ExprResult Res(ParseStringLiteralExpression());
3294 if (Res.isInvalid()) return Res;
3296 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3297 // expressions. At this point, we know that the only valid thing that starts
3298 // with '@' is an @"".
3299 SmallVector<SourceLocation, 4> AtLocs;
3300 ExprVector AtStrings;
3301 AtLocs.push_back(AtLoc);
3302 AtStrings.push_back(Res.get());
3304 while (Tok.is(tok::at)) {
3305 AtLocs.push_back(ConsumeToken()); // eat the @.
3307 // Invalid unless there is a string literal.
3308 if (!isTokenStringLiteral())
3309 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3311 ExprResult Lit(ParseStringLiteralExpression());
3312 if (Lit.isInvalid())
3315 AtStrings.push_back(Lit.get());
3318 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3321 /// ParseObjCBooleanLiteral -
3322 /// objc-scalar-literal : '@' boolean-keyword
3324 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3326 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3328 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3329 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3332 /// ParseObjCCharacterLiteral -
3333 /// objc-scalar-literal : '@' character-literal
3335 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3336 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3337 if (Lit.isInvalid()) {
3340 ConsumeToken(); // Consume the literal token.
3341 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3344 /// ParseObjCNumericLiteral -
3345 /// objc-scalar-literal : '@' scalar-literal
3347 /// scalar-literal : | numeric-constant /* any numeric constant. */
3349 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3350 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3351 if (Lit.isInvalid()) {
3354 ConsumeToken(); // Consume the literal token.
3355 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3358 /// ParseObjCBoxedExpr -
3359 /// objc-box-expression:
3360 /// @( assignment-expression )
3362 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3363 if (Tok.isNot(tok::l_paren))
3364 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3366 BalancedDelimiterTracker T(*this, tok::l_paren);
3368 ExprResult ValueExpr(ParseAssignmentExpression());
3369 if (T.consumeClose())
3372 if (ValueExpr.isInvalid())
3375 // Wrap the sub-expression in a parenthesized expression, to distinguish
3376 // a boxed expression from a literal.
3377 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3378 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3379 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3383 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3384 ExprVector ElementExprs; // array elements.
3385 ConsumeBracket(); // consume the l_square.
3387 bool HasInvalidEltExpr = false;
3388 while (Tok.isNot(tok::r_square)) {
3389 // Parse list of array element expressions (all must be id types).
3390 ExprResult Res(ParseAssignmentExpression());
3391 if (Res.isInvalid()) {
3392 // We must manually skip to a ']', otherwise the expression skipper will
3393 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3394 // the enclosing expression.
3395 SkipUntil(tok::r_square, StopAtSemi);
3399 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3400 if (Res.isInvalid())
3401 HasInvalidEltExpr = true;
3403 // Parse the ellipsis that indicates a pack expansion.
3404 if (Tok.is(tok::ellipsis))
3405 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3406 if (Res.isInvalid())
3407 HasInvalidEltExpr = true;
3409 ElementExprs.push_back(Res.get());
3411 if (Tok.is(tok::comma))
3412 ConsumeToken(); // Eat the ','.
3413 else if (Tok.isNot(tok::r_square))
3414 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3417 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3419 if (HasInvalidEltExpr)
3422 MultiExprArg Args(ElementExprs);
3423 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3426 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3427 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3428 ConsumeBrace(); // consume the l_square.
3429 bool HasInvalidEltExpr = false;
3430 while (Tok.isNot(tok::r_brace)) {
3431 // Parse the comma separated key : value expressions.
3434 ColonProtectionRAIIObject X(*this);
3435 KeyExpr = ParseAssignmentExpression();
3436 if (KeyExpr.isInvalid()) {
3437 // We must manually skip to a '}', otherwise the expression skipper will
3438 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3439 // the enclosing expression.
3440 SkipUntil(tok::r_brace, StopAtSemi);
3445 if (ExpectAndConsume(tok::colon)) {
3446 SkipUntil(tok::r_brace, StopAtSemi);
3450 ExprResult ValueExpr(ParseAssignmentExpression());
3451 if (ValueExpr.isInvalid()) {
3452 // We must manually skip to a '}', otherwise the expression skipper will
3453 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3454 // the enclosing expression.
3455 SkipUntil(tok::r_brace, StopAtSemi);
3459 // Check the key and value for possible typos
3460 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3461 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3462 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3463 HasInvalidEltExpr = true;
3465 // Parse the ellipsis that designates this as a pack expansion. Do not
3466 // ActOnPackExpansion here, leave it to template instantiation time where
3467 // we can get better diagnostics.
3468 SourceLocation EllipsisLoc;
3469 if (getLangOpts().CPlusPlus)
3470 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3472 // We have a valid expression. Collect it in a vector so we can
3473 // build the argument list.
3474 ObjCDictionaryElement Element = {
3475 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3477 Elements.push_back(Element);
3479 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3480 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3483 SourceLocation EndLoc = ConsumeBrace();
3485 if (HasInvalidEltExpr)
3488 // Create the ObjCDictionaryLiteral.
3489 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3493 /// objc-encode-expression:
3494 /// \@encode ( type-name )
3496 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3497 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3499 SourceLocation EncLoc = ConsumeToken();
3501 if (Tok.isNot(tok::l_paren))
3502 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3504 BalancedDelimiterTracker T(*this, tok::l_paren);
3507 TypeResult Ty = ParseTypeName();
3514 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3515 Ty.get(), T.getCloseLocation());
3518 /// objc-protocol-expression
3519 /// \@protocol ( protocol-name )
3521 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3522 SourceLocation ProtoLoc = ConsumeToken();
3524 if (Tok.isNot(tok::l_paren))
3525 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3527 BalancedDelimiterTracker T(*this, tok::l_paren);
3530 if (expectIdentifier())
3533 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3534 SourceLocation ProtoIdLoc = ConsumeToken();
3538 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3539 T.getOpenLocation(), ProtoIdLoc,
3540 T.getCloseLocation());
3543 /// objc-selector-expression
3544 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3545 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3546 SourceLocation SelectorLoc = ConsumeToken();
3548 if (Tok.isNot(tok::l_paren))
3549 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3551 SmallVector<IdentifierInfo *, 12> KeyIdents;
3552 SourceLocation sLoc;
3554 BalancedDelimiterTracker T(*this, tok::l_paren);
3556 bool HasOptionalParen = Tok.is(tok::l_paren);
3557 if (HasOptionalParen)
3560 if (Tok.is(tok::code_completion)) {
3561 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3566 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3567 if (!SelIdent && // missing selector name.
3568 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3569 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3571 KeyIdents.push_back(SelIdent);
3573 unsigned nColons = 0;
3574 if (Tok.isNot(tok::r_paren)) {
3576 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3578 KeyIdents.push_back(nullptr);
3579 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3583 if (Tok.is(tok::r_paren))
3586 if (Tok.is(tok::code_completion)) {
3587 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3592 // Check for another keyword selector.
3594 SelIdent = ParseObjCSelectorPiece(Loc);
3595 KeyIdents.push_back(SelIdent);
3596 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3600 if (HasOptionalParen && Tok.is(tok::r_paren))
3601 ConsumeParen(); // ')'
3603 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3604 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3605 T.getOpenLocation(),
3606 T.getCloseLocation(),
3610 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3611 // MCDecl might be null due to error in method or c-function prototype, etc.
3612 Decl *MCDecl = LM.D;
3613 bool skip = MCDecl &&
3614 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3615 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3619 // Save the current token position.
3620 SourceLocation OrigLoc = Tok.getLocation();
3622 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3623 // Store an artificial EOF token to ensure that we don't run off the end of
3624 // the method's body when we come to parse it.
3627 Eof.setKind(tok::eof);
3628 Eof.setEofData(MCDecl);
3629 Eof.setLocation(OrigLoc);
3630 LM.Toks.push_back(Eof);
3631 // Append the current token at the end of the new token stream so that it
3632 // doesn't get lost.
3633 LM.Toks.push_back(Tok);
3634 PP.EnterTokenStream(LM.Toks, true);
3636 // Consume the previously pushed token.
3637 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3639 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3640 "Inline objective-c method not starting with '{' or 'try' or ':'");
3641 // Enter a scope for the method or c-function body.
3642 ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
3643 Scope::FnScope | Scope::DeclScope |
3644 Scope::CompoundStmtScope);
3646 // Tell the actions module that we have entered a method or c-function definition
3647 // with the specified Declarator for the method/function.
3649 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3651 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3652 if (Tok.is(tok::kw_try))
3653 ParseFunctionTryBlock(MCDecl, BodyScope);
3655 if (Tok.is(tok::colon))
3656 ParseConstructorInitializer(MCDecl);
3658 Actions.ActOnDefaultCtorInitializers(MCDecl);
3659 ParseFunctionStatementBody(MCDecl, BodyScope);
3662 if (Tok.getLocation() != OrigLoc) {
3663 // Due to parsing error, we either went over the cached tokens or
3664 // there are still cached tokens left. If it's the latter case skip the
3666 // Since this is an uncommon situation that should be avoided, use the
3667 // expensive isBeforeInTranslationUnit call.
3668 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3670 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3673 // Clean up the remaining EOF token.