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 "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/PrettyDeclStackTrace.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 Parser::ParseObjCAtDirectives() {
49 SourceLocation AtLoc = ConsumeToken(); // the "@"
51 if (Tok.is(tok::code_completion)) {
52 Actions.CodeCompleteObjCAtDirective(getCurScope());
57 Decl *SingleDecl = nullptr;
58 switch (Tok.getObjCKeywordID()) {
60 return ParseObjCAtClassDeclaration(AtLoc);
61 case tok::objc_interface: {
62 ParsedAttributes attrs(AttrFactory);
63 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
66 case tok::objc_protocol: {
67 ParsedAttributes attrs(AttrFactory);
68 return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
70 case tok::objc_implementation:
71 return ParseObjCAtImplementationDeclaration(AtLoc);
73 return ParseObjCAtEndDeclaration(AtLoc);
74 case tok::objc_compatibility_alias:
75 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
77 case tok::objc_synthesize:
78 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
80 case tok::objc_dynamic:
81 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
83 case tok::objc_import:
84 if (getLangOpts().Modules || getLangOpts().DebuggerSupport)
85 return ParseModuleImport(AtLoc);
86 Diag(AtLoc, diag::err_atimport);
88 return Actions.ConvertDeclToDeclGroup(nullptr);
90 Diag(AtLoc, diag::err_unexpected_at);
95 return Actions.ConvertDeclToDeclGroup(SingleDecl);
98 /// Class to handle popping type parameters when leaving the scope.
99 class Parser::ObjCTypeParamListScope {
102 ObjCTypeParamList *Params;
105 ObjCTypeParamListScope(Sema &Actions, Scope *S)
106 : Actions(Actions), S(S), Params(nullptr) {}
108 ~ObjCTypeParamListScope() {
112 void enter(ObjCTypeParamList *P) {
119 Actions.popObjCTypeParamList(S, Params);
125 /// objc-class-declaration:
126 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
128 /// objc-class-forward-decl:
129 /// identifier objc-type-parameter-list[opt]
131 Parser::DeclGroupPtrTy
132 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
133 ConsumeToken(); // the identifier "class"
134 SmallVector<IdentifierInfo *, 8> ClassNames;
135 SmallVector<SourceLocation, 8> ClassLocs;
136 SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
139 MaybeSkipAttributes(tok::objc_class);
140 if (Tok.isNot(tok::identifier)) {
141 Diag(Tok, diag::err_expected) << tok::identifier;
142 SkipUntil(tok::semi);
143 return Actions.ConvertDeclToDeclGroup(nullptr);
145 ClassNames.push_back(Tok.getIdentifierInfo());
146 ClassLocs.push_back(Tok.getLocation());
149 // Parse the optional objc-type-parameter-list.
150 ObjCTypeParamList *TypeParams = nullptr;
151 if (Tok.is(tok::less))
152 TypeParams = parseObjCTypeParamList();
153 ClassTypeParams.push_back(TypeParams);
154 if (!TryConsumeToken(tok::comma))
159 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
160 return Actions.ConvertDeclToDeclGroup(nullptr);
162 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
168 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
170 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
171 if (ock == Sema::OCK_None)
174 Decl *Decl = Actions.getObjCDeclContext();
175 if (CurParsedObjCImpl) {
176 CurParsedObjCImpl->finish(AtLoc);
178 Actions.ActOnAtEnd(getCurScope(), AtLoc);
180 Diag(AtLoc, diag::err_objc_missing_end)
181 << FixItHint::CreateInsertion(AtLoc, "@end\n");
183 Diag(Decl->getLocStart(), diag::note_objc_container_start)
189 /// objc-class-interface-attributes[opt] objc-class-interface
190 /// objc-category-interface
192 /// objc-class-interface:
193 /// '@' 'interface' identifier objc-type-parameter-list[opt]
194 /// objc-superclass[opt] objc-protocol-refs[opt]
195 /// objc-class-instance-variables[opt]
196 /// objc-interface-decl-list
199 /// objc-category-interface:
200 /// '@' 'interface' identifier objc-type-parameter-list[opt]
201 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
202 /// objc-interface-decl-list
206 /// ':' identifier objc-type-arguments[opt]
208 /// objc-class-interface-attributes:
209 /// __attribute__((visibility("default")))
210 /// __attribute__((visibility("hidden")))
211 /// __attribute__((deprecated))
212 /// __attribute__((unavailable))
213 /// __attribute__((objc_exception)) - used by NSException on 64-bit
214 /// __attribute__((objc_root_class))
216 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
217 ParsedAttributes &attrs) {
218 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
219 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
220 CheckNestedObjCContexts(AtLoc);
221 ConsumeToken(); // the "interface" identifier
223 // Code completion after '@interface'.
224 if (Tok.is(tok::code_completion)) {
225 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
230 MaybeSkipAttributes(tok::objc_interface);
232 if (Tok.isNot(tok::identifier)) {
233 Diag(Tok, diag::err_expected)
234 << tok::identifier; // missing class or category name.
238 // We have a class or category name - consume it.
239 IdentifierInfo *nameId = Tok.getIdentifierInfo();
240 SourceLocation nameLoc = ConsumeToken();
242 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
243 // case, LAngleLoc will be valid and ProtocolIdents will capture the
244 // protocol references (that have not yet been resolved).
245 SourceLocation LAngleLoc, EndProtoLoc;
246 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
247 ObjCTypeParamList *typeParameterList = nullptr;
248 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
249 if (Tok.is(tok::less))
250 typeParameterList = parseObjCTypeParamListOrProtocolRefs(
251 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
253 if (Tok.is(tok::l_paren) &&
254 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
256 BalancedDelimiterTracker T(*this, tok::l_paren);
259 SourceLocation categoryLoc;
260 IdentifierInfo *categoryId = nullptr;
261 if (Tok.is(tok::code_completion)) {
262 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
267 // For ObjC2, the category name is optional (not an error).
268 if (Tok.is(tok::identifier)) {
269 categoryId = Tok.getIdentifierInfo();
270 categoryLoc = ConsumeToken();
272 else if (!getLangOpts().ObjC2) {
273 Diag(Tok, diag::err_expected)
274 << tok::identifier; // missing category name.
279 if (T.getCloseLocation().isInvalid())
282 if (!attrs.empty()) { // categories don't support attributes.
283 Diag(nameLoc, diag::err_objc_no_attributes_on_category);
287 // Next, we need to check for any protocol references.
288 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
289 SmallVector<Decl *, 8> ProtocolRefs;
290 SmallVector<SourceLocation, 8> ProtocolLocs;
291 if (Tok.is(tok::less) &&
292 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
293 LAngleLoc, EndProtoLoc,
294 /*consumeLastToken=*/true))
298 Actions.ActOnStartCategoryInterface(AtLoc,
301 categoryId, categoryLoc,
307 if (Tok.is(tok::l_brace))
308 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
310 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
314 // Parse a class interface.
315 IdentifierInfo *superClassId = nullptr;
316 SourceLocation superClassLoc;
317 SourceLocation typeArgsLAngleLoc;
318 SmallVector<ParsedType, 4> typeArgs;
319 SourceLocation typeArgsRAngleLoc;
320 SmallVector<Decl *, 4> protocols;
321 SmallVector<SourceLocation, 4> protocolLocs;
322 if (Tok.is(tok::colon)) { // a super class is specified.
325 // Code completion of superclass names.
326 if (Tok.is(tok::code_completion)) {
327 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
332 if (Tok.isNot(tok::identifier)) {
333 Diag(Tok, diag::err_expected)
334 << tok::identifier; // missing super class name.
337 superClassId = Tok.getIdentifierInfo();
338 superClassLoc = ConsumeToken();
340 // Type arguments for the superclass or protocol conformances.
341 if (Tok.is(tok::less)) {
342 parseObjCTypeArgsOrProtocolQualifiers(
343 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
344 protocols, protocolLocs, EndProtoLoc,
345 /*consumeLastToken=*/true,
346 /*warnOnIncompleteProtocols=*/true);
347 if (Tok.is(tok::eof))
352 // Next, we need to check for any protocol references.
353 if (LAngleLoc.isValid()) {
354 if (!ProtocolIdents.empty()) {
355 // We already parsed the protocols named when we thought we had a
356 // type parameter list. Translate them into actual protocol references.
357 for (const auto &pair : ProtocolIdents) {
358 protocolLocs.push_back(pair.second);
360 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
361 /*ForObjCContainer=*/true,
362 ProtocolIdents, protocols);
364 } else if (protocols.empty() && Tok.is(tok::less) &&
365 ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
366 LAngleLoc, EndProtoLoc,
367 /*consumeLastToken=*/true)) {
371 if (Tok.isNot(tok::less))
372 Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
373 superClassId, superClassLoc);
376 Actions.ActOnStartClassInterface(getCurScope(), AtLoc, nameId, nameLoc,
377 typeParameterList, superClassId,
380 SourceRange(typeArgsLAngleLoc,
382 protocols.data(), protocols.size(),
384 EndProtoLoc, attrs.getList());
386 if (Tok.is(tok::l_brace))
387 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
389 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
394 /// Add an attribute for a context-sensitive type nullability to the given
396 static void addContextSensitiveTypeNullability(Parser &P,
398 NullabilityKind nullability,
399 SourceLocation nullabilityLoc,
400 bool &addedToDeclSpec) {
401 // Create the attribute.
402 auto getNullabilityAttr = [&]() -> AttributeList * {
403 return D.getAttributePool().create(
404 P.getNullabilityKeyword(nullability),
405 SourceRange(nullabilityLoc),
406 nullptr, SourceLocation(),
408 AttributeList::AS_ContextSensitiveKeyword);
411 if (D.getNumTypeObjects() > 0) {
412 // Add the attribute to the declarator chunk nearest the declarator.
413 auto nullabilityAttr = getNullabilityAttr();
414 DeclaratorChunk &chunk = D.getTypeObject(0);
415 nullabilityAttr->setNext(chunk.getAttrListRef());
416 chunk.getAttrListRef() = nullabilityAttr;
417 } else if (!addedToDeclSpec) {
418 // Otherwise, just put it on the declaration specifiers (if one
419 // isn't there already).
420 D.getMutableDeclSpec().addAttributes(getNullabilityAttr());
421 addedToDeclSpec = true;
425 /// Parse an Objective-C type parameter list, if present, or capture
426 /// the locations of the protocol identifiers for a list of protocol
429 /// objc-type-parameter-list:
430 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
432 /// objc-type-parameter:
433 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
435 /// objc-type-parameter-bound:
438 /// objc-type-parameter-variance:
440 /// '__contravariant'
442 /// \param lAngleLoc The location of the starting '<'.
444 /// \param protocolIdents Will capture the list of identifiers, if the
445 /// angle brackets contain a list of protocol references rather than a
446 /// type parameter list.
448 /// \param rAngleLoc The location of the ending '>'.
449 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
450 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
451 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
452 SourceLocation &rAngleLoc, bool mayBeProtocolList) {
453 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
455 // Within the type parameter list, don't treat '>' as an operator.
456 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
458 // Local function to "flush" the protocol identifiers, turning them into
460 SmallVector<Decl *, 4> typeParams;
461 auto makeProtocolIdentsIntoTypeParameters = [&]() {
463 for (const auto &pair : protocolIdents) {
464 DeclResult typeParam = Actions.actOnObjCTypeParam(
465 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
466 index++, pair.first, pair.second, SourceLocation(), nullptr);
467 if (typeParam.isUsable())
468 typeParams.push_back(typeParam.get());
471 protocolIdents.clear();
472 mayBeProtocolList = false;
475 bool invalid = false;
476 lAngleLoc = ConsumeToken();
479 // Parse the variance, if any.
480 SourceLocation varianceLoc;
481 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
482 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
483 variance = Tok.is(tok::kw___covariant)
484 ? ObjCTypeParamVariance::Covariant
485 : ObjCTypeParamVariance::Contravariant;
486 varianceLoc = ConsumeToken();
488 // Once we've seen a variance specific , we know this is not a
489 // list of protocol references.
490 if (mayBeProtocolList) {
491 // Up until now, we have been queuing up parameters because they
492 // might be protocol references. Turn them into parameters now.
493 makeProtocolIdentsIntoTypeParameters();
497 // Parse the identifier.
498 if (!Tok.is(tok::identifier)) {
500 if (Tok.is(tok::code_completion)) {
501 // FIXME: If these aren't protocol references, we'll need different
503 Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
506 // FIXME: Better recovery here?.
510 Diag(Tok, diag::err_objc_expected_type_parameter);
515 IdentifierInfo *paramName = Tok.getIdentifierInfo();
516 SourceLocation paramLoc = ConsumeToken();
518 // If there is a bound, parse it.
519 SourceLocation colonLoc;
520 TypeResult boundType;
521 if (TryConsumeToken(tok::colon, colonLoc)) {
522 // Once we've seen a bound, we know this is not a list of protocol
524 if (mayBeProtocolList) {
525 // Up until now, we have been queuing up parameters because they
526 // might be protocol references. Turn them into parameters now.
527 makeProtocolIdentsIntoTypeParameters();
531 boundType = ParseTypeName();
532 if (boundType.isInvalid())
534 } else if (mayBeProtocolList) {
535 // If this could still be a protocol list, just capture the identifier.
536 // We don't want to turn it into a parameter.
537 protocolIdents.push_back(std::make_pair(paramName, paramLoc));
541 // Create the type parameter.
542 DeclResult typeParam = Actions.actOnObjCTypeParam(
543 getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
544 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
545 if (typeParam.isUsable())
546 typeParams.push_back(typeParam.get());
547 } while (TryConsumeToken(tok::comma));
551 SkipUntil(tok::greater, tok::at, StopBeforeMatch);
552 if (Tok.is(tok::greater))
554 } else if (ParseGreaterThanInTemplateList(rAngleLoc,
555 /*ConsumeLastToken=*/true,
556 /*ObjCGenericList=*/true)) {
557 Diag(lAngleLoc, diag::note_matching) << "'<'";
558 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
559 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
560 tok::comma, tok::semi },
562 if (Tok.is(tok::greater))
566 if (mayBeProtocolList) {
567 // A type parameter list must be followed by either a ':' (indicating the
568 // presence of a superclass) or a '(' (indicating that this is a category
569 // or extension). This disambiguates between an objc-type-parameter-list
570 // and a objc-protocol-refs.
571 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
572 // Returning null indicates that we don't have a type parameter list.
573 // The results the caller needs to handle the protocol references are
574 // captured in the reference parameters already.
578 // We have a type parameter list that looks like a list of protocol
579 // references. Turn that parameter list into type parameters.
580 makeProtocolIdentsIntoTypeParameters();
583 // Form the type parameter list and enter its scope.
584 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
591 // Clear out the angle locations; they're used by the caller to indicate
592 // whether there are any protocol references.
593 lAngleLoc = SourceLocation();
594 rAngleLoc = SourceLocation();
595 return invalid ? nullptr : list;
598 /// Parse an objc-type-parameter-list.
599 ObjCTypeParamList *Parser::parseObjCTypeParamList() {
600 SourceLocation lAngleLoc;
601 SmallVector<IdentifierLocPair, 1> protocolIdents;
602 SourceLocation rAngleLoc;
604 ObjCTypeParamListScope Scope(Actions, getCurScope());
605 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
607 /*mayBeProtocolList=*/false);
610 /// objc-interface-decl-list:
612 /// objc-interface-decl-list objc-property-decl [OBJC2]
613 /// objc-interface-decl-list objc-method-requirement [OBJC2]
614 /// objc-interface-decl-list objc-method-proto ';'
615 /// objc-interface-decl-list declaration
616 /// objc-interface-decl-list ';'
618 /// objc-method-requirement: [OBJC2]
622 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
624 SmallVector<Decl *, 32> allMethods;
625 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
626 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
631 // If this is a method prototype, parse it.
632 if (Tok.isOneOf(tok::minus, tok::plus)) {
633 if (Decl *methodPrototype =
634 ParseObjCMethodPrototype(MethodImplKind, false))
635 allMethods.push_back(methodPrototype);
636 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
637 // method definitions.
638 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
639 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
640 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
641 if (Tok.is(tok::semi))
646 if (Tok.is(tok::l_paren)) {
647 Diag(Tok, diag::err_expected_minus_or_plus);
648 ParseObjCMethodDecl(Tok.getLocation(),
650 MethodImplKind, false);
653 // Ignore excess semicolons.
654 if (Tok.is(tok::semi)) {
659 // If we got to the end of the file, exit the loop.
663 // Code completion within an Objective-C interface.
664 if (Tok.is(tok::code_completion)) {
665 Actions.CodeCompleteOrdinaryName(getCurScope(),
666 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
667 : Sema::PCC_ObjCInterface);
668 return cutOffParsing();
671 // If we don't have an @ directive, parse it as a function definition.
672 if (Tok.isNot(tok::at)) {
673 // The code below does not consume '}'s because it is afraid of eating the
674 // end of a namespace. Because of the way this code is structured, an
675 // erroneous r_brace would cause an infinite loop if not handled here.
676 if (Tok.is(tok::r_brace))
678 ParsedAttributesWithRange attrs(AttrFactory);
679 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
683 // Otherwise, we have an @ directive, eat the @.
684 SourceLocation AtLoc = ConsumeToken(); // the "@"
685 if (Tok.is(tok::code_completion)) {
686 Actions.CodeCompleteObjCAtDirective(getCurScope());
687 return cutOffParsing();
690 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
692 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
693 AtEnd.setBegin(AtLoc);
694 AtEnd.setEnd(Tok.getLocation());
696 } else if (DirectiveKind == tok::objc_not_keyword) {
697 Diag(Tok, diag::err_objc_unknown_at);
698 SkipUntil(tok::semi);
702 // Eat the identifier.
705 switch (DirectiveKind) {
707 // FIXME: If someone forgets an @end on a protocol, this loop will
708 // continue to eat up tons of stuff and spew lots of nonsense errors. It
709 // would probably be better to bail out if we saw an @class or @interface
710 // or something like that.
711 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
712 // Skip until we see an '@' or '}' or ';'.
713 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
716 case tok::objc_implementation:
717 case tok::objc_interface:
718 Diag(AtLoc, diag::err_objc_missing_end)
719 << FixItHint::CreateInsertion(AtLoc, "@end\n");
720 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
721 << (int) Actions.getObjCContainerKind();
725 case tok::objc_required:
726 case tok::objc_optional:
727 // This is only valid on protocols.
728 // FIXME: Should this check for ObjC2 being enabled?
729 if (contextKey != tok::objc_protocol)
730 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
732 MethodImplKind = DirectiveKind;
735 case tok::objc_property:
736 if (!getLangOpts().ObjC2)
737 Diag(AtLoc, diag::err_objc_properties_require_objc2);
740 SourceLocation LParenLoc;
741 // Parse property attribute list, if any.
742 if (Tok.is(tok::l_paren)) {
743 LParenLoc = Tok.getLocation();
744 ParseObjCPropertyAttribute(OCDS);
747 bool addedToDeclSpec = false;
748 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
749 if (FD.D.getIdentifier() == nullptr) {
750 Diag(AtLoc, diag::err_objc_property_requires_field_name)
751 << FD.D.getSourceRange();
754 if (FD.BitfieldSize) {
755 Diag(AtLoc, diag::err_objc_property_bitfield)
756 << FD.D.getSourceRange();
760 // Map a nullability property attribute to a context-sensitive keyword
762 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
763 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
764 OCDS.getNullabilityLoc(),
767 // Install the property declarator into interfaceDecl.
768 IdentifierInfo *SelName =
769 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
771 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
772 IdentifierInfo *SetterName = OCDS.getSetterName();
775 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
777 SetterSel = SelectorTable::constructSetterSelector(
778 PP.getIdentifierTable(), PP.getSelectorTable(),
779 FD.D.getIdentifier());
780 Decl *Property = Actions.ActOnProperty(
781 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
784 FD.complete(Property);
787 // Parse all the comma separated declarators.
788 ParsingDeclSpec DS(*this);
789 ParseStructDeclaration(DS, ObjCPropertyCallback);
791 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
796 // We break out of the big loop in two cases: when we see @end or when we see
797 // EOF. In the former case, eat the @end. In the later case, emit an error.
798 if (Tok.is(tok::code_completion)) {
799 Actions.CodeCompleteObjCAtDirective(getCurScope());
800 return cutOffParsing();
801 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
802 ConsumeToken(); // the "end" identifier
804 Diag(Tok, diag::err_objc_missing_end)
805 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
806 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
807 << (int) Actions.getObjCContainerKind();
808 AtEnd.setBegin(Tok.getLocation());
809 AtEnd.setEnd(Tok.getLocation());
812 // Insert collected methods declarations into the @interface object.
813 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
814 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
817 /// Diagnose redundant or conflicting nullability information.
818 static void diagnoseRedundantPropertyNullability(Parser &P,
820 NullabilityKind nullability,
821 SourceLocation nullabilityLoc){
822 if (DS.getNullability() == nullability) {
823 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
824 << DiagNullabilityKind(nullability, true)
825 << SourceRange(DS.getNullabilityLoc());
829 P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
830 << DiagNullabilityKind(nullability, true)
831 << DiagNullabilityKind(DS.getNullability(), true)
832 << SourceRange(DS.getNullabilityLoc());
835 /// Parse property attribute declarations.
837 /// property-attr-decl: '(' property-attrlist ')'
838 /// property-attrlist:
839 /// property-attribute
840 /// property-attrlist ',' property-attribute
841 /// property-attribute:
842 /// getter '=' identifier
843 /// setter '=' identifier ':'
853 /// unsafe_unretained
860 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
861 assert(Tok.getKind() == tok::l_paren);
862 BalancedDelimiterTracker T(*this, tok::l_paren);
866 if (Tok.is(tok::code_completion)) {
867 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
868 return cutOffParsing();
870 const IdentifierInfo *II = Tok.getIdentifierInfo();
872 // If this is not an identifier at all, bail out early.
878 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
880 if (II->isStr("readonly"))
881 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
882 else if (II->isStr("assign"))
883 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
884 else if (II->isStr("unsafe_unretained"))
885 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
886 else if (II->isStr("readwrite"))
887 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
888 else if (II->isStr("retain"))
889 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
890 else if (II->isStr("strong"))
891 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
892 else if (II->isStr("copy"))
893 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
894 else if (II->isStr("nonatomic"))
895 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
896 else if (II->isStr("atomic"))
897 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
898 else if (II->isStr("weak"))
899 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
900 else if (II->isStr("getter") || II->isStr("setter")) {
901 bool IsSetter = II->getNameStart()[0] == 's';
903 // getter/setter require extra treatment.
904 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
905 diag::err_objc_expected_equal_for_getter;
907 if (ExpectAndConsume(tok::equal, DiagID)) {
908 SkipUntil(tok::r_paren, StopAtSemi);
912 if (Tok.is(tok::code_completion)) {
914 Actions.CodeCompleteObjCPropertySetter(getCurScope());
916 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
917 return cutOffParsing();
920 SourceLocation SelLoc;
921 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
924 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
926 SkipUntil(tok::r_paren, StopAtSemi);
931 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
932 DS.setSetterName(SelIdent);
934 if (ExpectAndConsume(tok::colon,
935 diag::err_expected_colon_after_setter_name)) {
936 SkipUntil(tok::r_paren, StopAtSemi);
940 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
941 DS.setGetterName(SelIdent);
943 } else if (II->isStr("nonnull")) {
944 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
945 diagnoseRedundantPropertyNullability(*this, DS,
946 NullabilityKind::NonNull,
948 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
949 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
950 } else if (II->isStr("nullable")) {
951 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
952 diagnoseRedundantPropertyNullability(*this, DS,
953 NullabilityKind::Nullable,
955 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
956 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
957 } else if (II->isStr("null_unspecified")) {
958 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
959 diagnoseRedundantPropertyNullability(*this, DS,
960 NullabilityKind::Unspecified,
962 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
963 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
964 } else if (II->isStr("null_resettable")) {
965 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
966 diagnoseRedundantPropertyNullability(*this, DS,
967 NullabilityKind::Unspecified,
969 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
970 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
972 // Also set the null_resettable bit.
973 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable);
974 } else if (II->isStr("class")) {
975 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class);
977 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
978 SkipUntil(tok::r_paren, StopAtSemi);
982 if (Tok.isNot(tok::comma))
991 /// objc-method-proto:
992 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
993 /// objc-class-method objc-method-decl objc-method-attributes[opt]
995 /// objc-instance-method: '-'
996 /// objc-class-method: '+'
998 /// objc-method-attributes: [OBJC2]
999 /// __attribute__((deprecated))
1001 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
1002 bool MethodDefinition) {
1003 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
1005 tok::TokenKind methodType = Tok.getKind();
1006 SourceLocation mLoc = ConsumeToken();
1007 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
1009 // Since this rule is used for both method declarations and definitions,
1010 // the caller is (optionally) responsible for consuming the ';'.
1017 /// enum struct union if else while do for switch case default
1018 /// break continue return goto asm sizeof typeof __alignof
1019 /// unsigned long const short volatile signed restrict _Complex
1020 /// in out inout bycopy byref oneway int char float double void _Bool
1022 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
1024 switch (Tok.getKind()) {
1033 case tok::exclaimequal:
1035 case tok::pipeequal:
1037 case tok::caretequal: {
1038 std::string ThisTok(PP.getSpelling(Tok));
1039 if (isLetter(ThisTok[0])) {
1040 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1041 Tok.setKind(tok::identifier);
1042 SelectorLoc = ConsumeToken();
1048 case tok::identifier:
1058 case tok::kw_const_cast:
1059 case tok::kw_continue:
1060 case tok::kw_default:
1061 case tok::kw_delete:
1063 case tok::kw_double:
1064 case tok::kw_dynamic_cast:
1067 case tok::kw_explicit:
1068 case tok::kw_export:
1069 case tok::kw_extern:
1073 case tok::kw_friend:
1076 case tok::kw_inline:
1079 case tok::kw_mutable:
1080 case tok::kw_namespace:
1082 case tok::kw_operator:
1083 case tok::kw_private:
1084 case tok::kw_protected:
1085 case tok::kw_public:
1086 case tok::kw_register:
1087 case tok::kw_reinterpret_cast:
1088 case tok::kw_restrict:
1089 case tok::kw_return:
1091 case tok::kw_signed:
1092 case tok::kw_sizeof:
1093 case tok::kw_static:
1094 case tok::kw_static_cast:
1095 case tok::kw_struct:
1096 case tok::kw_switch:
1097 case tok::kw_template:
1102 case tok::kw_typedef:
1103 case tok::kw_typeid:
1104 case tok::kw_typename:
1105 case tok::kw_typeof:
1107 case tok::kw_unsigned:
1109 case tok::kw_virtual:
1111 case tok::kw_volatile:
1112 case tok::kw_wchar_t:
1115 case tok::kw__Complex:
1116 case tok::kw___alignof:
1117 case tok::kw___auto_type:
1118 IdentifierInfo *II = Tok.getIdentifierInfo();
1119 SelectorLoc = ConsumeToken();
1124 /// objc-for-collection-in: 'in'
1126 bool Parser::isTokIdentifier_in() const {
1127 // FIXME: May have to do additional look-ahead to only allow for
1128 // valid tokens following an 'in'; such as an identifier, unary operators,
1130 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
1131 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1134 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1135 /// qualifier list and builds their bitmask representation in the input
1138 /// objc-type-qualifiers:
1139 /// objc-type-qualifier
1140 /// objc-type-qualifiers objc-type-qualifier
1142 /// objc-type-qualifier:
1151 /// 'null_unspecified'
1153 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1154 Declarator::TheContext Context) {
1155 assert(Context == Declarator::ObjCParameterContext ||
1156 Context == Declarator::ObjCResultContext);
1159 if (Tok.is(tok::code_completion)) {
1160 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
1161 Context == Declarator::ObjCParameterContext);
1162 return cutOffParsing();
1165 if (Tok.isNot(tok::identifier))
1168 const IdentifierInfo *II = Tok.getIdentifierInfo();
1169 for (unsigned i = 0; i != objc_NumQuals; ++i) {
1170 if (II != ObjCTypeQuals[i] ||
1171 NextToken().is(tok::less) ||
1172 NextToken().is(tok::coloncolon))
1175 ObjCDeclSpec::ObjCDeclQualifier Qual;
1176 NullabilityKind Nullability;
1178 default: llvm_unreachable("Unknown decl qualifier");
1179 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
1180 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
1181 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
1182 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1183 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1184 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
1187 Qual = ObjCDeclSpec::DQ_CSNullability;
1188 Nullability = NullabilityKind::NonNull;
1192 Qual = ObjCDeclSpec::DQ_CSNullability;
1193 Nullability = NullabilityKind::Nullable;
1196 case objc_null_unspecified:
1197 Qual = ObjCDeclSpec::DQ_CSNullability;
1198 Nullability = NullabilityKind::Unspecified;
1202 // FIXME: Diagnose redundant specifiers.
1203 DS.setObjCDeclQualifier(Qual);
1204 if (Qual == ObjCDeclSpec::DQ_CSNullability)
1205 DS.setNullability(Tok.getLocation(), Nullability);
1212 // If this wasn't a recognized qualifier, bail out.
1217 /// Take all the decl attributes out of the given list and add
1218 /// them to the given attribute set.
1219 static void takeDeclAttributes(ParsedAttributes &attrs,
1220 AttributeList *list) {
1222 AttributeList *cur = list;
1223 list = cur->getNext();
1225 if (!cur->isUsedAsTypeAttr()) {
1226 // Clear out the next pointer. We're really completely
1227 // destroying the internal invariants of the declarator here,
1228 // but it doesn't matter because we're done with it.
1229 cur->setNext(nullptr);
1235 /// takeDeclAttributes - Take all the decl attributes from the given
1236 /// declarator and add them to the given list.
1237 static void takeDeclAttributes(ParsedAttributes &attrs,
1239 // First, take ownership of all attributes.
1240 attrs.getPool().takeAllFrom(D.getAttributePool());
1241 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1243 // Now actually move the attributes over.
1244 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
1245 takeDeclAttributes(attrs, D.getAttributes());
1246 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1247 takeDeclAttributes(attrs,
1248 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
1252 /// '(' objc-type-qualifiers[opt] type-name ')'
1253 /// '(' objc-type-qualifiers[opt] ')'
1255 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1256 Declarator::TheContext context,
1257 ParsedAttributes *paramAttrs) {
1258 assert(context == Declarator::ObjCParameterContext ||
1259 context == Declarator::ObjCResultContext);
1260 assert((paramAttrs != nullptr) ==
1261 (context == Declarator::ObjCParameterContext));
1263 assert(Tok.is(tok::l_paren) && "expected (");
1265 BalancedDelimiterTracker T(*this, tok::l_paren);
1268 SourceLocation TypeStartLoc = Tok.getLocation();
1269 ObjCDeclContextSwitch ObjCDC(*this);
1271 // Parse type qualifiers, in, inout, etc.
1272 ParseObjCTypeQualifierList(DS, context);
1275 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1276 // Parse an abstract declarator.
1277 DeclSpec declSpec(AttrFactory);
1278 declSpec.setObjCQualifiers(&DS);
1279 DeclSpecContext dsContext = DSC_normal;
1280 if (context == Declarator::ObjCResultContext)
1281 dsContext = DSC_objc_method_result;
1282 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1283 Declarator declarator(declSpec, context);
1284 ParseDeclarator(declarator);
1286 // If that's not invalid, extract a type.
1287 if (!declarator.isInvalidType()) {
1288 // Map a nullability specifier to a context-sensitive keyword attribute.
1289 bool addedToDeclSpec = false;
1290 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1291 addContextSensitiveTypeNullability(*this, declarator,
1292 DS.getNullability(),
1293 DS.getNullabilityLoc(),
1296 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1297 if (!type.isInvalid())
1300 // If we're parsing a parameter, steal all the decl attributes
1301 // and add them to the decl spec.
1302 if (context == Declarator::ObjCParameterContext)
1303 takeDeclAttributes(*paramAttrs, declarator);
1307 if (Tok.is(tok::r_paren))
1309 else if (Tok.getLocation() == TypeStartLoc) {
1310 // If we didn't eat any tokens, then this isn't a type.
1311 Diag(Tok, diag::err_expected_type);
1312 SkipUntil(tok::r_paren, StopAtSemi);
1314 // Otherwise, we found *something*, but didn't get a ')' in the right
1315 // place. Emit an error then return what we have as the type.
1321 /// objc-method-decl:
1323 /// objc-keyword-selector objc-parmlist[opt]
1324 /// objc-type-name objc-selector
1325 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1327 /// objc-keyword-selector:
1328 /// objc-keyword-decl
1329 /// objc-keyword-selector objc-keyword-decl
1331 /// objc-keyword-decl:
1332 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1333 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1334 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1335 /// ':' objc-keyword-attributes[opt] identifier
1338 /// objc-parms objc-ellipsis[opt]
1341 /// objc-parms , parameter-declaration
1346 /// objc-keyword-attributes: [OBJC2]
1347 /// __attribute__((unused))
1349 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1350 tok::TokenKind mType,
1351 tok::ObjCKeywordKind MethodImplKind,
1352 bool MethodDefinition) {
1353 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1355 if (Tok.is(tok::code_completion)) {
1356 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1357 /*ReturnType=*/nullptr);
1362 // Parse the return type if present.
1363 ParsedType ReturnType;
1365 if (Tok.is(tok::l_paren))
1366 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext,
1369 // If attributes exist before the method, parse them.
1370 ParsedAttributes methodAttrs(AttrFactory);
1371 if (getLangOpts().ObjC2)
1372 MaybeParseGNUAttributes(methodAttrs);
1374 if (Tok.is(tok::code_completion)) {
1375 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1381 // Now parse the selector.
1382 SourceLocation selLoc;
1383 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1385 // An unnamed colon is valid.
1386 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1387 Diag(Tok, diag::err_expected_selector_for_method)
1388 << SourceRange(mLoc, Tok.getLocation());
1389 // Skip until we get a ; or @.
1390 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1394 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1395 if (Tok.isNot(tok::colon)) {
1396 // If attributes exist after the method, parse them.
1397 if (getLangOpts().ObjC2)
1398 MaybeParseGNUAttributes(methodAttrs);
1400 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1402 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1403 mType, DSRet, ReturnType,
1404 selLoc, Sel, nullptr,
1405 CParamInfo.data(), CParamInfo.size(),
1406 methodAttrs.getList(), MethodImplKind,
1407 false, MethodDefinition);
1408 PD.complete(Result);
1412 SmallVector<IdentifierInfo *, 12> KeyIdents;
1413 SmallVector<SourceLocation, 12> KeyLocs;
1414 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1415 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1416 Scope::FunctionDeclarationScope | Scope::DeclScope);
1418 AttributePool allParamAttrs(AttrFactory);
1420 ParsedAttributes paramAttrs(AttrFactory);
1421 Sema::ObjCArgInfo ArgInfo;
1423 // Each iteration parses a single keyword argument.
1424 if (ExpectAndConsume(tok::colon))
1427 ArgInfo.Type = nullptr;
1428 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1429 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1430 Declarator::ObjCParameterContext,
1433 // If attributes exist before the argument name, parse them.
1434 // Regardless, collect all the attributes we've parsed so far.
1435 ArgInfo.ArgAttrs = nullptr;
1436 if (getLangOpts().ObjC2) {
1437 MaybeParseGNUAttributes(paramAttrs);
1438 ArgInfo.ArgAttrs = paramAttrs.getList();
1441 // Code completion for the next piece of the selector.
1442 if (Tok.is(tok::code_completion)) {
1443 KeyIdents.push_back(SelIdent);
1444 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1445 mType == tok::minus,
1446 /*AtParameterName=*/true,
1447 ReturnType, KeyIdents);
1452 if (Tok.isNot(tok::identifier)) {
1453 Diag(Tok, diag::err_expected)
1454 << tok::identifier; // missing argument name.
1458 ArgInfo.Name = Tok.getIdentifierInfo();
1459 ArgInfo.NameLoc = Tok.getLocation();
1460 ConsumeToken(); // Eat the identifier.
1462 ArgInfos.push_back(ArgInfo);
1463 KeyIdents.push_back(SelIdent);
1464 KeyLocs.push_back(selLoc);
1466 // Make sure the attributes persist.
1467 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1469 // Code completion for the next piece of the selector.
1470 if (Tok.is(tok::code_completion)) {
1471 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1472 mType == tok::minus,
1473 /*AtParameterName=*/false,
1474 ReturnType, KeyIdents);
1479 // Check for another keyword selector.
1480 SelIdent = ParseObjCSelectorPiece(selLoc);
1481 if (!SelIdent && Tok.isNot(tok::colon))
1484 SourceLocation ColonLoc = Tok.getLocation();
1485 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1486 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1487 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1488 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1491 // We have a selector or a colon, continue parsing.
1494 bool isVariadic = false;
1495 bool cStyleParamWarned = false;
1496 // Parse the (optional) parameter list.
1497 while (Tok.is(tok::comma)) {
1499 if (Tok.is(tok::ellipsis)) {
1504 if (!cStyleParamWarned) {
1505 Diag(Tok, diag::warn_cstyle_param);
1506 cStyleParamWarned = true;
1508 DeclSpec DS(AttrFactory);
1509 ParseDeclarationSpecifiers(DS);
1510 // Parse the declarator.
1511 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1512 ParseDeclarator(ParmDecl);
1513 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1514 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1515 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1516 ParmDecl.getIdentifierLoc(),
1521 // FIXME: Add support for optional parameter list...
1522 // If attributes exist after the method, parse them.
1523 if (getLangOpts().ObjC2)
1524 MaybeParseGNUAttributes(methodAttrs);
1526 if (KeyIdents.size() == 0)
1529 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1532 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1533 mType, DSRet, ReturnType,
1534 KeyLocs, Sel, &ArgInfos[0],
1535 CParamInfo.data(), CParamInfo.size(),
1536 methodAttrs.getList(),
1537 MethodImplKind, isVariadic, MethodDefinition);
1539 PD.complete(Result);
1543 /// objc-protocol-refs:
1544 /// '<' identifier-list '>'
1547 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1548 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1549 bool WarnOnDeclarations, bool ForObjCContainer,
1550 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1551 bool consumeLastToken) {
1552 assert(Tok.is(tok::less) && "expected <");
1554 LAngleLoc = ConsumeToken(); // the "<"
1556 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1559 if (Tok.is(tok::code_completion)) {
1560 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1565 if (Tok.isNot(tok::identifier)) {
1566 Diag(Tok, diag::err_expected) << tok::identifier;
1567 SkipUntil(tok::greater, StopAtSemi);
1570 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1571 Tok.getLocation()));
1572 ProtocolLocs.push_back(Tok.getLocation());
1575 if (!TryConsumeToken(tok::comma))
1580 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1581 /*ObjCGenericList=*/false))
1584 // Convert the list of protocols identifiers into a list of protocol decls.
1585 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1586 ProtocolIdents, Protocols);
1590 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1591 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1592 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1594 SourceLocation lAngleLoc;
1595 SmallVector<Decl *, 8> protocols;
1596 SmallVector<SourceLocation, 8> protocolLocs;
1597 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1598 lAngleLoc, rAngleLoc,
1599 /*consumeLastToken=*/true);
1600 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1604 if (result.isUsable()) {
1605 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1606 << FixItHint::CreateInsertion(lAngleLoc, "id")
1607 << SourceRange(lAngleLoc, rAngleLoc);
1613 /// Parse Objective-C type arguments or protocol qualifiers.
1615 /// objc-type-arguments:
1616 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1618 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1619 ParsedType baseType,
1620 SourceLocation &typeArgsLAngleLoc,
1621 SmallVectorImpl<ParsedType> &typeArgs,
1622 SourceLocation &typeArgsRAngleLoc,
1623 SourceLocation &protocolLAngleLoc,
1624 SmallVectorImpl<Decl *> &protocols,
1625 SmallVectorImpl<SourceLocation> &protocolLocs,
1626 SourceLocation &protocolRAngleLoc,
1627 bool consumeLastToken,
1628 bool warnOnIncompleteProtocols) {
1629 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1630 SourceLocation lAngleLoc = ConsumeToken();
1632 // Whether all of the elements we've parsed thus far are single
1633 // identifiers, which might be types or might be protocols.
1634 bool allSingleIdentifiers = true;
1635 SmallVector<IdentifierInfo *, 4> identifiers;
1636 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1638 // Parse a list of comma-separated identifiers, bailing out if we
1639 // see something different.
1641 // Parse a single identifier.
1642 if (Tok.is(tok::identifier) &&
1643 (NextToken().is(tok::comma) ||
1644 NextToken().is(tok::greater) ||
1645 NextToken().is(tok::greatergreater))) {
1646 identifiers.push_back(Tok.getIdentifierInfo());
1647 identifierLocs.push_back(ConsumeToken());
1651 if (Tok.is(tok::code_completion)) {
1652 // FIXME: Also include types here.
1653 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1654 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1655 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1656 identifierLocs[i]));
1659 QualType BaseT = Actions.GetTypeFromParser(baseType);
1660 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1661 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1663 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1669 allSingleIdentifiers = false;
1671 } while (TryConsumeToken(tok::comma));
1673 // If we parsed an identifier list, semantic analysis sorts out
1674 // whether it refers to protocols or to type arguments.
1675 if (allSingleIdentifiers) {
1676 // Parse the closing '>'.
1677 SourceLocation rAngleLoc;
1678 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1679 /*ObjCGenericList=*/true);
1681 // Let Sema figure out what we parsed.
1682 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1694 warnOnIncompleteProtocols);
1698 // We parsed an identifier list but stumbled into non single identifiers, this
1699 // means we might (a) check that what we already parsed is a legitimate type
1700 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1701 // must all be type args.
1703 // Convert the identifiers into type arguments.
1704 bool invalid = false;
1705 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1706 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1707 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1708 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1710 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1712 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1714 DeclSpec DS(AttrFactory);
1715 const char *prevSpec = nullptr;
1717 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1718 typeArg, Actions.getASTContext().getPrintingPolicy());
1720 // Form a declarator to turn this into a type.
1721 Declarator D(DS, Declarator::TypeNameContext);
1722 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1723 if (fullTypeArg.isUsable()) {
1724 typeArgs.push_back(fullTypeArg.get());
1725 if (!foundValidTypeId) {
1726 foundValidTypeId = identifiers[i];
1727 foundValidTypeSrcLoc = identifierLocs[i];
1731 unknownTypeArgs.push_back(identifiers[i]);
1732 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1736 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1737 unknownTypeArgs.push_back(identifiers[i]);
1738 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1739 } else if (!foundProtocolId) {
1740 foundProtocolId = identifiers[i];
1741 foundProtocolSrcLoc = identifierLocs[i];
1746 // Continue parsing type-names.
1748 Token CurTypeTok = Tok;
1749 TypeResult typeArg = ParseTypeName();
1751 // Consume the '...' for a pack expansion.
1752 SourceLocation ellipsisLoc;
1753 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1754 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1755 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1758 if (typeArg.isUsable()) {
1759 typeArgs.push_back(typeArg.get());
1760 if (!foundValidTypeId) {
1761 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1762 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1767 } while (TryConsumeToken(tok::comma));
1769 // Diagnose the mix between type args and protocols.
1770 if (foundProtocolId && foundValidTypeId)
1771 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1773 foundValidTypeSrcLoc);
1775 // Diagnose unknown arg types.
1777 if (unknownTypeArgs.size())
1778 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1779 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1780 getCurScope(), nullptr, T);
1782 // Parse the closing '>'.
1783 SourceLocation rAngleLoc;
1784 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1785 /*ObjCGenericList=*/true);
1792 // Record left/right angle locations.
1793 typeArgsLAngleLoc = lAngleLoc;
1794 typeArgsRAngleLoc = rAngleLoc;
1797 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1798 ParsedType baseType,
1799 SourceLocation &typeArgsLAngleLoc,
1800 SmallVectorImpl<ParsedType> &typeArgs,
1801 SourceLocation &typeArgsRAngleLoc,
1802 SourceLocation &protocolLAngleLoc,
1803 SmallVectorImpl<Decl *> &protocols,
1804 SmallVectorImpl<SourceLocation> &protocolLocs,
1805 SourceLocation &protocolRAngleLoc,
1806 bool consumeLastToken) {
1807 assert(Tok.is(tok::less));
1809 // Parse the first angle-bracket-delimited clause.
1810 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1819 /*warnOnIncompleteProtocols=*/false);
1820 if (Tok.is(tok::eof)) // Nothing else to do here...
1823 // An Objective-C object pointer followed by type arguments
1824 // can then be followed again by a set of protocol references, e.g.,
1825 // \c NSArray<NSView><NSTextDelegate>
1826 if ((consumeLastToken && Tok.is(tok::less)) ||
1827 (!consumeLastToken && NextToken().is(tok::less))) {
1828 // If we aren't consuming the last token, the prior '>' is still hanging
1829 // there. Consume it before we parse the protocol qualifiers.
1830 if (!consumeLastToken)
1833 if (!protocols.empty()) {
1834 SkipUntilFlags skipFlags = SkipUntilFlags();
1835 if (!consumeLastToken)
1836 skipFlags = skipFlags | StopBeforeMatch;
1837 Diag(Tok, diag::err_objc_type_args_after_protocols)
1838 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1839 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1841 ParseObjCProtocolReferences(protocols, protocolLocs,
1842 /*WarnOnDeclarations=*/false,
1843 /*ForObjCContainer=*/false,
1844 protocolLAngleLoc, protocolRAngleLoc,
1850 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1853 bool consumeLastToken,
1854 SourceLocation &endLoc) {
1855 assert(Tok.is(tok::less));
1856 SourceLocation typeArgsLAngleLoc;
1857 SmallVector<ParsedType, 4> typeArgs;
1858 SourceLocation typeArgsRAngleLoc;
1859 SourceLocation protocolLAngleLoc;
1860 SmallVector<Decl *, 4> protocols;
1861 SmallVector<SourceLocation, 4> protocolLocs;
1862 SourceLocation protocolRAngleLoc;
1864 // Parse type arguments and protocol qualifiers.
1865 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1866 typeArgsRAngleLoc, protocolLAngleLoc,
1867 protocols, protocolLocs,
1868 protocolRAngleLoc, consumeLastToken);
1870 if (Tok.is(tok::eof))
1871 return true; // Invalid type result.
1873 // Compute the location of the last token.
1874 if (consumeLastToken)
1875 endLoc = PrevTokLocation;
1877 endLoc = Tok.getLocation();
1879 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1892 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1893 BalancedDelimiterTracker &T,
1894 SmallVectorImpl<Decl *> &AllIvarDecls,
1895 bool RBraceMissing) {
1899 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1900 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1901 Actions.ActOnObjCContainerFinishDefinition();
1902 // Call ActOnFields() even if we don't have any decls. This is useful
1903 // for code rewriting tools that need to be aware of the empty list.
1904 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1906 T.getOpenLocation(), T.getCloseLocation(), nullptr);
1909 /// objc-class-instance-variables:
1910 /// '{' objc-instance-variable-decl-list[opt] '}'
1912 /// objc-instance-variable-decl-list:
1913 /// objc-visibility-spec
1914 /// objc-instance-variable-decl ';'
1916 /// objc-instance-variable-decl-list objc-visibility-spec
1917 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1918 /// objc-instance-variable-decl-list ';'
1920 /// objc-visibility-spec:
1924 /// @package [OBJC2]
1926 /// objc-instance-variable-decl:
1927 /// struct-declaration
1929 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1930 tok::ObjCKeywordKind visibility,
1931 SourceLocation atLoc) {
1932 assert(Tok.is(tok::l_brace) && "expected {");
1933 SmallVector<Decl *, 32> AllIvarDecls;
1935 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1936 ObjCDeclContextSwitch ObjCDC(*this);
1938 BalancedDelimiterTracker T(*this, tok::l_brace);
1940 // While we still have something to read, read the instance variables.
1941 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1942 // Each iteration of this loop reads one objc-instance-variable-decl.
1944 // Check for extraneous top-level semicolon.
1945 if (Tok.is(tok::semi)) {
1946 ConsumeExtraSemi(InstanceVariableList);
1950 // Set the default visibility to private.
1951 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1952 if (Tok.is(tok::code_completion)) {
1953 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1954 return cutOffParsing();
1957 switch (Tok.getObjCKeywordID()) {
1958 case tok::objc_private:
1959 case tok::objc_public:
1960 case tok::objc_protected:
1961 case tok::objc_package:
1962 visibility = Tok.getObjCKeywordID();
1967 Diag(Tok, diag::err_objc_unexpected_atend);
1968 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1969 Tok.setKind(tok::at);
1972 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1973 T, AllIvarDecls, true);
1977 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1982 if (Tok.is(tok::code_completion)) {
1983 Actions.CodeCompleteOrdinaryName(getCurScope(),
1984 Sema::PCC_ObjCInstanceVariableList);
1985 return cutOffParsing();
1988 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1989 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1990 // Install the declarator into the interface decl.
1991 FD.D.setObjCIvar(true);
1992 Decl *Field = Actions.ActOnIvar(
1993 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1994 FD.BitfieldSize, visibility);
1995 Actions.ActOnObjCContainerFinishDefinition();
1997 AllIvarDecls.push_back(Field);
2001 // Parse all the comma separated declarators.
2002 ParsingDeclSpec DS(*this);
2003 ParseStructDeclaration(DS, ObjCIvarCallback);
2005 if (Tok.is(tok::semi)) {
2008 Diag(Tok, diag::err_expected_semi_decl_list);
2009 // Skip to end of block or statement
2010 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2013 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
2014 T, AllIvarDecls, false);
2017 /// objc-protocol-declaration:
2018 /// objc-protocol-definition
2019 /// objc-protocol-forward-reference
2021 /// objc-protocol-definition:
2022 /// \@protocol identifier
2023 /// objc-protocol-refs[opt]
2024 /// objc-interface-decl-list
2027 /// objc-protocol-forward-reference:
2028 /// \@protocol identifier-list ';'
2030 /// "\@protocol identifier ;" should be resolved as "\@protocol
2031 /// identifier-list ;": objc-interface-decl-list may not start with a
2032 /// semicolon in the first alternative if objc-protocol-refs are omitted.
2033 Parser::DeclGroupPtrTy
2034 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2035 ParsedAttributes &attrs) {
2036 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2037 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2038 ConsumeToken(); // the "protocol" identifier
2040 if (Tok.is(tok::code_completion)) {
2041 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2046 MaybeSkipAttributes(tok::objc_protocol);
2048 if (Tok.isNot(tok::identifier)) {
2049 Diag(Tok, diag::err_expected) << tok::identifier; // missing protocol name.
2052 // Save the protocol name, then consume it.
2053 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2054 SourceLocation nameLoc = ConsumeToken();
2056 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2057 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2058 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo,
2062 CheckNestedObjCContexts(AtLoc);
2064 if (Tok.is(tok::comma)) { // list of forward declarations.
2065 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2066 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2068 // Parse the list of forward declarations.
2070 ConsumeToken(); // the ','
2071 if (Tok.isNot(tok::identifier)) {
2072 Diag(Tok, diag::err_expected) << tok::identifier;
2073 SkipUntil(tok::semi);
2076 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2077 Tok.getLocation()));
2078 ConsumeToken(); // the identifier
2080 if (Tok.isNot(tok::comma))
2084 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2087 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs,
2091 // Last, and definitely not least, parse a protocol declaration.
2092 SourceLocation LAngleLoc, EndProtoLoc;
2094 SmallVector<Decl *, 8> ProtocolRefs;
2095 SmallVector<SourceLocation, 8> ProtocolLocs;
2096 if (Tok.is(tok::less) &&
2097 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2098 LAngleLoc, EndProtoLoc,
2099 /*consumeLastToken=*/true))
2103 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
2104 ProtocolRefs.data(),
2105 ProtocolRefs.size(),
2106 ProtocolLocs.data(),
2107 EndProtoLoc, attrs.getList());
2109 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2110 return Actions.ConvertDeclToDeclGroup(ProtoType);
2113 /// objc-implementation:
2114 /// objc-class-implementation-prologue
2115 /// objc-category-implementation-prologue
2117 /// objc-class-implementation-prologue:
2118 /// @implementation identifier objc-superclass[opt]
2119 /// objc-class-instance-variables[opt]
2121 /// objc-category-implementation-prologue:
2122 /// @implementation identifier ( identifier )
2123 Parser::DeclGroupPtrTy
2124 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
2125 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2126 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2127 CheckNestedObjCContexts(AtLoc);
2128 ConsumeToken(); // the "implementation" identifier
2130 // Code completion after '@implementation'.
2131 if (Tok.is(tok::code_completion)) {
2132 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2137 MaybeSkipAttributes(tok::objc_implementation);
2139 if (Tok.isNot(tok::identifier)) {
2140 Diag(Tok, diag::err_expected)
2141 << tok::identifier; // missing class or category name.
2144 // We have a class or category name - consume it.
2145 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2146 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2147 Decl *ObjCImpDecl = nullptr;
2149 // Neither a type parameter list nor a list of protocol references is
2150 // permitted here. Parse and diagnose them.
2151 if (Tok.is(tok::less)) {
2152 SourceLocation lAngleLoc, rAngleLoc;
2153 SmallVector<IdentifierLocPair, 8> protocolIdents;
2154 SourceLocation diagLoc = Tok.getLocation();
2155 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2156 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2157 protocolIdents, rAngleLoc)) {
2158 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2159 << SourceRange(diagLoc, PrevTokLocation);
2160 } else if (lAngleLoc.isValid()) {
2161 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2162 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2166 if (Tok.is(tok::l_paren)) {
2167 // we have a category implementation.
2169 SourceLocation categoryLoc, rparenLoc;
2170 IdentifierInfo *categoryId = nullptr;
2172 if (Tok.is(tok::code_completion)) {
2173 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2178 if (Tok.is(tok::identifier)) {
2179 categoryId = Tok.getIdentifierInfo();
2180 categoryLoc = ConsumeToken();
2182 Diag(Tok, diag::err_expected)
2183 << tok::identifier; // missing category name.
2186 if (Tok.isNot(tok::r_paren)) {
2187 Diag(Tok, diag::err_expected) << tok::r_paren;
2188 SkipUntil(tok::r_paren); // don't stop at ';'
2191 rparenLoc = ConsumeParen();
2192 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2193 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2194 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2195 SmallVector<Decl *, 4> protocols;
2196 SmallVector<SourceLocation, 4> protocolLocs;
2197 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2198 /*warnOnIncompleteProtocols=*/false,
2199 /*ForObjCContainer=*/false,
2200 protocolLAngleLoc, protocolRAngleLoc,
2201 /*consumeLastToken=*/true);
2203 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2204 AtLoc, nameId, nameLoc, categoryId,
2208 // We have a class implementation
2209 SourceLocation superClassLoc;
2210 IdentifierInfo *superClassId = nullptr;
2211 if (TryConsumeToken(tok::colon)) {
2212 // We have a super class
2213 if (Tok.isNot(tok::identifier)) {
2214 Diag(Tok, diag::err_expected)
2215 << tok::identifier; // missing super class name.
2218 superClassId = Tok.getIdentifierInfo();
2219 superClassLoc = ConsumeToken(); // Consume super class name
2221 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2222 AtLoc, nameId, nameLoc,
2223 superClassId, superClassLoc);
2225 if (Tok.is(tok::l_brace)) // we have ivars
2226 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2227 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2228 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2230 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2231 SmallVector<Decl *, 4> protocols;
2232 SmallVector<SourceLocation, 4> protocolLocs;
2233 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2234 /*warnOnIncompleteProtocols=*/false,
2235 /*ForObjCContainer=*/false,
2236 protocolLAngleLoc, protocolRAngleLoc,
2237 /*consumeLastToken=*/true);
2240 assert(ObjCImpDecl);
2242 SmallVector<Decl *, 8> DeclsInGroup;
2245 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2246 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2247 ParsedAttributesWithRange attrs(AttrFactory);
2248 MaybeParseCXX11Attributes(attrs);
2249 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2250 DeclGroupRef DG = DGP.get();
2251 DeclsInGroup.append(DG.begin(), DG.end());
2256 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2259 Parser::DeclGroupPtrTy
2260 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2261 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2262 "ParseObjCAtEndDeclaration(): Expected @end");
2263 ConsumeToken(); // the "end" identifier
2264 if (CurParsedObjCImpl)
2265 CurParsedObjCImpl->finish(atEnd);
2267 // missing @implementation
2268 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2272 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2274 finish(P.Tok.getLocation());
2275 if (P.isEofOrEom()) {
2276 P.Diag(P.Tok, diag::err_objc_missing_end)
2277 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2278 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
2279 << Sema::OCK_Implementation;
2282 P.CurParsedObjCImpl = nullptr;
2283 assert(LateParsedObjCMethods.empty());
2286 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2288 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
2289 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2290 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2293 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2296 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2297 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2298 false/*c-functions*/);
2300 /// \brief Clear and free the cached objc methods.
2301 for (LateParsedObjCMethodContainer::iterator
2302 I = LateParsedObjCMethods.begin(),
2303 E = LateParsedObjCMethods.end(); I != E; ++I)
2305 LateParsedObjCMethods.clear();
2310 /// compatibility-alias-decl:
2311 /// @compatibility_alias alias-name class-name ';'
2313 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2314 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2315 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2316 ConsumeToken(); // consume compatibility_alias
2317 if (Tok.isNot(tok::identifier)) {
2318 Diag(Tok, diag::err_expected) << tok::identifier;
2321 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2322 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2323 if (Tok.isNot(tok::identifier)) {
2324 Diag(Tok, diag::err_expected) << tok::identifier;
2327 IdentifierInfo *classId = Tok.getIdentifierInfo();
2328 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2329 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2330 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2334 /// property-synthesis:
2335 /// @synthesize property-ivar-list ';'
2337 /// property-ivar-list:
2339 /// property-ivar-list ',' property-ivar
2343 /// identifier '=' identifier
2345 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2346 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2347 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2348 ConsumeToken(); // consume synthesize
2351 if (Tok.is(tok::code_completion)) {
2352 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2357 if (Tok.isNot(tok::identifier)) {
2358 Diag(Tok, diag::err_synthesized_property_name);
2359 SkipUntil(tok::semi);
2363 IdentifierInfo *propertyIvar = nullptr;
2364 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2365 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2366 SourceLocation propertyIvarLoc;
2367 if (TryConsumeToken(tok::equal)) {
2368 // property '=' ivar-name
2369 if (Tok.is(tok::code_completion)) {
2370 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2375 if (Tok.isNot(tok::identifier)) {
2376 Diag(Tok, diag::err_expected) << tok::identifier;
2379 propertyIvar = Tok.getIdentifierInfo();
2380 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2382 Actions.ActOnPropertyImplDecl(
2383 getCurScope(), atLoc, propertyLoc, true,
2384 propertyId, propertyIvar, propertyIvarLoc,
2385 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2386 if (Tok.isNot(tok::comma))
2388 ConsumeToken(); // consume ','
2390 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2394 /// property-dynamic:
2395 /// @dynamic property-list
2399 /// property-list ',' identifier
2401 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2402 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2403 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2404 ConsumeToken(); // consume dynamic
2406 bool isClassProperty = false;
2407 if (Tok.is(tok::l_paren)) {
2409 const IdentifierInfo *II = Tok.getIdentifierInfo();
2412 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2413 SkipUntil(tok::r_paren, StopAtSemi);
2415 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2416 if (II->isStr("class")) {
2417 isClassProperty = true;
2418 if (Tok.isNot(tok::r_paren)) {
2419 Diag(Tok, diag::err_expected) << tok::r_paren;
2420 SkipUntil(tok::r_paren, StopAtSemi);
2424 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2425 SkipUntil(tok::r_paren, StopAtSemi);
2431 if (Tok.is(tok::code_completion)) {
2432 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2437 if (Tok.isNot(tok::identifier)) {
2438 Diag(Tok, diag::err_expected) << tok::identifier;
2439 SkipUntil(tok::semi);
2443 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2444 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2445 Actions.ActOnPropertyImplDecl(
2446 getCurScope(), atLoc, propertyLoc, false,
2447 propertyId, nullptr, SourceLocation(),
2448 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2449 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2451 if (Tok.isNot(tok::comma))
2453 ConsumeToken(); // consume ','
2455 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2459 /// objc-throw-statement:
2460 /// throw expression[opt];
2462 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2464 ConsumeToken(); // consume throw
2465 if (Tok.isNot(tok::semi)) {
2466 Res = ParseExpression();
2467 if (Res.isInvalid()) {
2468 SkipUntil(tok::semi);
2473 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2474 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2477 /// objc-synchronized-statement:
2478 /// @synchronized '(' expression ')' compound-statement
2481 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2482 ConsumeToken(); // consume synchronized
2483 if (Tok.isNot(tok::l_paren)) {
2484 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2488 // The operand is surrounded with parentheses.
2489 ConsumeParen(); // '('
2490 ExprResult operand(ParseExpression());
2492 if (Tok.is(tok::r_paren)) {
2493 ConsumeParen(); // ')'
2495 if (!operand.isInvalid())
2496 Diag(Tok, diag::err_expected) << tok::r_paren;
2498 // Skip forward until we see a left brace, but don't consume it.
2499 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2502 // Require a compound statement.
2503 if (Tok.isNot(tok::l_brace)) {
2504 if (!operand.isInvalid())
2505 Diag(Tok, diag::err_expected) << tok::l_brace;
2509 // Check the @synchronized operand now.
2510 if (!operand.isInvalid())
2511 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2513 // Parse the compound statement within a new scope.
2514 ParseScope bodyScope(this, Scope::DeclScope);
2515 StmtResult body(ParseCompoundStatementBody());
2518 // If there was a semantic or parse error earlier with the
2519 // operand, fail now.
2520 if (operand.isInvalid())
2523 if (body.isInvalid())
2524 body = Actions.ActOnNullStmt(Tok.getLocation());
2526 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2529 /// objc-try-catch-statement:
2530 /// @try compound-statement objc-catch-list[opt]
2531 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2533 /// objc-catch-list:
2534 /// @catch ( parameter-declaration ) compound-statement
2535 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2536 /// catch-parameter-declaration:
2537 /// parameter-declaration
2540 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2541 bool catch_or_finally_seen = false;
2543 ConsumeToken(); // consume try
2544 if (Tok.isNot(tok::l_brace)) {
2545 Diag(Tok, diag::err_expected) << tok::l_brace;
2548 StmtVector CatchStmts;
2549 StmtResult FinallyStmt;
2550 ParseScope TryScope(this, Scope::DeclScope);
2551 StmtResult TryBody(ParseCompoundStatementBody());
2553 if (TryBody.isInvalid())
2554 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2556 while (Tok.is(tok::at)) {
2557 // At this point, we need to lookahead to determine if this @ is the start
2558 // of an @catch or @finally. We don't want to consume the @ token if this
2559 // is an @try or @encode or something else.
2560 Token AfterAt = GetLookAheadToken(1);
2561 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2562 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2565 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2566 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2567 Decl *FirstPart = nullptr;
2568 ConsumeToken(); // consume catch
2569 if (Tok.is(tok::l_paren)) {
2571 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
2572 if (Tok.isNot(tok::ellipsis)) {
2573 DeclSpec DS(AttrFactory);
2574 ParseDeclarationSpecifiers(DS);
2575 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
2576 ParseDeclarator(ParmDecl);
2578 // Inform the actions module about the declarator, so it
2579 // gets added to the current scope.
2580 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2582 ConsumeToken(); // consume '...'
2584 SourceLocation RParenLoc;
2586 if (Tok.is(tok::r_paren))
2587 RParenLoc = ConsumeParen();
2588 else // Skip over garbage, until we get to ')'. Eat the ')'.
2589 SkipUntil(tok::r_paren, StopAtSemi);
2591 StmtResult CatchBody(true);
2592 if (Tok.is(tok::l_brace))
2593 CatchBody = ParseCompoundStatementBody();
2595 Diag(Tok, diag::err_expected) << tok::l_brace;
2596 if (CatchBody.isInvalid())
2597 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2599 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2603 if (!Catch.isInvalid())
2604 CatchStmts.push_back(Catch.get());
2607 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2611 catch_or_finally_seen = true;
2613 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2614 ConsumeToken(); // consume finally
2615 ParseScope FinallyScope(this, Scope::DeclScope);
2617 StmtResult FinallyBody(true);
2618 if (Tok.is(tok::l_brace))
2619 FinallyBody = ParseCompoundStatementBody();
2621 Diag(Tok, diag::err_expected) << tok::l_brace;
2622 if (FinallyBody.isInvalid())
2623 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2624 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2626 catch_or_finally_seen = true;
2630 if (!catch_or_finally_seen) {
2631 Diag(atLoc, diag::err_missing_catch_finally);
2635 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2640 /// objc-autoreleasepool-statement:
2641 /// @autoreleasepool compound-statement
2644 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2645 ConsumeToken(); // consume autoreleasepool
2646 if (Tok.isNot(tok::l_brace)) {
2647 Diag(Tok, diag::err_expected) << tok::l_brace;
2650 // Enter a scope to hold everything within the compound stmt. Compound
2651 // statements can always hold declarations.
2652 ParseScope BodyScope(this, Scope::DeclScope);
2654 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2657 if (AutoreleasePoolBody.isInvalid())
2658 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2659 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2660 AutoreleasePoolBody.get());
2663 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2664 /// for later parsing.
2665 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2666 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2667 trySkippingFunctionBody()) {
2668 Actions.ActOnSkippedFunctionBody(MDecl);
2672 LexedMethod* LM = new LexedMethod(this, MDecl);
2673 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2674 CachedTokens &Toks = LM->Toks;
2675 // Begin by storing the '{' or 'try' or ':' token.
2676 Toks.push_back(Tok);
2677 if (Tok.is(tok::kw_try)) {
2679 if (Tok.is(tok::colon)) {
2680 Toks.push_back(Tok);
2682 while (Tok.isNot(tok::l_brace)) {
2683 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2684 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2687 Toks.push_back(Tok); // also store '{'
2689 else if (Tok.is(tok::colon)) {
2691 // FIXME: This is wrong, due to C++11 braced initialization.
2692 while (Tok.isNot(tok::l_brace)) {
2693 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2694 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2696 Toks.push_back(Tok); // also store '{'
2699 // Consume everything up to (and including) the matching right brace.
2700 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2701 while (Tok.is(tok::kw_catch)) {
2702 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2703 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2707 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2709 Decl *Parser::ParseObjCMethodDefinition() {
2710 Decl *MDecl = ParseObjCMethodPrototype();
2712 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2713 "parsing Objective-C method");
2715 // parse optional ';'
2716 if (Tok.is(tok::semi)) {
2717 if (CurParsedObjCImpl) {
2718 Diag(Tok, diag::warn_semicolon_before_method_body)
2719 << FixItHint::CreateRemoval(Tok.getLocation());
2724 // We should have an opening brace now.
2725 if (Tok.isNot(tok::l_brace)) {
2726 Diag(Tok, diag::err_expected_method_body);
2728 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2729 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2731 // If we didn't find the '{', bail out.
2732 if (Tok.isNot(tok::l_brace))
2738 SkipUntil(tok::r_brace);
2742 // Allow the rest of sema to find private method decl implementations.
2743 Actions.AddAnyMethodToGlobalPool(MDecl);
2744 assert (CurParsedObjCImpl
2745 && "ParseObjCMethodDefinition - Method out of @implementation");
2746 // Consume the tokens and store them for later parsing.
2747 StashAwayMethodOrFunctionBodyTokens(MDecl);
2751 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2752 if (Tok.is(tok::code_completion)) {
2753 Actions.CodeCompleteObjCAtStatement(getCurScope());
2758 if (Tok.isObjCAtKeyword(tok::objc_try))
2759 return ParseObjCTryStmt(AtLoc);
2761 if (Tok.isObjCAtKeyword(tok::objc_throw))
2762 return ParseObjCThrowStmt(AtLoc);
2764 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2765 return ParseObjCSynchronizedStmt(AtLoc);
2767 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2768 return ParseObjCAutoreleasePoolStmt(AtLoc);
2770 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2771 getLangOpts().DebuggerSupport) {
2772 SkipUntil(tok::semi);
2773 return Actions.ActOnNullStmt(Tok.getLocation());
2776 ExprStatementTokLoc = AtLoc;
2777 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2778 if (Res.isInvalid()) {
2779 // If the expression is invalid, skip ahead to the next semicolon. Not
2780 // doing this opens us up to the possibility of infinite loops if
2781 // ParseExpression does not consume any tokens.
2782 SkipUntil(tok::semi);
2786 // Otherwise, eat the semicolon.
2787 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2788 return Actions.ActOnExprStmt(Res);
2791 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2792 switch (Tok.getKind()) {
2793 case tok::code_completion:
2794 Actions.CodeCompleteObjCAtExpression(getCurScope());
2800 tok::TokenKind Kind = Tok.getKind();
2801 SourceLocation OpLoc = ConsumeToken();
2803 if (!Tok.is(tok::numeric_constant)) {
2804 const char *Symbol = nullptr;
2806 case tok::minus: Symbol = "-"; break;
2807 case tok::plus: Symbol = "+"; break;
2808 default: llvm_unreachable("missing unary operator case");
2810 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2815 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2816 if (Lit.isInvalid()) {
2819 ConsumeToken(); // Consume the literal token.
2821 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2822 if (Lit.isInvalid())
2825 return ParsePostfixExpressionSuffix(
2826 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2829 case tok::string_literal: // primary-expression: string-literal
2830 case tok::wide_string_literal:
2831 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2833 case tok::char_constant:
2834 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2836 case tok::numeric_constant:
2837 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2839 case tok::kw_true: // Objective-C++, etc.
2840 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2841 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2842 case tok::kw_false: // Objective-C++, etc.
2843 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2844 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2847 // Objective-C array literal
2848 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2851 // Objective-C dictionary literal
2852 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2855 // Objective-C boxed expression
2856 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2859 if (Tok.getIdentifierInfo() == nullptr)
2860 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2862 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2863 case tok::objc_encode:
2864 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2865 case tok::objc_protocol:
2866 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2867 case tok::objc_selector:
2868 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2869 case tok::objc_available:
2870 return ParseAvailabilityCheckExpr(AtLoc);
2872 const char *str = nullptr;
2873 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2874 // that this is a proper statement where such directives could actually
2876 if (GetLookAheadToken(1).is(tok::l_brace) &&
2877 ExprStatementTokLoc == AtLoc) {
2878 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2881 : (ch == 'f' ? "finally"
2882 : (ch == 'a' ? "autoreleasepool" : nullptr));
2885 SourceLocation kwLoc = Tok.getLocation();
2886 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2887 FixItHint::CreateReplacement(kwLoc, str));
2890 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2896 /// \brief Parse the receiver of an Objective-C++ message send.
2898 /// This routine parses the receiver of a message send in
2899 /// Objective-C++ either as a type or as an expression. Note that this
2900 /// routine must not be called to parse a send to 'super', since it
2901 /// has no way to return such a result.
2903 /// \param IsExpr Whether the receiver was parsed as an expression.
2905 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2906 /// IsExpr is true), the parsed expression. If the receiver was parsed
2907 /// as a type (\c IsExpr is false), the parsed type.
2909 /// \returns True if an error occurred during parsing or semantic
2910 /// analysis, in which case the arguments do not have valid
2911 /// values. Otherwise, returns false for a successful parse.
2913 /// objc-receiver: [C++]
2914 /// 'super' [not parsed here]
2916 /// simple-type-specifier
2917 /// typename-specifier
2918 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2919 InMessageExpressionRAIIObject InMessage(*this, true);
2921 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2922 tok::annot_cxxscope))
2923 TryAnnotateTypeOrScopeToken();
2925 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2928 // Make sure any typos in the receiver are corrected or diagnosed, so that
2929 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2930 // only the things that are valid ObjC receivers?
2931 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2932 if (Receiver.isInvalid())
2936 TypeOrExpr = Receiver.get();
2941 // typename-specifier
2942 // simple-type-specifier
2943 // expression (that starts with one of the above)
2944 DeclSpec DS(AttrFactory);
2945 ParseCXXSimpleTypeSpecifier(DS);
2947 if (Tok.is(tok::l_paren)) {
2948 // If we see an opening parentheses at this point, we are
2949 // actually parsing an expression that starts with a
2950 // function-style cast, e.g.,
2952 // postfix-expression:
2953 // simple-type-specifier ( expression-list [opt] )
2954 // typename-specifier ( expression-list [opt] )
2956 // Parse the remainder of this case, then the (optional)
2957 // postfix-expression suffix, followed by the (optional)
2958 // right-hand side of the binary expression. We have an
2960 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2961 if (!Receiver.isInvalid())
2962 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2963 if (!Receiver.isInvalid())
2964 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2965 if (Receiver.isInvalid())
2969 TypeOrExpr = Receiver.get();
2973 // We have a class message. Turn the simple-type-specifier or
2974 // typename-specifier we parsed into a type and parse the
2975 // remainder of the class message.
2976 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2977 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2978 if (Type.isInvalid())
2982 TypeOrExpr = Type.get().getAsOpaquePtr();
2986 /// \brief Determine whether the parser is currently referring to a an
2987 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2989 /// This routine will only return true for a subset of valid message-send
2991 bool Parser::isSimpleObjCMessageExpression() {
2992 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2993 "Incorrect start for isSimpleObjCMessageExpression");
2994 return GetLookAheadToken(1).is(tok::identifier) &&
2995 GetLookAheadToken(2).is(tok::identifier);
2998 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2999 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
3000 InMessageExpression)
3005 if (Tok.is(tok::annot_typename))
3006 Type = getTypeAnnotation(Tok);
3007 else if (Tok.is(tok::identifier))
3008 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
3013 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
3014 const Token &AfterNext = GetLookAheadToken(2);
3015 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
3016 if (Tok.is(tok::identifier))
3017 TryAnnotateTypeOrScopeToken();
3019 return Tok.is(tok::annot_typename);
3026 /// objc-message-expr:
3027 /// '[' objc-receiver objc-message-args ']'
3029 /// objc-receiver: [C]
3035 ExprResult Parser::ParseObjCMessageExpression() {
3036 assert(Tok.is(tok::l_square) && "'[' expected");
3037 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3039 if (Tok.is(tok::code_completion)) {
3040 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3045 InMessageExpressionRAIIObject InMessage(*this, true);
3047 if (getLangOpts().CPlusPlus) {
3048 // We completely separate the C and C++ cases because C++ requires
3049 // more complicated (read: slower) parsing.
3051 // Handle send to super.
3052 // FIXME: This doesn't benefit from the same typo-correction we
3053 // get in Objective-C.
3054 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3055 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3056 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3059 // Parse the receiver, which is either a type or an expression.
3061 void *TypeOrExpr = nullptr;
3062 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3063 SkipUntil(tok::r_square, StopAtSemi);
3068 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3069 static_cast<Expr *>(TypeOrExpr));
3071 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3072 ParsedType::getFromOpaquePtr(TypeOrExpr),
3076 if (Tok.is(tok::identifier)) {
3077 IdentifierInfo *Name = Tok.getIdentifierInfo();
3078 SourceLocation NameLoc = Tok.getLocation();
3079 ParsedType ReceiverType;
3080 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3081 Name == Ident_super,
3082 NextToken().is(tok::period),
3084 case Sema::ObjCSuperMessage:
3085 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3088 case Sema::ObjCClassMessage:
3089 if (!ReceiverType) {
3090 SkipUntil(tok::r_square, StopAtSemi);
3094 ConsumeToken(); // the type name
3096 // Parse type arguments and protocol qualifiers.
3097 if (Tok.is(tok::less)) {
3098 SourceLocation NewEndLoc;
3099 TypeResult NewReceiverType
3100 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3101 /*consumeLastToken=*/true,
3103 if (!NewReceiverType.isUsable()) {
3104 SkipUntil(tok::r_square, StopAtSemi);
3108 ReceiverType = NewReceiverType.get();
3111 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3112 ReceiverType, nullptr);
3114 case Sema::ObjCInstanceMessage:
3115 // Fall through to parse an expression.
3120 // Otherwise, an arbitrary expression can be the receiver of a send.
3121 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3122 if (Res.isInvalid()) {
3123 SkipUntil(tok::r_square, StopAtSemi);
3127 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3131 /// \brief Parse the remainder of an Objective-C message following the
3132 /// '[' objc-receiver.
3134 /// This routine handles sends to super, class messages (sent to a
3135 /// class name), and instance messages (sent to an object), and the
3136 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3137 /// ReceiverExpr, respectively. Only one of these parameters may have
3140 /// \param LBracLoc The location of the opening '['.
3142 /// \param SuperLoc If this is a send to 'super', the location of the
3143 /// 'super' keyword that indicates a send to the superclass.
3145 /// \param ReceiverType If this is a class message, the type of the
3146 /// class we are sending a message to.
3148 /// \param ReceiverExpr If this is an instance message, the expression
3149 /// used to compute the receiver object.
3151 /// objc-message-args:
3153 /// objc-keywordarg-list
3155 /// objc-keywordarg-list:
3157 /// objc-keywordarg-list objc-keywordarg
3159 /// objc-keywordarg:
3160 /// selector-name[opt] ':' objc-keywordexpr
3162 /// objc-keywordexpr:
3163 /// nonempty-expr-list
3165 /// nonempty-expr-list:
3166 /// assignment-expression
3167 /// nonempty-expr-list , assignment-expression
3170 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3171 SourceLocation SuperLoc,
3172 ParsedType ReceiverType,
3173 Expr *ReceiverExpr) {
3174 InMessageExpressionRAIIObject InMessage(*this, true);
3176 if (Tok.is(tok::code_completion)) {
3177 if (SuperLoc.isValid())
3178 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3180 else if (ReceiverType)
3181 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3184 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3190 // Parse objc-selector
3192 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3194 SmallVector<IdentifierInfo *, 12> KeyIdents;
3195 SmallVector<SourceLocation, 12> KeyLocs;
3196 ExprVector KeyExprs;
3198 if (Tok.is(tok::colon)) {
3200 // Each iteration parses a single keyword argument.
3201 KeyIdents.push_back(selIdent);
3202 KeyLocs.push_back(Loc);
3204 if (ExpectAndConsume(tok::colon)) {
3205 // We must manually skip to a ']', otherwise the expression skipper will
3206 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3207 // the enclosing expression.
3208 SkipUntil(tok::r_square, StopAtSemi);
3212 /// Parse the expression after ':'
3214 if (Tok.is(tok::code_completion)) {
3215 if (SuperLoc.isValid())
3216 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3218 /*AtArgumentEpression=*/true);
3219 else if (ReceiverType)
3220 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3222 /*AtArgumentEpression=*/true);
3224 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3226 /*AtArgumentEpression=*/true);
3233 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3234 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3235 Expr = ParseBraceInitializer();
3237 Expr = ParseAssignmentExpression();
3239 ExprResult Res(Expr);
3240 if (Res.isInvalid()) {
3241 // We must manually skip to a ']', otherwise the expression skipper will
3242 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3243 // the enclosing expression.
3244 SkipUntil(tok::r_square, StopAtSemi);
3248 // We have a valid expression.
3249 KeyExprs.push_back(Res.get());
3251 // Code completion after each argument.
3252 if (Tok.is(tok::code_completion)) {
3253 if (SuperLoc.isValid())
3254 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3256 /*AtArgumentEpression=*/false);
3257 else if (ReceiverType)
3258 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3260 /*AtArgumentEpression=*/false);
3262 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3264 /*AtArgumentEpression=*/false);
3269 // Check for another keyword selector.
3270 selIdent = ParseObjCSelectorPiece(Loc);
3271 if (!selIdent && Tok.isNot(tok::colon))
3273 // We have a selector or a colon, continue parsing.
3275 // Parse the, optional, argument list, comma separated.
3276 while (Tok.is(tok::comma)) {
3277 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3278 /// Parse the expression after ','
3279 ExprResult Res(ParseAssignmentExpression());
3280 if (Tok.is(tok::colon))
3281 Res = Actions.CorrectDelayedTyposInExpr(Res);
3282 if (Res.isInvalid()) {
3283 if (Tok.is(tok::colon)) {
3284 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3285 FixItHint::CreateRemoval(commaLoc);
3287 // We must manually skip to a ']', otherwise the expression skipper will
3288 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3289 // the enclosing expression.
3290 SkipUntil(tok::r_square, StopAtSemi);
3294 // We have a valid expression.
3295 KeyExprs.push_back(Res.get());
3297 } else if (!selIdent) {
3298 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3300 // We must manually skip to a ']', otherwise the expression skipper will
3301 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3302 // the enclosing expression.
3303 SkipUntil(tok::r_square, StopAtSemi);
3307 if (Tok.isNot(tok::r_square)) {
3308 Diag(Tok, diag::err_expected)
3309 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3310 // We must manually skip to a ']', otherwise the expression skipper will
3311 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3312 // the enclosing expression.
3313 SkipUntil(tok::r_square, StopAtSemi);
3317 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3319 unsigned nKeys = KeyIdents.size();
3321 KeyIdents.push_back(selIdent);
3322 KeyLocs.push_back(Loc);
3324 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3326 if (SuperLoc.isValid())
3327 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3328 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3329 else if (ReceiverType)
3330 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3331 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3332 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3333 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3336 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3337 ExprResult Res(ParseStringLiteralExpression());
3338 if (Res.isInvalid()) return Res;
3340 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3341 // expressions. At this point, we know that the only valid thing that starts
3342 // with '@' is an @"".
3343 SmallVector<SourceLocation, 4> AtLocs;
3344 ExprVector AtStrings;
3345 AtLocs.push_back(AtLoc);
3346 AtStrings.push_back(Res.get());
3348 while (Tok.is(tok::at)) {
3349 AtLocs.push_back(ConsumeToken()); // eat the @.
3351 // Invalid unless there is a string literal.
3352 if (!isTokenStringLiteral())
3353 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3355 ExprResult Lit(ParseStringLiteralExpression());
3356 if (Lit.isInvalid())
3359 AtStrings.push_back(Lit.get());
3362 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3365 /// ParseObjCBooleanLiteral -
3366 /// objc-scalar-literal : '@' boolean-keyword
3368 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3370 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3372 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3373 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3376 /// ParseObjCCharacterLiteral -
3377 /// objc-scalar-literal : '@' character-literal
3379 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3380 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3381 if (Lit.isInvalid()) {
3384 ConsumeToken(); // Consume the literal token.
3385 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3388 /// ParseObjCNumericLiteral -
3389 /// objc-scalar-literal : '@' scalar-literal
3391 /// scalar-literal : | numeric-constant /* any numeric constant. */
3393 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3394 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3395 if (Lit.isInvalid()) {
3398 ConsumeToken(); // Consume the literal token.
3399 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3402 /// ParseObjCBoxedExpr -
3403 /// objc-box-expression:
3404 /// @( assignment-expression )
3406 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3407 if (Tok.isNot(tok::l_paren))
3408 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3410 BalancedDelimiterTracker T(*this, tok::l_paren);
3412 ExprResult ValueExpr(ParseAssignmentExpression());
3413 if (T.consumeClose())
3416 if (ValueExpr.isInvalid())
3419 // Wrap the sub-expression in a parenthesized expression, to distinguish
3420 // a boxed expression from a literal.
3421 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3422 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3423 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3427 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3428 ExprVector ElementExprs; // array elements.
3429 ConsumeBracket(); // consume the l_square.
3431 bool HasInvalidEltExpr = false;
3432 while (Tok.isNot(tok::r_square)) {
3433 // Parse list of array element expressions (all must be id types).
3434 ExprResult Res(ParseAssignmentExpression());
3435 if (Res.isInvalid()) {
3436 // We must manually skip to a ']', otherwise the expression skipper will
3437 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3438 // the enclosing expression.
3439 SkipUntil(tok::r_square, StopAtSemi);
3443 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3444 if (Res.isInvalid())
3445 HasInvalidEltExpr = true;
3447 // Parse the ellipsis that indicates a pack expansion.
3448 if (Tok.is(tok::ellipsis))
3449 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3450 if (Res.isInvalid())
3451 HasInvalidEltExpr = true;
3453 ElementExprs.push_back(Res.get());
3455 if (Tok.is(tok::comma))
3456 ConsumeToken(); // Eat the ','.
3457 else if (Tok.isNot(tok::r_square))
3458 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3461 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3463 if (HasInvalidEltExpr)
3466 MultiExprArg Args(ElementExprs);
3467 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3470 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3471 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3472 ConsumeBrace(); // consume the l_square.
3473 bool HasInvalidEltExpr = false;
3474 while (Tok.isNot(tok::r_brace)) {
3475 // Parse the comma separated key : value expressions.
3478 ColonProtectionRAIIObject X(*this);
3479 KeyExpr = ParseAssignmentExpression();
3480 if (KeyExpr.isInvalid()) {
3481 // We must manually skip to a '}', otherwise the expression skipper will
3482 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3483 // the enclosing expression.
3484 SkipUntil(tok::r_brace, StopAtSemi);
3489 if (ExpectAndConsume(tok::colon)) {
3490 SkipUntil(tok::r_brace, StopAtSemi);
3494 ExprResult ValueExpr(ParseAssignmentExpression());
3495 if (ValueExpr.isInvalid()) {
3496 // We must manually skip to a '}', otherwise the expression skipper will
3497 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3498 // the enclosing expression.
3499 SkipUntil(tok::r_brace, StopAtSemi);
3503 // Check the key and value for possible typos
3504 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3505 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3506 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3507 HasInvalidEltExpr = true;
3509 // Parse the ellipsis that designates this as a pack expansion. Do not
3510 // ActOnPackExpansion here, leave it to template instantiation time where
3511 // we can get better diagnostics.
3512 SourceLocation EllipsisLoc;
3513 if (getLangOpts().CPlusPlus)
3514 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3516 // We have a valid expression. Collect it in a vector so we can
3517 // build the argument list.
3518 ObjCDictionaryElement Element = {
3519 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3521 Elements.push_back(Element);
3523 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3524 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3527 SourceLocation EndLoc = ConsumeBrace();
3529 if (HasInvalidEltExpr)
3532 // Create the ObjCDictionaryLiteral.
3533 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3537 /// objc-encode-expression:
3538 /// \@encode ( type-name )
3540 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3541 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3543 SourceLocation EncLoc = ConsumeToken();
3545 if (Tok.isNot(tok::l_paren))
3546 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3548 BalancedDelimiterTracker T(*this, tok::l_paren);
3551 TypeResult Ty = ParseTypeName();
3558 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3559 Ty.get(), T.getCloseLocation());
3562 /// objc-protocol-expression
3563 /// \@protocol ( protocol-name )
3565 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3566 SourceLocation ProtoLoc = ConsumeToken();
3568 if (Tok.isNot(tok::l_paren))
3569 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3571 BalancedDelimiterTracker T(*this, tok::l_paren);
3574 if (Tok.isNot(tok::identifier))
3575 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3577 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3578 SourceLocation ProtoIdLoc = ConsumeToken();
3582 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3583 T.getOpenLocation(), ProtoIdLoc,
3584 T.getCloseLocation());
3587 /// objc-selector-expression
3588 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3589 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3590 SourceLocation SelectorLoc = ConsumeToken();
3592 if (Tok.isNot(tok::l_paren))
3593 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3595 SmallVector<IdentifierInfo *, 12> KeyIdents;
3596 SourceLocation sLoc;
3598 BalancedDelimiterTracker T(*this, tok::l_paren);
3600 bool HasOptionalParen = Tok.is(tok::l_paren);
3601 if (HasOptionalParen)
3604 if (Tok.is(tok::code_completion)) {
3605 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3610 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3611 if (!SelIdent && // missing selector name.
3612 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3613 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3615 KeyIdents.push_back(SelIdent);
3617 unsigned nColons = 0;
3618 if (Tok.isNot(tok::r_paren)) {
3620 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3622 KeyIdents.push_back(nullptr);
3623 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3627 if (Tok.is(tok::r_paren))
3630 if (Tok.is(tok::code_completion)) {
3631 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3636 // Check for another keyword selector.
3638 SelIdent = ParseObjCSelectorPiece(Loc);
3639 KeyIdents.push_back(SelIdent);
3640 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3644 if (HasOptionalParen && Tok.is(tok::r_paren))
3645 ConsumeParen(); // ')'
3647 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3648 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3649 T.getOpenLocation(),
3650 T.getCloseLocation(),
3654 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3655 // MCDecl might be null due to error in method or c-function prototype, etc.
3656 Decl *MCDecl = LM.D;
3657 bool skip = MCDecl &&
3658 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3659 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3663 // Save the current token position.
3664 SourceLocation OrigLoc = Tok.getLocation();
3666 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3667 // Append the current token at the end of the new token stream so that it
3668 // doesn't get lost.
3669 LM.Toks.push_back(Tok);
3670 PP.EnterTokenStream(LM.Toks, true);
3672 // Consume the previously pushed token.
3673 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3675 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3676 "Inline objective-c method not starting with '{' or 'try' or ':'");
3677 // Enter a scope for the method or c-function body.
3678 ParseScope BodyScope(this,
3680 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
3681 : Scope::FnScope|Scope::DeclScope);
3683 // Tell the actions module that we have entered a method or c-function definition
3684 // with the specified Declarator for the method/function.
3686 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3688 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3689 if (Tok.is(tok::kw_try))
3690 ParseFunctionTryBlock(MCDecl, BodyScope);
3692 if (Tok.is(tok::colon))
3693 ParseConstructorInitializer(MCDecl);
3695 Actions.ActOnDefaultCtorInitializers(MCDecl);
3696 ParseFunctionStatementBody(MCDecl, BodyScope);
3699 if (Tok.getLocation() != OrigLoc) {
3700 // Due to parsing error, we either went over the cached tokens or
3701 // there are still cached tokens left. If it's the latter case skip the
3703 // Since this is an uncommon situation that should be avoided, use the
3704 // expensive isBeforeInTranslationUnit call.
3705 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3707 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))