1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Objective-C portions of the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/RAIIObjectsForParser.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 (expectIdentifier()) {
141 SkipUntil(tok::semi);
142 return Actions.ConvertDeclToDeclGroup(nullptr);
144 ClassNames.push_back(Tok.getIdentifierInfo());
145 ClassLocs.push_back(Tok.getLocation());
148 // Parse the optional objc-type-parameter-list.
149 ObjCTypeParamList *TypeParams = nullptr;
150 if (Tok.is(tok::less))
151 TypeParams = parseObjCTypeParamList();
152 ClassTypeParams.push_back(TypeParams);
153 if (!TryConsumeToken(tok::comma))
158 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
159 return Actions.ConvertDeclToDeclGroup(nullptr);
161 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
167 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
169 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
170 if (ock == Sema::OCK_None)
173 Decl *Decl = Actions.getObjCDeclContext();
174 if (CurParsedObjCImpl) {
175 CurParsedObjCImpl->finish(AtLoc);
177 Actions.ActOnAtEnd(getCurScope(), AtLoc);
179 Diag(AtLoc, diag::err_objc_missing_end)
180 << FixItHint::CreateInsertion(AtLoc, "@end\n");
182 Diag(Decl->getLocStart(), diag::note_objc_container_start)
188 /// objc-class-interface-attributes[opt] objc-class-interface
189 /// objc-category-interface
191 /// objc-class-interface:
192 /// '@' 'interface' identifier objc-type-parameter-list[opt]
193 /// objc-superclass[opt] objc-protocol-refs[opt]
194 /// objc-class-instance-variables[opt]
195 /// objc-interface-decl-list
198 /// objc-category-interface:
199 /// '@' 'interface' identifier objc-type-parameter-list[opt]
200 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
201 /// objc-interface-decl-list
205 /// ':' identifier objc-type-arguments[opt]
207 /// objc-class-interface-attributes:
208 /// __attribute__((visibility("default")))
209 /// __attribute__((visibility("hidden")))
210 /// __attribute__((deprecated))
211 /// __attribute__((unavailable))
212 /// __attribute__((objc_exception)) - used by NSException on 64-bit
213 /// __attribute__((objc_root_class))
215 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
216 ParsedAttributes &attrs) {
217 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
218 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
219 CheckNestedObjCContexts(AtLoc);
220 ConsumeToken(); // the "interface" identifier
222 // Code completion after '@interface'.
223 if (Tok.is(tok::code_completion)) {
224 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
229 MaybeSkipAttributes(tok::objc_interface);
231 if (expectIdentifier())
232 return nullptr; // missing class or category name.
234 // We have a class or category name - consume it.
235 IdentifierInfo *nameId = Tok.getIdentifierInfo();
236 SourceLocation nameLoc = ConsumeToken();
238 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
239 // case, LAngleLoc will be valid and ProtocolIdents will capture the
240 // protocol references (that have not yet been resolved).
241 SourceLocation LAngleLoc, EndProtoLoc;
242 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
243 ObjCTypeParamList *typeParameterList = nullptr;
244 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
245 if (Tok.is(tok::less))
246 typeParameterList = parseObjCTypeParamListOrProtocolRefs(
247 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
249 if (Tok.is(tok::l_paren) &&
250 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
252 BalancedDelimiterTracker T(*this, tok::l_paren);
255 SourceLocation categoryLoc;
256 IdentifierInfo *categoryId = nullptr;
257 if (Tok.is(tok::code_completion)) {
258 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
263 // For ObjC2, the category name is optional (not an error).
264 if (Tok.is(tok::identifier)) {
265 categoryId = Tok.getIdentifierInfo();
266 categoryLoc = ConsumeToken();
268 else if (!getLangOpts().ObjC2) {
269 Diag(Tok, diag::err_expected)
270 << tok::identifier; // missing category name.
275 if (T.getCloseLocation().isInvalid())
278 // Next, we need to check for any protocol references.
279 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
280 SmallVector<Decl *, 8> ProtocolRefs;
281 SmallVector<SourceLocation, 8> ProtocolLocs;
282 if (Tok.is(tok::less) &&
283 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
284 LAngleLoc, EndProtoLoc,
285 /*consumeLastToken=*/true))
288 Decl *CategoryType = Actions.ActOnStartCategoryInterface(
289 AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
290 ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
291 EndProtoLoc, attrs.getList());
293 if (Tok.is(tok::l_brace))
294 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
296 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
300 // Parse a class interface.
301 IdentifierInfo *superClassId = nullptr;
302 SourceLocation superClassLoc;
303 SourceLocation typeArgsLAngleLoc;
304 SmallVector<ParsedType, 4> typeArgs;
305 SourceLocation typeArgsRAngleLoc;
306 SmallVector<Decl *, 4> protocols;
307 SmallVector<SourceLocation, 4> protocolLocs;
308 if (Tok.is(tok::colon)) { // a super class is specified.
311 // Code completion of superclass names.
312 if (Tok.is(tok::code_completion)) {
313 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
318 if (expectIdentifier())
319 return nullptr; // missing super class name.
320 superClassId = Tok.getIdentifierInfo();
321 superClassLoc = ConsumeToken();
323 // Type arguments for the superclass or protocol conformances.
324 if (Tok.is(tok::less)) {
325 parseObjCTypeArgsOrProtocolQualifiers(
326 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
327 protocols, protocolLocs, EndProtoLoc,
328 /*consumeLastToken=*/true,
329 /*warnOnIncompleteProtocols=*/true);
330 if (Tok.is(tok::eof))
335 // Next, we need to check for any protocol references.
336 if (LAngleLoc.isValid()) {
337 if (!ProtocolIdents.empty()) {
338 // We already parsed the protocols named when we thought we had a
339 // type parameter list. Translate them into actual protocol references.
340 for (const auto &pair : ProtocolIdents) {
341 protocolLocs.push_back(pair.second);
343 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
344 /*ForObjCContainer=*/true,
345 ProtocolIdents, protocols);
347 } else if (protocols.empty() && Tok.is(tok::less) &&
348 ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
349 LAngleLoc, EndProtoLoc,
350 /*consumeLastToken=*/true)) {
354 if (Tok.isNot(tok::less))
355 Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
356 superClassId, superClassLoc);
359 Actions.ActOnStartClassInterface(getCurScope(), AtLoc, nameId, nameLoc,
360 typeParameterList, superClassId,
363 SourceRange(typeArgsLAngleLoc,
365 protocols.data(), protocols.size(),
367 EndProtoLoc, attrs.getList());
369 if (Tok.is(tok::l_brace))
370 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
372 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
377 /// Add an attribute for a context-sensitive type nullability to the given
379 static void addContextSensitiveTypeNullability(Parser &P,
381 NullabilityKind nullability,
382 SourceLocation nullabilityLoc,
383 bool &addedToDeclSpec) {
384 // Create the attribute.
385 auto getNullabilityAttr = [&]() -> AttributeList * {
386 return D.getAttributePool().create(
387 P.getNullabilityKeyword(nullability),
388 SourceRange(nullabilityLoc),
389 nullptr, SourceLocation(),
391 AttributeList::AS_ContextSensitiveKeyword);
394 if (D.getNumTypeObjects() > 0) {
395 // Add the attribute to the declarator chunk nearest the declarator.
396 auto nullabilityAttr = getNullabilityAttr();
397 DeclaratorChunk &chunk = D.getTypeObject(0);
398 nullabilityAttr->setNext(chunk.getAttrListRef());
399 chunk.getAttrListRef() = nullabilityAttr;
400 } else if (!addedToDeclSpec) {
401 // Otherwise, just put it on the declaration specifiers (if one
402 // isn't there already).
403 D.getMutableDeclSpec().addAttributes(getNullabilityAttr());
404 addedToDeclSpec = true;
408 /// Parse an Objective-C type parameter list, if present, or capture
409 /// the locations of the protocol identifiers for a list of protocol
412 /// objc-type-parameter-list:
413 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
415 /// objc-type-parameter:
416 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
418 /// objc-type-parameter-bound:
421 /// objc-type-parameter-variance:
423 /// '__contravariant'
425 /// \param lAngleLoc The location of the starting '<'.
427 /// \param protocolIdents Will capture the list of identifiers, if the
428 /// angle brackets contain a list of protocol references rather than a
429 /// type parameter list.
431 /// \param rAngleLoc The location of the ending '>'.
432 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
433 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
434 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
435 SourceLocation &rAngleLoc, bool mayBeProtocolList) {
436 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
438 // Within the type parameter list, don't treat '>' as an operator.
439 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
441 // Local function to "flush" the protocol identifiers, turning them into
443 SmallVector<Decl *, 4> typeParams;
444 auto makeProtocolIdentsIntoTypeParameters = [&]() {
446 for (const auto &pair : protocolIdents) {
447 DeclResult typeParam = Actions.actOnObjCTypeParam(
448 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
449 index++, pair.first, pair.second, SourceLocation(), nullptr);
450 if (typeParam.isUsable())
451 typeParams.push_back(typeParam.get());
454 protocolIdents.clear();
455 mayBeProtocolList = false;
458 bool invalid = false;
459 lAngleLoc = ConsumeToken();
462 // Parse the variance, if any.
463 SourceLocation varianceLoc;
464 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
465 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
466 variance = Tok.is(tok::kw___covariant)
467 ? ObjCTypeParamVariance::Covariant
468 : ObjCTypeParamVariance::Contravariant;
469 varianceLoc = ConsumeToken();
471 // Once we've seen a variance specific , we know this is not a
472 // list of protocol references.
473 if (mayBeProtocolList) {
474 // Up until now, we have been queuing up parameters because they
475 // might be protocol references. Turn them into parameters now.
476 makeProtocolIdentsIntoTypeParameters();
480 // Parse the identifier.
481 if (!Tok.is(tok::identifier)) {
483 if (Tok.is(tok::code_completion)) {
484 // FIXME: If these aren't protocol references, we'll need different
486 Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
489 // FIXME: Better recovery here?.
493 Diag(Tok, diag::err_objc_expected_type_parameter);
498 IdentifierInfo *paramName = Tok.getIdentifierInfo();
499 SourceLocation paramLoc = ConsumeToken();
501 // If there is a bound, parse it.
502 SourceLocation colonLoc;
503 TypeResult boundType;
504 if (TryConsumeToken(tok::colon, colonLoc)) {
505 // Once we've seen a bound, we know this is not a list of protocol
507 if (mayBeProtocolList) {
508 // Up until now, we have been queuing up parameters because they
509 // might be protocol references. Turn them into parameters now.
510 makeProtocolIdentsIntoTypeParameters();
514 boundType = ParseTypeName();
515 if (boundType.isInvalid())
517 } else if (mayBeProtocolList) {
518 // If this could still be a protocol list, just capture the identifier.
519 // We don't want to turn it into a parameter.
520 protocolIdents.push_back(std::make_pair(paramName, paramLoc));
524 // Create the type parameter.
525 DeclResult typeParam = Actions.actOnObjCTypeParam(
526 getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
527 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
528 if (typeParam.isUsable())
529 typeParams.push_back(typeParam.get());
530 } while (TryConsumeToken(tok::comma));
534 SkipUntil(tok::greater, tok::at, StopBeforeMatch);
535 if (Tok.is(tok::greater))
537 } else if (ParseGreaterThanInTemplateList(rAngleLoc,
538 /*ConsumeLastToken=*/true,
539 /*ObjCGenericList=*/true)) {
540 Diag(lAngleLoc, diag::note_matching) << "'<'";
541 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
542 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
543 tok::comma, tok::semi },
545 if (Tok.is(tok::greater))
549 if (mayBeProtocolList) {
550 // A type parameter list must be followed by either a ':' (indicating the
551 // presence of a superclass) or a '(' (indicating that this is a category
552 // or extension). This disambiguates between an objc-type-parameter-list
553 // and a objc-protocol-refs.
554 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
555 // Returning null indicates that we don't have a type parameter list.
556 // The results the caller needs to handle the protocol references are
557 // captured in the reference parameters already.
561 // We have a type parameter list that looks like a list of protocol
562 // references. Turn that parameter list into type parameters.
563 makeProtocolIdentsIntoTypeParameters();
566 // Form the type parameter list and enter its scope.
567 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
574 // Clear out the angle locations; they're used by the caller to indicate
575 // whether there are any protocol references.
576 lAngleLoc = SourceLocation();
577 rAngleLoc = SourceLocation();
578 return invalid ? nullptr : list;
581 /// Parse an objc-type-parameter-list.
582 ObjCTypeParamList *Parser::parseObjCTypeParamList() {
583 SourceLocation lAngleLoc;
584 SmallVector<IdentifierLocPair, 1> protocolIdents;
585 SourceLocation rAngleLoc;
587 ObjCTypeParamListScope Scope(Actions, getCurScope());
588 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
590 /*mayBeProtocolList=*/false);
593 /// objc-interface-decl-list:
595 /// objc-interface-decl-list objc-property-decl [OBJC2]
596 /// objc-interface-decl-list objc-method-requirement [OBJC2]
597 /// objc-interface-decl-list objc-method-proto ';'
598 /// objc-interface-decl-list declaration
599 /// objc-interface-decl-list ';'
601 /// objc-method-requirement: [OBJC2]
605 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
607 SmallVector<Decl *, 32> allMethods;
608 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
609 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
614 // If this is a method prototype, parse it.
615 if (Tok.isOneOf(tok::minus, tok::plus)) {
616 if (Decl *methodPrototype =
617 ParseObjCMethodPrototype(MethodImplKind, false))
618 allMethods.push_back(methodPrototype);
619 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
620 // method definitions.
621 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
622 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
623 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
624 if (Tok.is(tok::semi))
629 if (Tok.is(tok::l_paren)) {
630 Diag(Tok, diag::err_expected_minus_or_plus);
631 ParseObjCMethodDecl(Tok.getLocation(),
633 MethodImplKind, false);
636 // Ignore excess semicolons.
637 if (Tok.is(tok::semi)) {
642 // If we got to the end of the file, exit the loop.
646 // Code completion within an Objective-C interface.
647 if (Tok.is(tok::code_completion)) {
648 Actions.CodeCompleteOrdinaryName(getCurScope(),
649 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
650 : Sema::PCC_ObjCInterface);
651 return cutOffParsing();
654 // If we don't have an @ directive, parse it as a function definition.
655 if (Tok.isNot(tok::at)) {
656 // The code below does not consume '}'s because it is afraid of eating the
657 // end of a namespace. Because of the way this code is structured, an
658 // erroneous r_brace would cause an infinite loop if not handled here.
659 if (Tok.is(tok::r_brace))
661 ParsedAttributesWithRange attrs(AttrFactory);
662 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
666 // Otherwise, we have an @ directive, eat the @.
667 SourceLocation AtLoc = ConsumeToken(); // the "@"
668 if (Tok.is(tok::code_completion)) {
669 Actions.CodeCompleteObjCAtDirective(getCurScope());
670 return cutOffParsing();
673 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
675 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
676 AtEnd.setBegin(AtLoc);
677 AtEnd.setEnd(Tok.getLocation());
679 } else if (DirectiveKind == tok::objc_not_keyword) {
680 Diag(Tok, diag::err_objc_unknown_at);
681 SkipUntil(tok::semi);
685 // Eat the identifier.
688 switch (DirectiveKind) {
690 // FIXME: If someone forgets an @end on a protocol, this loop will
691 // continue to eat up tons of stuff and spew lots of nonsense errors. It
692 // would probably be better to bail out if we saw an @class or @interface
693 // or something like that.
694 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
695 // Skip until we see an '@' or '}' or ';'.
696 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
699 case tok::objc_implementation:
700 case tok::objc_interface:
701 Diag(AtLoc, diag::err_objc_missing_end)
702 << FixItHint::CreateInsertion(AtLoc, "@end\n");
703 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
704 << (int) Actions.getObjCContainerKind();
708 case tok::objc_required:
709 case tok::objc_optional:
710 // This is only valid on protocols.
711 // FIXME: Should this check for ObjC2 being enabled?
712 if (contextKey != tok::objc_protocol)
713 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
715 MethodImplKind = DirectiveKind;
718 case tok::objc_property:
719 if (!getLangOpts().ObjC2)
720 Diag(AtLoc, diag::err_objc_properties_require_objc2);
723 SourceLocation LParenLoc;
724 // Parse property attribute list, if any.
725 if (Tok.is(tok::l_paren)) {
726 LParenLoc = Tok.getLocation();
727 ParseObjCPropertyAttribute(OCDS);
730 bool addedToDeclSpec = false;
731 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
732 if (FD.D.getIdentifier() == nullptr) {
733 Diag(AtLoc, diag::err_objc_property_requires_field_name)
734 << FD.D.getSourceRange();
737 if (FD.BitfieldSize) {
738 Diag(AtLoc, diag::err_objc_property_bitfield)
739 << FD.D.getSourceRange();
743 // Map a nullability property attribute to a context-sensitive keyword
745 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
746 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
747 OCDS.getNullabilityLoc(),
750 // Install the property declarator into interfaceDecl.
751 IdentifierInfo *SelName =
752 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
754 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
755 IdentifierInfo *SetterName = OCDS.getSetterName();
758 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
760 SetterSel = SelectorTable::constructSetterSelector(
761 PP.getIdentifierTable(), PP.getSelectorTable(),
762 FD.D.getIdentifier());
763 Decl *Property = Actions.ActOnProperty(
764 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
767 FD.complete(Property);
770 // Parse all the comma separated declarators.
771 ParsingDeclSpec DS(*this);
772 ParseStructDeclaration(DS, ObjCPropertyCallback);
774 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
779 // We break out of the big loop in two cases: when we see @end or when we see
780 // EOF. In the former case, eat the @end. In the later case, emit an error.
781 if (Tok.is(tok::code_completion)) {
782 Actions.CodeCompleteObjCAtDirective(getCurScope());
783 return cutOffParsing();
784 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
785 ConsumeToken(); // the "end" identifier
787 Diag(Tok, diag::err_objc_missing_end)
788 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
789 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
790 << (int) Actions.getObjCContainerKind();
791 AtEnd.setBegin(Tok.getLocation());
792 AtEnd.setEnd(Tok.getLocation());
795 // Insert collected methods declarations into the @interface object.
796 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
797 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
800 /// Diagnose redundant or conflicting nullability information.
801 static void diagnoseRedundantPropertyNullability(Parser &P,
803 NullabilityKind nullability,
804 SourceLocation nullabilityLoc){
805 if (DS.getNullability() == nullability) {
806 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
807 << DiagNullabilityKind(nullability, true)
808 << SourceRange(DS.getNullabilityLoc());
812 P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
813 << DiagNullabilityKind(nullability, true)
814 << DiagNullabilityKind(DS.getNullability(), true)
815 << SourceRange(DS.getNullabilityLoc());
818 /// Parse property attribute declarations.
820 /// property-attr-decl: '(' property-attrlist ')'
821 /// property-attrlist:
822 /// property-attribute
823 /// property-attrlist ',' property-attribute
824 /// property-attribute:
825 /// getter '=' identifier
826 /// setter '=' identifier ':'
836 /// unsafe_unretained
843 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
844 assert(Tok.getKind() == tok::l_paren);
845 BalancedDelimiterTracker T(*this, tok::l_paren);
849 if (Tok.is(tok::code_completion)) {
850 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
851 return cutOffParsing();
853 const IdentifierInfo *II = Tok.getIdentifierInfo();
855 // If this is not an identifier at all, bail out early.
861 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
863 if (II->isStr("readonly"))
864 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
865 else if (II->isStr("assign"))
866 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
867 else if (II->isStr("unsafe_unretained"))
868 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
869 else if (II->isStr("readwrite"))
870 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
871 else if (II->isStr("retain"))
872 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
873 else if (II->isStr("strong"))
874 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
875 else if (II->isStr("copy"))
876 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
877 else if (II->isStr("nonatomic"))
878 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
879 else if (II->isStr("atomic"))
880 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
881 else if (II->isStr("weak"))
882 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
883 else if (II->isStr("getter") || II->isStr("setter")) {
884 bool IsSetter = II->getNameStart()[0] == 's';
886 // getter/setter require extra treatment.
887 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
888 diag::err_objc_expected_equal_for_getter;
890 if (ExpectAndConsume(tok::equal, DiagID)) {
891 SkipUntil(tok::r_paren, StopAtSemi);
895 if (Tok.is(tok::code_completion)) {
897 Actions.CodeCompleteObjCPropertySetter(getCurScope());
899 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
900 return cutOffParsing();
903 SourceLocation SelLoc;
904 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
907 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
909 SkipUntil(tok::r_paren, StopAtSemi);
914 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
915 DS.setSetterName(SelIdent, SelLoc);
917 if (ExpectAndConsume(tok::colon,
918 diag::err_expected_colon_after_setter_name)) {
919 SkipUntil(tok::r_paren, StopAtSemi);
923 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
924 DS.setGetterName(SelIdent, SelLoc);
926 } else if (II->isStr("nonnull")) {
927 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
928 diagnoseRedundantPropertyNullability(*this, DS,
929 NullabilityKind::NonNull,
931 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
932 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
933 } else if (II->isStr("nullable")) {
934 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
935 diagnoseRedundantPropertyNullability(*this, DS,
936 NullabilityKind::Nullable,
938 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
939 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
940 } else if (II->isStr("null_unspecified")) {
941 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
942 diagnoseRedundantPropertyNullability(*this, DS,
943 NullabilityKind::Unspecified,
945 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
946 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
947 } else if (II->isStr("null_resettable")) {
948 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
949 diagnoseRedundantPropertyNullability(*this, DS,
950 NullabilityKind::Unspecified,
952 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
953 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
955 // Also set the null_resettable bit.
956 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable);
957 } else if (II->isStr("class")) {
958 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class);
960 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
961 SkipUntil(tok::r_paren, StopAtSemi);
965 if (Tok.isNot(tok::comma))
974 /// objc-method-proto:
975 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
976 /// objc-class-method objc-method-decl objc-method-attributes[opt]
978 /// objc-instance-method: '-'
979 /// objc-class-method: '+'
981 /// objc-method-attributes: [OBJC2]
982 /// __attribute__((deprecated))
984 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
985 bool MethodDefinition) {
986 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
988 tok::TokenKind methodType = Tok.getKind();
989 SourceLocation mLoc = ConsumeToken();
990 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
992 // Since this rule is used for both method declarations and definitions,
993 // the caller is (optionally) responsible for consuming the ';'.
1000 /// enum struct union if else while do for switch case default
1001 /// break continue return goto asm sizeof typeof __alignof
1002 /// unsigned long const short volatile signed restrict _Complex
1003 /// in out inout bycopy byref oneway int char float double void _Bool
1005 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
1007 switch (Tok.getKind()) {
1016 case tok::exclaimequal:
1018 case tok::pipeequal:
1020 case tok::caretequal: {
1021 std::string ThisTok(PP.getSpelling(Tok));
1022 if (isLetter(ThisTok[0])) {
1023 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1024 Tok.setKind(tok::identifier);
1025 SelectorLoc = ConsumeToken();
1031 case tok::identifier:
1041 case tok::kw_const_cast:
1042 case tok::kw_continue:
1043 case tok::kw_default:
1044 case tok::kw_delete:
1046 case tok::kw_double:
1047 case tok::kw_dynamic_cast:
1050 case tok::kw_explicit:
1051 case tok::kw_export:
1052 case tok::kw_extern:
1056 case tok::kw_friend:
1059 case tok::kw_inline:
1062 case tok::kw_mutable:
1063 case tok::kw_namespace:
1065 case tok::kw_operator:
1066 case tok::kw_private:
1067 case tok::kw_protected:
1068 case tok::kw_public:
1069 case tok::kw_register:
1070 case tok::kw_reinterpret_cast:
1071 case tok::kw_restrict:
1072 case tok::kw_return:
1074 case tok::kw_signed:
1075 case tok::kw_sizeof:
1076 case tok::kw_static:
1077 case tok::kw_static_cast:
1078 case tok::kw_struct:
1079 case tok::kw_switch:
1080 case tok::kw_template:
1085 case tok::kw_typedef:
1086 case tok::kw_typeid:
1087 case tok::kw_typename:
1088 case tok::kw_typeof:
1090 case tok::kw_unsigned:
1092 case tok::kw_virtual:
1094 case tok::kw_volatile:
1095 case tok::kw_wchar_t:
1098 case tok::kw__Complex:
1099 case tok::kw___alignof:
1100 case tok::kw___auto_type:
1101 IdentifierInfo *II = Tok.getIdentifierInfo();
1102 SelectorLoc = ConsumeToken();
1107 /// objc-for-collection-in: 'in'
1109 bool Parser::isTokIdentifier_in() const {
1110 // FIXME: May have to do additional look-ahead to only allow for
1111 // valid tokens following an 'in'; such as an identifier, unary operators,
1113 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
1114 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1117 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1118 /// qualifier list and builds their bitmask representation in the input
1121 /// objc-type-qualifiers:
1122 /// objc-type-qualifier
1123 /// objc-type-qualifiers objc-type-qualifier
1125 /// objc-type-qualifier:
1134 /// 'null_unspecified'
1136 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1137 Declarator::TheContext Context) {
1138 assert(Context == Declarator::ObjCParameterContext ||
1139 Context == Declarator::ObjCResultContext);
1142 if (Tok.is(tok::code_completion)) {
1143 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
1144 Context == Declarator::ObjCParameterContext);
1145 return cutOffParsing();
1148 if (Tok.isNot(tok::identifier))
1151 const IdentifierInfo *II = Tok.getIdentifierInfo();
1152 for (unsigned i = 0; i != objc_NumQuals; ++i) {
1153 if (II != ObjCTypeQuals[i] ||
1154 NextToken().is(tok::less) ||
1155 NextToken().is(tok::coloncolon))
1158 ObjCDeclSpec::ObjCDeclQualifier Qual;
1159 NullabilityKind Nullability;
1161 default: llvm_unreachable("Unknown decl qualifier");
1162 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
1163 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
1164 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
1165 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1166 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1167 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
1170 Qual = ObjCDeclSpec::DQ_CSNullability;
1171 Nullability = NullabilityKind::NonNull;
1175 Qual = ObjCDeclSpec::DQ_CSNullability;
1176 Nullability = NullabilityKind::Nullable;
1179 case objc_null_unspecified:
1180 Qual = ObjCDeclSpec::DQ_CSNullability;
1181 Nullability = NullabilityKind::Unspecified;
1185 // FIXME: Diagnose redundant specifiers.
1186 DS.setObjCDeclQualifier(Qual);
1187 if (Qual == ObjCDeclSpec::DQ_CSNullability)
1188 DS.setNullability(Tok.getLocation(), Nullability);
1195 // If this wasn't a recognized qualifier, bail out.
1200 /// Take all the decl attributes out of the given list and add
1201 /// them to the given attribute set.
1202 static void takeDeclAttributes(ParsedAttributes &attrs,
1203 AttributeList *list) {
1205 AttributeList *cur = list;
1206 list = cur->getNext();
1208 if (!cur->isUsedAsTypeAttr()) {
1209 // Clear out the next pointer. We're really completely
1210 // destroying the internal invariants of the declarator here,
1211 // but it doesn't matter because we're done with it.
1212 cur->setNext(nullptr);
1218 /// takeDeclAttributes - Take all the decl attributes from the given
1219 /// declarator and add them to the given list.
1220 static void takeDeclAttributes(ParsedAttributes &attrs,
1222 // First, take ownership of all attributes.
1223 attrs.getPool().takeAllFrom(D.getAttributePool());
1224 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1226 // Now actually move the attributes over.
1227 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
1228 takeDeclAttributes(attrs, D.getAttributes());
1229 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1230 takeDeclAttributes(attrs,
1231 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
1235 /// '(' objc-type-qualifiers[opt] type-name ')'
1236 /// '(' objc-type-qualifiers[opt] ')'
1238 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1239 Declarator::TheContext context,
1240 ParsedAttributes *paramAttrs) {
1241 assert(context == Declarator::ObjCParameterContext ||
1242 context == Declarator::ObjCResultContext);
1243 assert((paramAttrs != nullptr) ==
1244 (context == Declarator::ObjCParameterContext));
1246 assert(Tok.is(tok::l_paren) && "expected (");
1248 BalancedDelimiterTracker T(*this, tok::l_paren);
1251 SourceLocation TypeStartLoc = Tok.getLocation();
1252 ObjCDeclContextSwitch ObjCDC(*this);
1254 // Parse type qualifiers, in, inout, etc.
1255 ParseObjCTypeQualifierList(DS, context);
1258 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1259 // Parse an abstract declarator.
1260 DeclSpec declSpec(AttrFactory);
1261 declSpec.setObjCQualifiers(&DS);
1262 DeclSpecContext dsContext = DSC_normal;
1263 if (context == Declarator::ObjCResultContext)
1264 dsContext = DSC_objc_method_result;
1265 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1266 Declarator declarator(declSpec, context);
1267 ParseDeclarator(declarator);
1269 // If that's not invalid, extract a type.
1270 if (!declarator.isInvalidType()) {
1271 // Map a nullability specifier to a context-sensitive keyword attribute.
1272 bool addedToDeclSpec = false;
1273 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1274 addContextSensitiveTypeNullability(*this, declarator,
1275 DS.getNullability(),
1276 DS.getNullabilityLoc(),
1279 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1280 if (!type.isInvalid())
1283 // If we're parsing a parameter, steal all the decl attributes
1284 // and add them to the decl spec.
1285 if (context == Declarator::ObjCParameterContext)
1286 takeDeclAttributes(*paramAttrs, declarator);
1290 if (Tok.is(tok::r_paren))
1292 else if (Tok.getLocation() == TypeStartLoc) {
1293 // If we didn't eat any tokens, then this isn't a type.
1294 Diag(Tok, diag::err_expected_type);
1295 SkipUntil(tok::r_paren, StopAtSemi);
1297 // Otherwise, we found *something*, but didn't get a ')' in the right
1298 // place. Emit an error then return what we have as the type.
1304 /// objc-method-decl:
1306 /// objc-keyword-selector objc-parmlist[opt]
1307 /// objc-type-name objc-selector
1308 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1310 /// objc-keyword-selector:
1311 /// objc-keyword-decl
1312 /// objc-keyword-selector objc-keyword-decl
1314 /// objc-keyword-decl:
1315 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1316 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1317 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1318 /// ':' objc-keyword-attributes[opt] identifier
1321 /// objc-parms objc-ellipsis[opt]
1324 /// objc-parms , parameter-declaration
1329 /// objc-keyword-attributes: [OBJC2]
1330 /// __attribute__((unused))
1332 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1333 tok::TokenKind mType,
1334 tok::ObjCKeywordKind MethodImplKind,
1335 bool MethodDefinition) {
1336 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1338 if (Tok.is(tok::code_completion)) {
1339 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1340 /*ReturnType=*/nullptr);
1345 // Parse the return type if present.
1346 ParsedType ReturnType;
1348 if (Tok.is(tok::l_paren))
1349 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext,
1352 // If attributes exist before the method, parse them.
1353 ParsedAttributes methodAttrs(AttrFactory);
1354 if (getLangOpts().ObjC2)
1355 MaybeParseGNUAttributes(methodAttrs);
1357 if (Tok.is(tok::code_completion)) {
1358 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1364 // Now parse the selector.
1365 SourceLocation selLoc;
1366 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1368 // An unnamed colon is valid.
1369 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1370 Diag(Tok, diag::err_expected_selector_for_method)
1371 << SourceRange(mLoc, Tok.getLocation());
1372 // Skip until we get a ; or @.
1373 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1377 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1378 if (Tok.isNot(tok::colon)) {
1379 // If attributes exist after the method, parse them.
1380 if (getLangOpts().ObjC2)
1381 MaybeParseGNUAttributes(methodAttrs);
1383 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1385 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1386 mType, DSRet, ReturnType,
1387 selLoc, Sel, nullptr,
1388 CParamInfo.data(), CParamInfo.size(),
1389 methodAttrs.getList(), MethodImplKind,
1390 false, MethodDefinition);
1391 PD.complete(Result);
1395 SmallVector<IdentifierInfo *, 12> KeyIdents;
1396 SmallVector<SourceLocation, 12> KeyLocs;
1397 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1398 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1399 Scope::FunctionDeclarationScope | Scope::DeclScope);
1401 AttributePool allParamAttrs(AttrFactory);
1403 ParsedAttributes paramAttrs(AttrFactory);
1404 Sema::ObjCArgInfo ArgInfo;
1406 // Each iteration parses a single keyword argument.
1407 if (ExpectAndConsume(tok::colon))
1410 ArgInfo.Type = nullptr;
1411 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1412 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1413 Declarator::ObjCParameterContext,
1416 // If attributes exist before the argument name, parse them.
1417 // Regardless, collect all the attributes we've parsed so far.
1418 ArgInfo.ArgAttrs = nullptr;
1419 if (getLangOpts().ObjC2) {
1420 MaybeParseGNUAttributes(paramAttrs);
1421 ArgInfo.ArgAttrs = paramAttrs.getList();
1424 // Code completion for the next piece of the selector.
1425 if (Tok.is(tok::code_completion)) {
1426 KeyIdents.push_back(SelIdent);
1427 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1428 mType == tok::minus,
1429 /*AtParameterName=*/true,
1430 ReturnType, KeyIdents);
1435 if (expectIdentifier())
1436 break; // missing argument name.
1438 ArgInfo.Name = Tok.getIdentifierInfo();
1439 ArgInfo.NameLoc = Tok.getLocation();
1440 ConsumeToken(); // Eat the identifier.
1442 ArgInfos.push_back(ArgInfo);
1443 KeyIdents.push_back(SelIdent);
1444 KeyLocs.push_back(selLoc);
1446 // Make sure the attributes persist.
1447 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1449 // Code completion for the next piece of the selector.
1450 if (Tok.is(tok::code_completion)) {
1451 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1452 mType == tok::minus,
1453 /*AtParameterName=*/false,
1454 ReturnType, KeyIdents);
1459 // Check for another keyword selector.
1460 SelIdent = ParseObjCSelectorPiece(selLoc);
1461 if (!SelIdent && Tok.isNot(tok::colon))
1464 SourceLocation ColonLoc = Tok.getLocation();
1465 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1466 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1467 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1468 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1471 // We have a selector or a colon, continue parsing.
1474 bool isVariadic = false;
1475 bool cStyleParamWarned = false;
1476 // Parse the (optional) parameter list.
1477 while (Tok.is(tok::comma)) {
1479 if (Tok.is(tok::ellipsis)) {
1484 if (!cStyleParamWarned) {
1485 Diag(Tok, diag::warn_cstyle_param);
1486 cStyleParamWarned = true;
1488 DeclSpec DS(AttrFactory);
1489 ParseDeclarationSpecifiers(DS);
1490 // Parse the declarator.
1491 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1492 ParseDeclarator(ParmDecl);
1493 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1494 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1495 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1496 ParmDecl.getIdentifierLoc(),
1501 // FIXME: Add support for optional parameter list...
1502 // If attributes exist after the method, parse them.
1503 if (getLangOpts().ObjC2)
1504 MaybeParseGNUAttributes(methodAttrs);
1506 if (KeyIdents.size() == 0)
1509 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1512 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1513 mType, DSRet, ReturnType,
1514 KeyLocs, Sel, &ArgInfos[0],
1515 CParamInfo.data(), CParamInfo.size(),
1516 methodAttrs.getList(),
1517 MethodImplKind, isVariadic, MethodDefinition);
1519 PD.complete(Result);
1523 /// objc-protocol-refs:
1524 /// '<' identifier-list '>'
1527 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1528 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1529 bool WarnOnDeclarations, bool ForObjCContainer,
1530 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1531 bool consumeLastToken) {
1532 assert(Tok.is(tok::less) && "expected <");
1534 LAngleLoc = ConsumeToken(); // the "<"
1536 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1539 if (Tok.is(tok::code_completion)) {
1540 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1545 if (expectIdentifier()) {
1546 SkipUntil(tok::greater, StopAtSemi);
1549 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1550 Tok.getLocation()));
1551 ProtocolLocs.push_back(Tok.getLocation());
1554 if (!TryConsumeToken(tok::comma))
1559 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1560 /*ObjCGenericList=*/false))
1563 // Convert the list of protocols identifiers into a list of protocol decls.
1564 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1565 ProtocolIdents, Protocols);
1569 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1570 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1571 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1573 SourceLocation lAngleLoc;
1574 SmallVector<Decl *, 8> protocols;
1575 SmallVector<SourceLocation, 8> protocolLocs;
1576 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1577 lAngleLoc, rAngleLoc,
1578 /*consumeLastToken=*/true);
1579 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1583 if (result.isUsable()) {
1584 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1585 << FixItHint::CreateInsertion(lAngleLoc, "id")
1586 << SourceRange(lAngleLoc, rAngleLoc);
1592 /// Parse Objective-C type arguments or protocol qualifiers.
1594 /// objc-type-arguments:
1595 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1597 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1598 ParsedType baseType,
1599 SourceLocation &typeArgsLAngleLoc,
1600 SmallVectorImpl<ParsedType> &typeArgs,
1601 SourceLocation &typeArgsRAngleLoc,
1602 SourceLocation &protocolLAngleLoc,
1603 SmallVectorImpl<Decl *> &protocols,
1604 SmallVectorImpl<SourceLocation> &protocolLocs,
1605 SourceLocation &protocolRAngleLoc,
1606 bool consumeLastToken,
1607 bool warnOnIncompleteProtocols) {
1608 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1609 SourceLocation lAngleLoc = ConsumeToken();
1611 // Whether all of the elements we've parsed thus far are single
1612 // identifiers, which might be types or might be protocols.
1613 bool allSingleIdentifiers = true;
1614 SmallVector<IdentifierInfo *, 4> identifiers;
1615 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1617 // Parse a list of comma-separated identifiers, bailing out if we
1618 // see something different.
1620 // Parse a single identifier.
1621 if (Tok.is(tok::identifier) &&
1622 (NextToken().is(tok::comma) ||
1623 NextToken().is(tok::greater) ||
1624 NextToken().is(tok::greatergreater))) {
1625 identifiers.push_back(Tok.getIdentifierInfo());
1626 identifierLocs.push_back(ConsumeToken());
1630 if (Tok.is(tok::code_completion)) {
1631 // FIXME: Also include types here.
1632 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1633 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1634 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1635 identifierLocs[i]));
1638 QualType BaseT = Actions.GetTypeFromParser(baseType);
1639 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1640 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1642 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1648 allSingleIdentifiers = false;
1650 } while (TryConsumeToken(tok::comma));
1652 // If we parsed an identifier list, semantic analysis sorts out
1653 // whether it refers to protocols or to type arguments.
1654 if (allSingleIdentifiers) {
1655 // Parse the closing '>'.
1656 SourceLocation rAngleLoc;
1657 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1658 /*ObjCGenericList=*/true);
1660 // Let Sema figure out what we parsed.
1661 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1673 warnOnIncompleteProtocols);
1677 // We parsed an identifier list but stumbled into non single identifiers, this
1678 // means we might (a) check that what we already parsed is a legitimate type
1679 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1680 // must all be type args.
1682 // Convert the identifiers into type arguments.
1683 bool invalid = false;
1684 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1685 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1686 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1687 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1689 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1691 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1693 DeclSpec DS(AttrFactory);
1694 const char *prevSpec = nullptr;
1696 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1697 typeArg, Actions.getASTContext().getPrintingPolicy());
1699 // Form a declarator to turn this into a type.
1700 Declarator D(DS, Declarator::TypeNameContext);
1701 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1702 if (fullTypeArg.isUsable()) {
1703 typeArgs.push_back(fullTypeArg.get());
1704 if (!foundValidTypeId) {
1705 foundValidTypeId = identifiers[i];
1706 foundValidTypeSrcLoc = identifierLocs[i];
1710 unknownTypeArgs.push_back(identifiers[i]);
1711 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1715 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1716 unknownTypeArgs.push_back(identifiers[i]);
1717 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1718 } else if (!foundProtocolId) {
1719 foundProtocolId = identifiers[i];
1720 foundProtocolSrcLoc = identifierLocs[i];
1725 // Continue parsing type-names.
1727 Token CurTypeTok = Tok;
1728 TypeResult typeArg = ParseTypeName();
1730 // Consume the '...' for a pack expansion.
1731 SourceLocation ellipsisLoc;
1732 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1733 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1734 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1737 if (typeArg.isUsable()) {
1738 typeArgs.push_back(typeArg.get());
1739 if (!foundValidTypeId) {
1740 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1741 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1746 } while (TryConsumeToken(tok::comma));
1748 // Diagnose the mix between type args and protocols.
1749 if (foundProtocolId && foundValidTypeId)
1750 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1752 foundValidTypeSrcLoc);
1754 // Diagnose unknown arg types.
1756 if (unknownTypeArgs.size())
1757 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1758 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1759 getCurScope(), nullptr, T);
1761 // Parse the closing '>'.
1762 SourceLocation rAngleLoc;
1763 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1764 /*ObjCGenericList=*/true);
1771 // Record left/right angle locations.
1772 typeArgsLAngleLoc = lAngleLoc;
1773 typeArgsRAngleLoc = rAngleLoc;
1776 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1777 ParsedType baseType,
1778 SourceLocation &typeArgsLAngleLoc,
1779 SmallVectorImpl<ParsedType> &typeArgs,
1780 SourceLocation &typeArgsRAngleLoc,
1781 SourceLocation &protocolLAngleLoc,
1782 SmallVectorImpl<Decl *> &protocols,
1783 SmallVectorImpl<SourceLocation> &protocolLocs,
1784 SourceLocation &protocolRAngleLoc,
1785 bool consumeLastToken) {
1786 assert(Tok.is(tok::less));
1788 // Parse the first angle-bracket-delimited clause.
1789 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1798 /*warnOnIncompleteProtocols=*/false);
1799 if (Tok.is(tok::eof)) // Nothing else to do here...
1802 // An Objective-C object pointer followed by type arguments
1803 // can then be followed again by a set of protocol references, e.g.,
1804 // \c NSArray<NSView><NSTextDelegate>
1805 if ((consumeLastToken && Tok.is(tok::less)) ||
1806 (!consumeLastToken && NextToken().is(tok::less))) {
1807 // If we aren't consuming the last token, the prior '>' is still hanging
1808 // there. Consume it before we parse the protocol qualifiers.
1809 if (!consumeLastToken)
1812 if (!protocols.empty()) {
1813 SkipUntilFlags skipFlags = SkipUntilFlags();
1814 if (!consumeLastToken)
1815 skipFlags = skipFlags | StopBeforeMatch;
1816 Diag(Tok, diag::err_objc_type_args_after_protocols)
1817 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1818 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1820 ParseObjCProtocolReferences(protocols, protocolLocs,
1821 /*WarnOnDeclarations=*/false,
1822 /*ForObjCContainer=*/false,
1823 protocolLAngleLoc, protocolRAngleLoc,
1829 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1832 bool consumeLastToken,
1833 SourceLocation &endLoc) {
1834 assert(Tok.is(tok::less));
1835 SourceLocation typeArgsLAngleLoc;
1836 SmallVector<ParsedType, 4> typeArgs;
1837 SourceLocation typeArgsRAngleLoc;
1838 SourceLocation protocolLAngleLoc;
1839 SmallVector<Decl *, 4> protocols;
1840 SmallVector<SourceLocation, 4> protocolLocs;
1841 SourceLocation protocolRAngleLoc;
1843 // Parse type arguments and protocol qualifiers.
1844 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1845 typeArgsRAngleLoc, protocolLAngleLoc,
1846 protocols, protocolLocs,
1847 protocolRAngleLoc, consumeLastToken);
1849 if (Tok.is(tok::eof))
1850 return true; // Invalid type result.
1852 // Compute the location of the last token.
1853 if (consumeLastToken)
1854 endLoc = PrevTokLocation;
1856 endLoc = Tok.getLocation();
1858 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1871 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1872 BalancedDelimiterTracker &T,
1873 SmallVectorImpl<Decl *> &AllIvarDecls,
1874 bool RBraceMissing) {
1878 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1879 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1880 Actions.ActOnObjCContainerFinishDefinition();
1881 // Call ActOnFields() even if we don't have any decls. This is useful
1882 // for code rewriting tools that need to be aware of the empty list.
1883 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1885 T.getOpenLocation(), T.getCloseLocation(), nullptr);
1888 /// objc-class-instance-variables:
1889 /// '{' objc-instance-variable-decl-list[opt] '}'
1891 /// objc-instance-variable-decl-list:
1892 /// objc-visibility-spec
1893 /// objc-instance-variable-decl ';'
1895 /// objc-instance-variable-decl-list objc-visibility-spec
1896 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1897 /// objc-instance-variable-decl-list ';'
1899 /// objc-visibility-spec:
1903 /// @package [OBJC2]
1905 /// objc-instance-variable-decl:
1906 /// struct-declaration
1908 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1909 tok::ObjCKeywordKind visibility,
1910 SourceLocation atLoc) {
1911 assert(Tok.is(tok::l_brace) && "expected {");
1912 SmallVector<Decl *, 32> AllIvarDecls;
1914 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1915 ObjCDeclContextSwitch ObjCDC(*this);
1917 BalancedDelimiterTracker T(*this, tok::l_brace);
1919 // While we still have something to read, read the instance variables.
1920 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1921 // Each iteration of this loop reads one objc-instance-variable-decl.
1923 // Check for extraneous top-level semicolon.
1924 if (Tok.is(tok::semi)) {
1925 ConsumeExtraSemi(InstanceVariableList);
1929 // Set the default visibility to private.
1930 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1931 if (Tok.is(tok::code_completion)) {
1932 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1933 return cutOffParsing();
1936 switch (Tok.getObjCKeywordID()) {
1937 case tok::objc_private:
1938 case tok::objc_public:
1939 case tok::objc_protected:
1940 case tok::objc_package:
1941 visibility = Tok.getObjCKeywordID();
1946 Diag(Tok, diag::err_objc_unexpected_atend);
1947 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1948 Tok.setKind(tok::at);
1951 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1952 T, AllIvarDecls, true);
1956 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1961 if (Tok.is(tok::code_completion)) {
1962 Actions.CodeCompleteOrdinaryName(getCurScope(),
1963 Sema::PCC_ObjCInstanceVariableList);
1964 return cutOffParsing();
1967 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1968 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1969 // Install the declarator into the interface decl.
1970 FD.D.setObjCIvar(true);
1971 Decl *Field = Actions.ActOnIvar(
1972 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1973 FD.BitfieldSize, visibility);
1974 Actions.ActOnObjCContainerFinishDefinition();
1976 AllIvarDecls.push_back(Field);
1980 // Parse all the comma separated declarators.
1981 ParsingDeclSpec DS(*this);
1982 ParseStructDeclaration(DS, ObjCIvarCallback);
1984 if (Tok.is(tok::semi)) {
1987 Diag(Tok, diag::err_expected_semi_decl_list);
1988 // Skip to end of block or statement
1989 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1992 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1993 T, AllIvarDecls, false);
1996 /// objc-protocol-declaration:
1997 /// objc-protocol-definition
1998 /// objc-protocol-forward-reference
2000 /// objc-protocol-definition:
2001 /// \@protocol identifier
2002 /// objc-protocol-refs[opt]
2003 /// objc-interface-decl-list
2006 /// objc-protocol-forward-reference:
2007 /// \@protocol identifier-list ';'
2009 /// "\@protocol identifier ;" should be resolved as "\@protocol
2010 /// identifier-list ;": objc-interface-decl-list may not start with a
2011 /// semicolon in the first alternative if objc-protocol-refs are omitted.
2012 Parser::DeclGroupPtrTy
2013 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2014 ParsedAttributes &attrs) {
2015 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2016 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2017 ConsumeToken(); // the "protocol" identifier
2019 if (Tok.is(tok::code_completion)) {
2020 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2025 MaybeSkipAttributes(tok::objc_protocol);
2027 if (expectIdentifier())
2028 return nullptr; // missing protocol name.
2029 // Save the protocol name, then consume it.
2030 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2031 SourceLocation nameLoc = ConsumeToken();
2033 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2034 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2035 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo,
2039 CheckNestedObjCContexts(AtLoc);
2041 if (Tok.is(tok::comma)) { // list of forward declarations.
2042 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2043 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2045 // Parse the list of forward declarations.
2047 ConsumeToken(); // the ','
2048 if (expectIdentifier()) {
2049 SkipUntil(tok::semi);
2052 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2053 Tok.getLocation()));
2054 ConsumeToken(); // the identifier
2056 if (Tok.isNot(tok::comma))
2060 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2063 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs,
2067 // Last, and definitely not least, parse a protocol declaration.
2068 SourceLocation LAngleLoc, EndProtoLoc;
2070 SmallVector<Decl *, 8> ProtocolRefs;
2071 SmallVector<SourceLocation, 8> ProtocolLocs;
2072 if (Tok.is(tok::less) &&
2073 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2074 LAngleLoc, EndProtoLoc,
2075 /*consumeLastToken=*/true))
2079 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
2080 ProtocolRefs.data(),
2081 ProtocolRefs.size(),
2082 ProtocolLocs.data(),
2083 EndProtoLoc, attrs.getList());
2085 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2086 return Actions.ConvertDeclToDeclGroup(ProtoType);
2089 /// objc-implementation:
2090 /// objc-class-implementation-prologue
2091 /// objc-category-implementation-prologue
2093 /// objc-class-implementation-prologue:
2094 /// @implementation identifier objc-superclass[opt]
2095 /// objc-class-instance-variables[opt]
2097 /// objc-category-implementation-prologue:
2098 /// @implementation identifier ( identifier )
2099 Parser::DeclGroupPtrTy
2100 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
2101 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2102 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2103 CheckNestedObjCContexts(AtLoc);
2104 ConsumeToken(); // the "implementation" identifier
2106 // Code completion after '@implementation'.
2107 if (Tok.is(tok::code_completion)) {
2108 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2113 MaybeSkipAttributes(tok::objc_implementation);
2115 if (expectIdentifier())
2116 return nullptr; // missing class or category name.
2117 // We have a class or category name - consume it.
2118 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2119 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2120 Decl *ObjCImpDecl = nullptr;
2122 // Neither a type parameter list nor a list of protocol references is
2123 // permitted here. Parse and diagnose them.
2124 if (Tok.is(tok::less)) {
2125 SourceLocation lAngleLoc, rAngleLoc;
2126 SmallVector<IdentifierLocPair, 8> protocolIdents;
2127 SourceLocation diagLoc = Tok.getLocation();
2128 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2129 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2130 protocolIdents, rAngleLoc)) {
2131 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2132 << SourceRange(diagLoc, PrevTokLocation);
2133 } else if (lAngleLoc.isValid()) {
2134 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2135 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2139 if (Tok.is(tok::l_paren)) {
2140 // we have a category implementation.
2142 SourceLocation categoryLoc, rparenLoc;
2143 IdentifierInfo *categoryId = nullptr;
2145 if (Tok.is(tok::code_completion)) {
2146 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2151 if (Tok.is(tok::identifier)) {
2152 categoryId = Tok.getIdentifierInfo();
2153 categoryLoc = ConsumeToken();
2155 Diag(Tok, diag::err_expected)
2156 << tok::identifier; // missing category name.
2159 if (Tok.isNot(tok::r_paren)) {
2160 Diag(Tok, diag::err_expected) << tok::r_paren;
2161 SkipUntil(tok::r_paren); // don't stop at ';'
2164 rparenLoc = ConsumeParen();
2165 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2166 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2167 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2168 SmallVector<Decl *, 4> protocols;
2169 SmallVector<SourceLocation, 4> protocolLocs;
2170 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2171 /*warnOnIncompleteProtocols=*/false,
2172 /*ForObjCContainer=*/false,
2173 protocolLAngleLoc, protocolRAngleLoc,
2174 /*consumeLastToken=*/true);
2176 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2177 AtLoc, nameId, nameLoc, categoryId,
2181 // We have a class implementation
2182 SourceLocation superClassLoc;
2183 IdentifierInfo *superClassId = nullptr;
2184 if (TryConsumeToken(tok::colon)) {
2185 // We have a super class
2186 if (expectIdentifier())
2187 return nullptr; // missing super class name.
2188 superClassId = Tok.getIdentifierInfo();
2189 superClassLoc = ConsumeToken(); // Consume super class name
2191 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2192 AtLoc, nameId, nameLoc,
2193 superClassId, superClassLoc);
2195 if (Tok.is(tok::l_brace)) // we have ivars
2196 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2197 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2198 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2200 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2201 SmallVector<Decl *, 4> protocols;
2202 SmallVector<SourceLocation, 4> protocolLocs;
2203 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2204 /*warnOnIncompleteProtocols=*/false,
2205 /*ForObjCContainer=*/false,
2206 protocolLAngleLoc, protocolRAngleLoc,
2207 /*consumeLastToken=*/true);
2210 assert(ObjCImpDecl);
2212 SmallVector<Decl *, 8> DeclsInGroup;
2215 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2216 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2217 ParsedAttributesWithRange attrs(AttrFactory);
2218 MaybeParseCXX11Attributes(attrs);
2219 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2220 DeclGroupRef DG = DGP.get();
2221 DeclsInGroup.append(DG.begin(), DG.end());
2226 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2229 Parser::DeclGroupPtrTy
2230 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2231 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2232 "ParseObjCAtEndDeclaration(): Expected @end");
2233 ConsumeToken(); // the "end" identifier
2234 if (CurParsedObjCImpl)
2235 CurParsedObjCImpl->finish(atEnd);
2237 // missing @implementation
2238 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2242 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2244 finish(P.Tok.getLocation());
2245 if (P.isEofOrEom()) {
2246 P.Diag(P.Tok, diag::err_objc_missing_end)
2247 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2248 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
2249 << Sema::OCK_Implementation;
2252 P.CurParsedObjCImpl = nullptr;
2253 assert(LateParsedObjCMethods.empty());
2256 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2258 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
2259 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2260 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2263 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2266 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2267 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2268 false/*c-functions*/);
2270 /// \brief Clear and free the cached objc methods.
2271 for (LateParsedObjCMethodContainer::iterator
2272 I = LateParsedObjCMethods.begin(),
2273 E = LateParsedObjCMethods.end(); I != E; ++I)
2275 LateParsedObjCMethods.clear();
2280 /// compatibility-alias-decl:
2281 /// @compatibility_alias alias-name class-name ';'
2283 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2284 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2285 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2286 ConsumeToken(); // consume compatibility_alias
2287 if (expectIdentifier())
2289 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2290 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2291 if (expectIdentifier())
2293 IdentifierInfo *classId = Tok.getIdentifierInfo();
2294 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2295 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2296 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2300 /// property-synthesis:
2301 /// @synthesize property-ivar-list ';'
2303 /// property-ivar-list:
2305 /// property-ivar-list ',' property-ivar
2309 /// identifier '=' identifier
2311 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2312 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2313 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2314 ConsumeToken(); // consume synthesize
2317 if (Tok.is(tok::code_completion)) {
2318 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2323 if (Tok.isNot(tok::identifier)) {
2324 Diag(Tok, diag::err_synthesized_property_name);
2325 SkipUntil(tok::semi);
2329 IdentifierInfo *propertyIvar = nullptr;
2330 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2331 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2332 SourceLocation propertyIvarLoc;
2333 if (TryConsumeToken(tok::equal)) {
2334 // property '=' ivar-name
2335 if (Tok.is(tok::code_completion)) {
2336 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2341 if (expectIdentifier())
2343 propertyIvar = Tok.getIdentifierInfo();
2344 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2346 Actions.ActOnPropertyImplDecl(
2347 getCurScope(), atLoc, propertyLoc, true,
2348 propertyId, propertyIvar, propertyIvarLoc,
2349 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2350 if (Tok.isNot(tok::comma))
2352 ConsumeToken(); // consume ','
2354 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2358 /// property-dynamic:
2359 /// @dynamic property-list
2363 /// property-list ',' identifier
2365 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2366 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2367 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2368 ConsumeToken(); // consume dynamic
2370 bool isClassProperty = false;
2371 if (Tok.is(tok::l_paren)) {
2373 const IdentifierInfo *II = Tok.getIdentifierInfo();
2376 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2377 SkipUntil(tok::r_paren, StopAtSemi);
2379 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2380 if (II->isStr("class")) {
2381 isClassProperty = true;
2382 if (Tok.isNot(tok::r_paren)) {
2383 Diag(Tok, diag::err_expected) << tok::r_paren;
2384 SkipUntil(tok::r_paren, StopAtSemi);
2388 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2389 SkipUntil(tok::r_paren, StopAtSemi);
2395 if (Tok.is(tok::code_completion)) {
2396 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2401 if (expectIdentifier()) {
2402 SkipUntil(tok::semi);
2406 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2407 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2408 Actions.ActOnPropertyImplDecl(
2409 getCurScope(), atLoc, propertyLoc, false,
2410 propertyId, nullptr, SourceLocation(),
2411 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2412 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2414 if (Tok.isNot(tok::comma))
2416 ConsumeToken(); // consume ','
2418 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2422 /// objc-throw-statement:
2423 /// throw expression[opt];
2425 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2427 ConsumeToken(); // consume throw
2428 if (Tok.isNot(tok::semi)) {
2429 Res = ParseExpression();
2430 if (Res.isInvalid()) {
2431 SkipUntil(tok::semi);
2436 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2437 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2440 /// objc-synchronized-statement:
2441 /// @synchronized '(' expression ')' compound-statement
2444 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2445 ConsumeToken(); // consume synchronized
2446 if (Tok.isNot(tok::l_paren)) {
2447 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2451 // The operand is surrounded with parentheses.
2452 ConsumeParen(); // '('
2453 ExprResult operand(ParseExpression());
2455 if (Tok.is(tok::r_paren)) {
2456 ConsumeParen(); // ')'
2458 if (!operand.isInvalid())
2459 Diag(Tok, diag::err_expected) << tok::r_paren;
2461 // Skip forward until we see a left brace, but don't consume it.
2462 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2465 // Require a compound statement.
2466 if (Tok.isNot(tok::l_brace)) {
2467 if (!operand.isInvalid())
2468 Diag(Tok, diag::err_expected) << tok::l_brace;
2472 // Check the @synchronized operand now.
2473 if (!operand.isInvalid())
2474 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2476 // Parse the compound statement within a new scope.
2477 ParseScope bodyScope(this, Scope::DeclScope);
2478 StmtResult body(ParseCompoundStatementBody());
2481 // If there was a semantic or parse error earlier with the
2482 // operand, fail now.
2483 if (operand.isInvalid())
2486 if (body.isInvalid())
2487 body = Actions.ActOnNullStmt(Tok.getLocation());
2489 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2492 /// objc-try-catch-statement:
2493 /// @try compound-statement objc-catch-list[opt]
2494 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2496 /// objc-catch-list:
2497 /// @catch ( parameter-declaration ) compound-statement
2498 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2499 /// catch-parameter-declaration:
2500 /// parameter-declaration
2503 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2504 bool catch_or_finally_seen = false;
2506 ConsumeToken(); // consume try
2507 if (Tok.isNot(tok::l_brace)) {
2508 Diag(Tok, diag::err_expected) << tok::l_brace;
2511 StmtVector CatchStmts;
2512 StmtResult FinallyStmt;
2513 ParseScope TryScope(this, Scope::DeclScope);
2514 StmtResult TryBody(ParseCompoundStatementBody());
2516 if (TryBody.isInvalid())
2517 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2519 while (Tok.is(tok::at)) {
2520 // At this point, we need to lookahead to determine if this @ is the start
2521 // of an @catch or @finally. We don't want to consume the @ token if this
2522 // is an @try or @encode or something else.
2523 Token AfterAt = GetLookAheadToken(1);
2524 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2525 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2528 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2529 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2530 Decl *FirstPart = nullptr;
2531 ConsumeToken(); // consume catch
2532 if (Tok.is(tok::l_paren)) {
2534 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
2535 if (Tok.isNot(tok::ellipsis)) {
2536 DeclSpec DS(AttrFactory);
2537 ParseDeclarationSpecifiers(DS);
2538 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
2539 ParseDeclarator(ParmDecl);
2541 // Inform the actions module about the declarator, so it
2542 // gets added to the current scope.
2543 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2545 ConsumeToken(); // consume '...'
2547 SourceLocation RParenLoc;
2549 if (Tok.is(tok::r_paren))
2550 RParenLoc = ConsumeParen();
2551 else // Skip over garbage, until we get to ')'. Eat the ')'.
2552 SkipUntil(tok::r_paren, StopAtSemi);
2554 StmtResult CatchBody(true);
2555 if (Tok.is(tok::l_brace))
2556 CatchBody = ParseCompoundStatementBody();
2558 Diag(Tok, diag::err_expected) << tok::l_brace;
2559 if (CatchBody.isInvalid())
2560 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2562 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2566 if (!Catch.isInvalid())
2567 CatchStmts.push_back(Catch.get());
2570 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2574 catch_or_finally_seen = true;
2576 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2577 ConsumeToken(); // consume finally
2578 ParseScope FinallyScope(this, Scope::DeclScope);
2580 StmtResult FinallyBody(true);
2581 if (Tok.is(tok::l_brace))
2582 FinallyBody = ParseCompoundStatementBody();
2584 Diag(Tok, diag::err_expected) << tok::l_brace;
2585 if (FinallyBody.isInvalid())
2586 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2587 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2589 catch_or_finally_seen = true;
2593 if (!catch_or_finally_seen) {
2594 Diag(atLoc, diag::err_missing_catch_finally);
2598 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2603 /// objc-autoreleasepool-statement:
2604 /// @autoreleasepool compound-statement
2607 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2608 ConsumeToken(); // consume autoreleasepool
2609 if (Tok.isNot(tok::l_brace)) {
2610 Diag(Tok, diag::err_expected) << tok::l_brace;
2613 // Enter a scope to hold everything within the compound stmt. Compound
2614 // statements can always hold declarations.
2615 ParseScope BodyScope(this, Scope::DeclScope);
2617 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2620 if (AutoreleasePoolBody.isInvalid())
2621 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2622 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2623 AutoreleasePoolBody.get());
2626 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2627 /// for later parsing.
2628 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2629 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2630 trySkippingFunctionBody()) {
2631 Actions.ActOnSkippedFunctionBody(MDecl);
2635 LexedMethod* LM = new LexedMethod(this, MDecl);
2636 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2637 CachedTokens &Toks = LM->Toks;
2638 // Begin by storing the '{' or 'try' or ':' token.
2639 Toks.push_back(Tok);
2640 if (Tok.is(tok::kw_try)) {
2642 if (Tok.is(tok::colon)) {
2643 Toks.push_back(Tok);
2645 while (Tok.isNot(tok::l_brace)) {
2646 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2647 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2650 Toks.push_back(Tok); // also store '{'
2652 else if (Tok.is(tok::colon)) {
2654 // FIXME: This is wrong, due to C++11 braced initialization.
2655 while (Tok.isNot(tok::l_brace)) {
2656 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2657 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2659 Toks.push_back(Tok); // also store '{'
2662 // Consume everything up to (and including) the matching right brace.
2663 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2664 while (Tok.is(tok::kw_catch)) {
2665 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2666 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2670 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2672 Decl *Parser::ParseObjCMethodDefinition() {
2673 Decl *MDecl = ParseObjCMethodPrototype();
2675 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2676 "parsing Objective-C method");
2678 // parse optional ';'
2679 if (Tok.is(tok::semi)) {
2680 if (CurParsedObjCImpl) {
2681 Diag(Tok, diag::warn_semicolon_before_method_body)
2682 << FixItHint::CreateRemoval(Tok.getLocation());
2687 // We should have an opening brace now.
2688 if (Tok.isNot(tok::l_brace)) {
2689 Diag(Tok, diag::err_expected_method_body);
2691 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2692 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2694 // If we didn't find the '{', bail out.
2695 if (Tok.isNot(tok::l_brace))
2701 SkipUntil(tok::r_brace);
2705 // Allow the rest of sema to find private method decl implementations.
2706 Actions.AddAnyMethodToGlobalPool(MDecl);
2707 assert (CurParsedObjCImpl
2708 && "ParseObjCMethodDefinition - Method out of @implementation");
2709 // Consume the tokens and store them for later parsing.
2710 StashAwayMethodOrFunctionBodyTokens(MDecl);
2714 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2715 if (Tok.is(tok::code_completion)) {
2716 Actions.CodeCompleteObjCAtStatement(getCurScope());
2721 if (Tok.isObjCAtKeyword(tok::objc_try))
2722 return ParseObjCTryStmt(AtLoc);
2724 if (Tok.isObjCAtKeyword(tok::objc_throw))
2725 return ParseObjCThrowStmt(AtLoc);
2727 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2728 return ParseObjCSynchronizedStmt(AtLoc);
2730 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2731 return ParseObjCAutoreleasePoolStmt(AtLoc);
2733 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2734 getLangOpts().DebuggerSupport) {
2735 SkipUntil(tok::semi);
2736 return Actions.ActOnNullStmt(Tok.getLocation());
2739 ExprStatementTokLoc = AtLoc;
2740 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2741 if (Res.isInvalid()) {
2742 // If the expression is invalid, skip ahead to the next semicolon. Not
2743 // doing this opens us up to the possibility of infinite loops if
2744 // ParseExpression does not consume any tokens.
2745 SkipUntil(tok::semi);
2749 // Otherwise, eat the semicolon.
2750 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2751 return Actions.ActOnExprStmt(Res);
2754 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2755 switch (Tok.getKind()) {
2756 case tok::code_completion:
2757 Actions.CodeCompleteObjCAtExpression(getCurScope());
2763 tok::TokenKind Kind = Tok.getKind();
2764 SourceLocation OpLoc = ConsumeToken();
2766 if (!Tok.is(tok::numeric_constant)) {
2767 const char *Symbol = nullptr;
2769 case tok::minus: Symbol = "-"; break;
2770 case tok::plus: Symbol = "+"; break;
2771 default: llvm_unreachable("missing unary operator case");
2773 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2778 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2779 if (Lit.isInvalid()) {
2782 ConsumeToken(); // Consume the literal token.
2784 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2785 if (Lit.isInvalid())
2788 return ParsePostfixExpressionSuffix(
2789 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2792 case tok::string_literal: // primary-expression: string-literal
2793 case tok::wide_string_literal:
2794 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2796 case tok::char_constant:
2797 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2799 case tok::numeric_constant:
2800 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2802 case tok::kw_true: // Objective-C++, etc.
2803 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2804 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2805 case tok::kw_false: // Objective-C++, etc.
2806 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2807 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2810 // Objective-C array literal
2811 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2814 // Objective-C dictionary literal
2815 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2818 // Objective-C boxed expression
2819 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2822 if (Tok.getIdentifierInfo() == nullptr)
2823 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2825 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2826 case tok::objc_encode:
2827 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2828 case tok::objc_protocol:
2829 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2830 case tok::objc_selector:
2831 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2832 case tok::objc_available:
2833 return ParseAvailabilityCheckExpr(AtLoc);
2835 const char *str = nullptr;
2836 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2837 // that this is a proper statement where such directives could actually
2839 if (GetLookAheadToken(1).is(tok::l_brace) &&
2840 ExprStatementTokLoc == AtLoc) {
2841 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2844 : (ch == 'f' ? "finally"
2845 : (ch == 'a' ? "autoreleasepool" : nullptr));
2848 SourceLocation kwLoc = Tok.getLocation();
2849 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2850 FixItHint::CreateReplacement(kwLoc, str));
2853 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2859 /// \brief Parse the receiver of an Objective-C++ message send.
2861 /// This routine parses the receiver of a message send in
2862 /// Objective-C++ either as a type or as an expression. Note that this
2863 /// routine must not be called to parse a send to 'super', since it
2864 /// has no way to return such a result.
2866 /// \param IsExpr Whether the receiver was parsed as an expression.
2868 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2869 /// IsExpr is true), the parsed expression. If the receiver was parsed
2870 /// as a type (\c IsExpr is false), the parsed type.
2872 /// \returns True if an error occurred during parsing or semantic
2873 /// analysis, in which case the arguments do not have valid
2874 /// values. Otherwise, returns false for a successful parse.
2876 /// objc-receiver: [C++]
2877 /// 'super' [not parsed here]
2879 /// simple-type-specifier
2880 /// typename-specifier
2881 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2882 InMessageExpressionRAIIObject InMessage(*this, true);
2884 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2885 tok::annot_cxxscope))
2886 TryAnnotateTypeOrScopeToken();
2888 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2891 // Make sure any typos in the receiver are corrected or diagnosed, so that
2892 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2893 // only the things that are valid ObjC receivers?
2894 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2895 if (Receiver.isInvalid())
2899 TypeOrExpr = Receiver.get();
2904 // typename-specifier
2905 // simple-type-specifier
2906 // expression (that starts with one of the above)
2907 DeclSpec DS(AttrFactory);
2908 ParseCXXSimpleTypeSpecifier(DS);
2910 if (Tok.is(tok::l_paren)) {
2911 // If we see an opening parentheses at this point, we are
2912 // actually parsing an expression that starts with a
2913 // function-style cast, e.g.,
2915 // postfix-expression:
2916 // simple-type-specifier ( expression-list [opt] )
2917 // typename-specifier ( expression-list [opt] )
2919 // Parse the remainder of this case, then the (optional)
2920 // postfix-expression suffix, followed by the (optional)
2921 // right-hand side of the binary expression. We have an
2923 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2924 if (!Receiver.isInvalid())
2925 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2926 if (!Receiver.isInvalid())
2927 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2928 if (Receiver.isInvalid())
2932 TypeOrExpr = Receiver.get();
2936 // We have a class message. Turn the simple-type-specifier or
2937 // typename-specifier we parsed into a type and parse the
2938 // remainder of the class message.
2939 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2940 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2941 if (Type.isInvalid())
2945 TypeOrExpr = Type.get().getAsOpaquePtr();
2949 /// \brief Determine whether the parser is currently referring to a an
2950 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2952 /// This routine will only return true for a subset of valid message-send
2954 bool Parser::isSimpleObjCMessageExpression() {
2955 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2956 "Incorrect start for isSimpleObjCMessageExpression");
2957 return GetLookAheadToken(1).is(tok::identifier) &&
2958 GetLookAheadToken(2).is(tok::identifier);
2961 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2962 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2963 InMessageExpression)
2968 if (Tok.is(tok::annot_typename))
2969 Type = getTypeAnnotation(Tok);
2970 else if (Tok.is(tok::identifier))
2971 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2976 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2977 const Token &AfterNext = GetLookAheadToken(2);
2978 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2979 if (Tok.is(tok::identifier))
2980 TryAnnotateTypeOrScopeToken();
2982 return Tok.is(tok::annot_typename);
2989 /// objc-message-expr:
2990 /// '[' objc-receiver objc-message-args ']'
2992 /// objc-receiver: [C]
2998 ExprResult Parser::ParseObjCMessageExpression() {
2999 assert(Tok.is(tok::l_square) && "'[' expected");
3000 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3002 if (Tok.is(tok::code_completion)) {
3003 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3008 InMessageExpressionRAIIObject InMessage(*this, true);
3010 if (getLangOpts().CPlusPlus) {
3011 // We completely separate the C and C++ cases because C++ requires
3012 // more complicated (read: slower) parsing.
3014 // Handle send to super.
3015 // FIXME: This doesn't benefit from the same typo-correction we
3016 // get in Objective-C.
3017 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3018 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3019 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3022 // Parse the receiver, which is either a type or an expression.
3024 void *TypeOrExpr = nullptr;
3025 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3026 SkipUntil(tok::r_square, StopAtSemi);
3031 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3032 static_cast<Expr *>(TypeOrExpr));
3034 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3035 ParsedType::getFromOpaquePtr(TypeOrExpr),
3039 if (Tok.is(tok::identifier)) {
3040 IdentifierInfo *Name = Tok.getIdentifierInfo();
3041 SourceLocation NameLoc = Tok.getLocation();
3042 ParsedType ReceiverType;
3043 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3044 Name == Ident_super,
3045 NextToken().is(tok::period),
3047 case Sema::ObjCSuperMessage:
3048 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3051 case Sema::ObjCClassMessage:
3052 if (!ReceiverType) {
3053 SkipUntil(tok::r_square, StopAtSemi);
3057 ConsumeToken(); // the type name
3059 // Parse type arguments and protocol qualifiers.
3060 if (Tok.is(tok::less)) {
3061 SourceLocation NewEndLoc;
3062 TypeResult NewReceiverType
3063 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3064 /*consumeLastToken=*/true,
3066 if (!NewReceiverType.isUsable()) {
3067 SkipUntil(tok::r_square, StopAtSemi);
3071 ReceiverType = NewReceiverType.get();
3074 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3075 ReceiverType, nullptr);
3077 case Sema::ObjCInstanceMessage:
3078 // Fall through to parse an expression.
3083 // Otherwise, an arbitrary expression can be the receiver of a send.
3084 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3085 if (Res.isInvalid()) {
3086 SkipUntil(tok::r_square, StopAtSemi);
3090 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3094 /// \brief Parse the remainder of an Objective-C message following the
3095 /// '[' objc-receiver.
3097 /// This routine handles sends to super, class messages (sent to a
3098 /// class name), and instance messages (sent to an object), and the
3099 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3100 /// ReceiverExpr, respectively. Only one of these parameters may have
3103 /// \param LBracLoc The location of the opening '['.
3105 /// \param SuperLoc If this is a send to 'super', the location of the
3106 /// 'super' keyword that indicates a send to the superclass.
3108 /// \param ReceiverType If this is a class message, the type of the
3109 /// class we are sending a message to.
3111 /// \param ReceiverExpr If this is an instance message, the expression
3112 /// used to compute the receiver object.
3114 /// objc-message-args:
3116 /// objc-keywordarg-list
3118 /// objc-keywordarg-list:
3120 /// objc-keywordarg-list objc-keywordarg
3122 /// objc-keywordarg:
3123 /// selector-name[opt] ':' objc-keywordexpr
3125 /// objc-keywordexpr:
3126 /// nonempty-expr-list
3128 /// nonempty-expr-list:
3129 /// assignment-expression
3130 /// nonempty-expr-list , assignment-expression
3133 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3134 SourceLocation SuperLoc,
3135 ParsedType ReceiverType,
3136 Expr *ReceiverExpr) {
3137 InMessageExpressionRAIIObject InMessage(*this, true);
3139 if (Tok.is(tok::code_completion)) {
3140 if (SuperLoc.isValid())
3141 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3143 else if (ReceiverType)
3144 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3147 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3153 // Parse objc-selector
3155 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3157 SmallVector<IdentifierInfo *, 12> KeyIdents;
3158 SmallVector<SourceLocation, 12> KeyLocs;
3159 ExprVector KeyExprs;
3161 if (Tok.is(tok::colon)) {
3163 // Each iteration parses a single keyword argument.
3164 KeyIdents.push_back(selIdent);
3165 KeyLocs.push_back(Loc);
3167 if (ExpectAndConsume(tok::colon)) {
3168 // We must manually skip to a ']', otherwise the expression skipper will
3169 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3170 // the enclosing expression.
3171 SkipUntil(tok::r_square, StopAtSemi);
3175 /// Parse the expression after ':'
3177 if (Tok.is(tok::code_completion)) {
3178 if (SuperLoc.isValid())
3179 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3181 /*AtArgumentEpression=*/true);
3182 else if (ReceiverType)
3183 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3185 /*AtArgumentEpression=*/true);
3187 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3189 /*AtArgumentEpression=*/true);
3196 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3197 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3198 Expr = ParseBraceInitializer();
3200 Expr = ParseAssignmentExpression();
3202 ExprResult Res(Expr);
3203 if (Res.isInvalid()) {
3204 // We must manually skip to a ']', otherwise the expression skipper will
3205 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3206 // the enclosing expression.
3207 SkipUntil(tok::r_square, StopAtSemi);
3211 // We have a valid expression.
3212 KeyExprs.push_back(Res.get());
3214 // Code completion after each argument.
3215 if (Tok.is(tok::code_completion)) {
3216 if (SuperLoc.isValid())
3217 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3219 /*AtArgumentEpression=*/false);
3220 else if (ReceiverType)
3221 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3223 /*AtArgumentEpression=*/false);
3225 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3227 /*AtArgumentEpression=*/false);
3232 // Check for another keyword selector.
3233 selIdent = ParseObjCSelectorPiece(Loc);
3234 if (!selIdent && Tok.isNot(tok::colon))
3236 // We have a selector or a colon, continue parsing.
3238 // Parse the, optional, argument list, comma separated.
3239 while (Tok.is(tok::comma)) {
3240 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3241 /// Parse the expression after ','
3242 ExprResult Res(ParseAssignmentExpression());
3243 if (Tok.is(tok::colon))
3244 Res = Actions.CorrectDelayedTyposInExpr(Res);
3245 if (Res.isInvalid()) {
3246 if (Tok.is(tok::colon)) {
3247 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3248 FixItHint::CreateRemoval(commaLoc);
3250 // We must manually skip to a ']', otherwise the expression skipper will
3251 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3252 // the enclosing expression.
3253 SkipUntil(tok::r_square, StopAtSemi);
3257 // We have a valid expression.
3258 KeyExprs.push_back(Res.get());
3260 } else if (!selIdent) {
3261 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3263 // We must manually skip to a ']', otherwise the expression skipper will
3264 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3265 // the enclosing expression.
3266 SkipUntil(tok::r_square, StopAtSemi);
3270 if (Tok.isNot(tok::r_square)) {
3271 Diag(Tok, diag::err_expected)
3272 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3273 // We must manually skip to a ']', otherwise the expression skipper will
3274 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3275 // the enclosing expression.
3276 SkipUntil(tok::r_square, StopAtSemi);
3280 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3282 unsigned nKeys = KeyIdents.size();
3284 KeyIdents.push_back(selIdent);
3285 KeyLocs.push_back(Loc);
3287 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3289 if (SuperLoc.isValid())
3290 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3291 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3292 else if (ReceiverType)
3293 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3294 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3295 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3296 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3299 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3300 ExprResult Res(ParseStringLiteralExpression());
3301 if (Res.isInvalid()) return Res;
3303 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3304 // expressions. At this point, we know that the only valid thing that starts
3305 // with '@' is an @"".
3306 SmallVector<SourceLocation, 4> AtLocs;
3307 ExprVector AtStrings;
3308 AtLocs.push_back(AtLoc);
3309 AtStrings.push_back(Res.get());
3311 while (Tok.is(tok::at)) {
3312 AtLocs.push_back(ConsumeToken()); // eat the @.
3314 // Invalid unless there is a string literal.
3315 if (!isTokenStringLiteral())
3316 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3318 ExprResult Lit(ParseStringLiteralExpression());
3319 if (Lit.isInvalid())
3322 AtStrings.push_back(Lit.get());
3325 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3328 /// ParseObjCBooleanLiteral -
3329 /// objc-scalar-literal : '@' boolean-keyword
3331 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3333 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3335 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3336 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3339 /// ParseObjCCharacterLiteral -
3340 /// objc-scalar-literal : '@' character-literal
3342 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3343 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3344 if (Lit.isInvalid()) {
3347 ConsumeToken(); // Consume the literal token.
3348 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3351 /// ParseObjCNumericLiteral -
3352 /// objc-scalar-literal : '@' scalar-literal
3354 /// scalar-literal : | numeric-constant /* any numeric constant. */
3356 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3357 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3358 if (Lit.isInvalid()) {
3361 ConsumeToken(); // Consume the literal token.
3362 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3365 /// ParseObjCBoxedExpr -
3366 /// objc-box-expression:
3367 /// @( assignment-expression )
3369 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3370 if (Tok.isNot(tok::l_paren))
3371 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3373 BalancedDelimiterTracker T(*this, tok::l_paren);
3375 ExprResult ValueExpr(ParseAssignmentExpression());
3376 if (T.consumeClose())
3379 if (ValueExpr.isInvalid())
3382 // Wrap the sub-expression in a parenthesized expression, to distinguish
3383 // a boxed expression from a literal.
3384 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3385 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3386 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3390 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3391 ExprVector ElementExprs; // array elements.
3392 ConsumeBracket(); // consume the l_square.
3394 bool HasInvalidEltExpr = false;
3395 while (Tok.isNot(tok::r_square)) {
3396 // Parse list of array element expressions (all must be id types).
3397 ExprResult Res(ParseAssignmentExpression());
3398 if (Res.isInvalid()) {
3399 // We must manually skip to a ']', otherwise the expression skipper will
3400 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3401 // the enclosing expression.
3402 SkipUntil(tok::r_square, StopAtSemi);
3406 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3407 if (Res.isInvalid())
3408 HasInvalidEltExpr = true;
3410 // Parse the ellipsis that indicates a pack expansion.
3411 if (Tok.is(tok::ellipsis))
3412 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3413 if (Res.isInvalid())
3414 HasInvalidEltExpr = true;
3416 ElementExprs.push_back(Res.get());
3418 if (Tok.is(tok::comma))
3419 ConsumeToken(); // Eat the ','.
3420 else if (Tok.isNot(tok::r_square))
3421 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3424 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3426 if (HasInvalidEltExpr)
3429 MultiExprArg Args(ElementExprs);
3430 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3433 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3434 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3435 ConsumeBrace(); // consume the l_square.
3436 bool HasInvalidEltExpr = false;
3437 while (Tok.isNot(tok::r_brace)) {
3438 // Parse the comma separated key : value expressions.
3441 ColonProtectionRAIIObject X(*this);
3442 KeyExpr = ParseAssignmentExpression();
3443 if (KeyExpr.isInvalid()) {
3444 // We must manually skip to a '}', otherwise the expression skipper will
3445 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3446 // the enclosing expression.
3447 SkipUntil(tok::r_brace, StopAtSemi);
3452 if (ExpectAndConsume(tok::colon)) {
3453 SkipUntil(tok::r_brace, StopAtSemi);
3457 ExprResult ValueExpr(ParseAssignmentExpression());
3458 if (ValueExpr.isInvalid()) {
3459 // We must manually skip to a '}', otherwise the expression skipper will
3460 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3461 // the enclosing expression.
3462 SkipUntil(tok::r_brace, StopAtSemi);
3466 // Check the key and value for possible typos
3467 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3468 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3469 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3470 HasInvalidEltExpr = true;
3472 // Parse the ellipsis that designates this as a pack expansion. Do not
3473 // ActOnPackExpansion here, leave it to template instantiation time where
3474 // we can get better diagnostics.
3475 SourceLocation EllipsisLoc;
3476 if (getLangOpts().CPlusPlus)
3477 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3479 // We have a valid expression. Collect it in a vector so we can
3480 // build the argument list.
3481 ObjCDictionaryElement Element = {
3482 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3484 Elements.push_back(Element);
3486 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3487 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3490 SourceLocation EndLoc = ConsumeBrace();
3492 if (HasInvalidEltExpr)
3495 // Create the ObjCDictionaryLiteral.
3496 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3500 /// objc-encode-expression:
3501 /// \@encode ( type-name )
3503 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3504 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3506 SourceLocation EncLoc = ConsumeToken();
3508 if (Tok.isNot(tok::l_paren))
3509 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3511 BalancedDelimiterTracker T(*this, tok::l_paren);
3514 TypeResult Ty = ParseTypeName();
3521 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3522 Ty.get(), T.getCloseLocation());
3525 /// objc-protocol-expression
3526 /// \@protocol ( protocol-name )
3528 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3529 SourceLocation ProtoLoc = ConsumeToken();
3531 if (Tok.isNot(tok::l_paren))
3532 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3534 BalancedDelimiterTracker T(*this, tok::l_paren);
3537 if (expectIdentifier())
3540 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3541 SourceLocation ProtoIdLoc = ConsumeToken();
3545 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3546 T.getOpenLocation(), ProtoIdLoc,
3547 T.getCloseLocation());
3550 /// objc-selector-expression
3551 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3552 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3553 SourceLocation SelectorLoc = ConsumeToken();
3555 if (Tok.isNot(tok::l_paren))
3556 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3558 SmallVector<IdentifierInfo *, 12> KeyIdents;
3559 SourceLocation sLoc;
3561 BalancedDelimiterTracker T(*this, tok::l_paren);
3563 bool HasOptionalParen = Tok.is(tok::l_paren);
3564 if (HasOptionalParen)
3567 if (Tok.is(tok::code_completion)) {
3568 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3573 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3574 if (!SelIdent && // missing selector name.
3575 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3576 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3578 KeyIdents.push_back(SelIdent);
3580 unsigned nColons = 0;
3581 if (Tok.isNot(tok::r_paren)) {
3583 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3585 KeyIdents.push_back(nullptr);
3586 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3590 if (Tok.is(tok::r_paren))
3593 if (Tok.is(tok::code_completion)) {
3594 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3599 // Check for another keyword selector.
3601 SelIdent = ParseObjCSelectorPiece(Loc);
3602 KeyIdents.push_back(SelIdent);
3603 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3607 if (HasOptionalParen && Tok.is(tok::r_paren))
3608 ConsumeParen(); // ')'
3610 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3611 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3612 T.getOpenLocation(),
3613 T.getCloseLocation(),
3617 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3618 // MCDecl might be null due to error in method or c-function prototype, etc.
3619 Decl *MCDecl = LM.D;
3620 bool skip = MCDecl &&
3621 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3622 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3626 // Save the current token position.
3627 SourceLocation OrigLoc = Tok.getLocation();
3629 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3630 // Append the current token at the end of the new token stream so that it
3631 // doesn't get lost.
3632 LM.Toks.push_back(Tok);
3633 PP.EnterTokenStream(LM.Toks, true);
3635 // Consume the previously pushed token.
3636 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3638 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3639 "Inline objective-c method not starting with '{' or 'try' or ':'");
3640 // Enter a scope for the method or c-function body.
3641 ParseScope BodyScope(this,
3643 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
3644 : Scope::FnScope|Scope::DeclScope);
3646 // Tell the actions module that we have entered a method or c-function definition
3647 // with the specified Declarator for the method/function.
3649 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3651 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3652 if (Tok.is(tok::kw_try))
3653 ParseFunctionTryBlock(MCDecl, BodyScope);
3655 if (Tok.is(tok::colon))
3656 ParseConstructorInitializer(MCDecl);
3658 Actions.ActOnDefaultCtorInitializers(MCDecl);
3659 ParseFunctionStatementBody(MCDecl, BodyScope);
3662 if (Tok.getLocation() != OrigLoc) {
3663 // Due to parsing error, we either went over the cached tokens or
3664 // there are still cached tokens left. If it's the latter case skip the
3666 // Since this is an uncommon situation that should be avoided, use the
3667 // expensive isBeforeInTranslationUnit call.
3668 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3670 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))