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()) {
1011 // Empty selector piece uses the location of the ':'.
1012 SelectorLoc = Tok.getLocation();
1020 case tok::exclaimequal:
1022 case tok::pipeequal:
1024 case tok::caretequal: {
1025 std::string ThisTok(PP.getSpelling(Tok));
1026 if (isLetter(ThisTok[0])) {
1027 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1028 Tok.setKind(tok::identifier);
1029 SelectorLoc = ConsumeToken();
1035 case tok::identifier:
1045 case tok::kw_const_cast:
1046 case tok::kw_continue:
1047 case tok::kw_default:
1048 case tok::kw_delete:
1050 case tok::kw_double:
1051 case tok::kw_dynamic_cast:
1054 case tok::kw_explicit:
1055 case tok::kw_export:
1056 case tok::kw_extern:
1060 case tok::kw_friend:
1063 case tok::kw_inline:
1066 case tok::kw_mutable:
1067 case tok::kw_namespace:
1069 case tok::kw_operator:
1070 case tok::kw_private:
1071 case tok::kw_protected:
1072 case tok::kw_public:
1073 case tok::kw_register:
1074 case tok::kw_reinterpret_cast:
1075 case tok::kw_restrict:
1076 case tok::kw_return:
1078 case tok::kw_signed:
1079 case tok::kw_sizeof:
1080 case tok::kw_static:
1081 case tok::kw_static_cast:
1082 case tok::kw_struct:
1083 case tok::kw_switch:
1084 case tok::kw_template:
1089 case tok::kw_typedef:
1090 case tok::kw_typeid:
1091 case tok::kw_typename:
1092 case tok::kw_typeof:
1094 case tok::kw_unsigned:
1096 case tok::kw_virtual:
1098 case tok::kw_volatile:
1099 case tok::kw_wchar_t:
1102 case tok::kw__Complex:
1103 case tok::kw___alignof:
1104 case tok::kw___auto_type:
1105 IdentifierInfo *II = Tok.getIdentifierInfo();
1106 SelectorLoc = ConsumeToken();
1111 /// objc-for-collection-in: 'in'
1113 bool Parser::isTokIdentifier_in() const {
1114 // FIXME: May have to do additional look-ahead to only allow for
1115 // valid tokens following an 'in'; such as an identifier, unary operators,
1117 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
1118 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1121 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1122 /// qualifier list and builds their bitmask representation in the input
1125 /// objc-type-qualifiers:
1126 /// objc-type-qualifier
1127 /// objc-type-qualifiers objc-type-qualifier
1129 /// objc-type-qualifier:
1138 /// 'null_unspecified'
1140 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1141 Declarator::TheContext Context) {
1142 assert(Context == Declarator::ObjCParameterContext ||
1143 Context == Declarator::ObjCResultContext);
1146 if (Tok.is(tok::code_completion)) {
1147 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
1148 Context == Declarator::ObjCParameterContext);
1149 return cutOffParsing();
1152 if (Tok.isNot(tok::identifier))
1155 const IdentifierInfo *II = Tok.getIdentifierInfo();
1156 for (unsigned i = 0; i != objc_NumQuals; ++i) {
1157 if (II != ObjCTypeQuals[i] ||
1158 NextToken().is(tok::less) ||
1159 NextToken().is(tok::coloncolon))
1162 ObjCDeclSpec::ObjCDeclQualifier Qual;
1163 NullabilityKind Nullability;
1165 default: llvm_unreachable("Unknown decl qualifier");
1166 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
1167 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
1168 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
1169 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1170 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1171 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
1174 Qual = ObjCDeclSpec::DQ_CSNullability;
1175 Nullability = NullabilityKind::NonNull;
1179 Qual = ObjCDeclSpec::DQ_CSNullability;
1180 Nullability = NullabilityKind::Nullable;
1183 case objc_null_unspecified:
1184 Qual = ObjCDeclSpec::DQ_CSNullability;
1185 Nullability = NullabilityKind::Unspecified;
1189 // FIXME: Diagnose redundant specifiers.
1190 DS.setObjCDeclQualifier(Qual);
1191 if (Qual == ObjCDeclSpec::DQ_CSNullability)
1192 DS.setNullability(Tok.getLocation(), Nullability);
1199 // If this wasn't a recognized qualifier, bail out.
1204 /// Take all the decl attributes out of the given list and add
1205 /// them to the given attribute set.
1206 static void takeDeclAttributes(ParsedAttributes &attrs,
1207 AttributeList *list) {
1209 AttributeList *cur = list;
1210 list = cur->getNext();
1212 if (!cur->isUsedAsTypeAttr()) {
1213 // Clear out the next pointer. We're really completely
1214 // destroying the internal invariants of the declarator here,
1215 // but it doesn't matter because we're done with it.
1216 cur->setNext(nullptr);
1222 /// takeDeclAttributes - Take all the decl attributes from the given
1223 /// declarator and add them to the given list.
1224 static void takeDeclAttributes(ParsedAttributes &attrs,
1226 // First, take ownership of all attributes.
1227 attrs.getPool().takeAllFrom(D.getAttributePool());
1228 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1230 // Now actually move the attributes over.
1231 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
1232 takeDeclAttributes(attrs, D.getAttributes());
1233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1234 takeDeclAttributes(attrs,
1235 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
1239 /// '(' objc-type-qualifiers[opt] type-name ')'
1240 /// '(' objc-type-qualifiers[opt] ')'
1242 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1243 Declarator::TheContext context,
1244 ParsedAttributes *paramAttrs) {
1245 assert(context == Declarator::ObjCParameterContext ||
1246 context == Declarator::ObjCResultContext);
1247 assert((paramAttrs != nullptr) ==
1248 (context == Declarator::ObjCParameterContext));
1250 assert(Tok.is(tok::l_paren) && "expected (");
1252 BalancedDelimiterTracker T(*this, tok::l_paren);
1255 SourceLocation TypeStartLoc = Tok.getLocation();
1256 ObjCDeclContextSwitch ObjCDC(*this);
1258 // Parse type qualifiers, in, inout, etc.
1259 ParseObjCTypeQualifierList(DS, context);
1262 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1263 // Parse an abstract declarator.
1264 DeclSpec declSpec(AttrFactory);
1265 declSpec.setObjCQualifiers(&DS);
1266 DeclSpecContext dsContext = DSC_normal;
1267 if (context == Declarator::ObjCResultContext)
1268 dsContext = DSC_objc_method_result;
1269 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1270 Declarator declarator(declSpec, context);
1271 ParseDeclarator(declarator);
1273 // If that's not invalid, extract a type.
1274 if (!declarator.isInvalidType()) {
1275 // Map a nullability specifier to a context-sensitive keyword attribute.
1276 bool addedToDeclSpec = false;
1277 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1278 addContextSensitiveTypeNullability(*this, declarator,
1279 DS.getNullability(),
1280 DS.getNullabilityLoc(),
1283 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1284 if (!type.isInvalid())
1287 // If we're parsing a parameter, steal all the decl attributes
1288 // and add them to the decl spec.
1289 if (context == Declarator::ObjCParameterContext)
1290 takeDeclAttributes(*paramAttrs, declarator);
1294 if (Tok.is(tok::r_paren))
1296 else if (Tok.getLocation() == TypeStartLoc) {
1297 // If we didn't eat any tokens, then this isn't a type.
1298 Diag(Tok, diag::err_expected_type);
1299 SkipUntil(tok::r_paren, StopAtSemi);
1301 // Otherwise, we found *something*, but didn't get a ')' in the right
1302 // place. Emit an error then return what we have as the type.
1308 /// objc-method-decl:
1310 /// objc-keyword-selector objc-parmlist[opt]
1311 /// objc-type-name objc-selector
1312 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1314 /// objc-keyword-selector:
1315 /// objc-keyword-decl
1316 /// objc-keyword-selector objc-keyword-decl
1318 /// objc-keyword-decl:
1319 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1320 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1321 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1322 /// ':' objc-keyword-attributes[opt] identifier
1325 /// objc-parms objc-ellipsis[opt]
1328 /// objc-parms , parameter-declaration
1333 /// objc-keyword-attributes: [OBJC2]
1334 /// __attribute__((unused))
1336 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1337 tok::TokenKind mType,
1338 tok::ObjCKeywordKind MethodImplKind,
1339 bool MethodDefinition) {
1340 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1342 if (Tok.is(tok::code_completion)) {
1343 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1344 /*ReturnType=*/nullptr);
1349 // Parse the return type if present.
1350 ParsedType ReturnType;
1352 if (Tok.is(tok::l_paren))
1353 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext,
1356 // If attributes exist before the method, parse them.
1357 ParsedAttributes methodAttrs(AttrFactory);
1358 if (getLangOpts().ObjC2)
1359 MaybeParseGNUAttributes(methodAttrs);
1361 if (Tok.is(tok::code_completion)) {
1362 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1368 // Now parse the selector.
1369 SourceLocation selLoc;
1370 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1372 // An unnamed colon is valid.
1373 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1374 Diag(Tok, diag::err_expected_selector_for_method)
1375 << SourceRange(mLoc, Tok.getLocation());
1376 // Skip until we get a ; or @.
1377 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1381 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1382 if (Tok.isNot(tok::colon)) {
1383 // If attributes exist after the method, parse them.
1384 if (getLangOpts().ObjC2)
1385 MaybeParseGNUAttributes(methodAttrs);
1387 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1389 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1390 mType, DSRet, ReturnType,
1391 selLoc, Sel, nullptr,
1392 CParamInfo.data(), CParamInfo.size(),
1393 methodAttrs.getList(), MethodImplKind,
1394 false, MethodDefinition);
1395 PD.complete(Result);
1399 SmallVector<IdentifierInfo *, 12> KeyIdents;
1400 SmallVector<SourceLocation, 12> KeyLocs;
1401 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1402 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1403 Scope::FunctionDeclarationScope | Scope::DeclScope);
1405 AttributePool allParamAttrs(AttrFactory);
1407 ParsedAttributes paramAttrs(AttrFactory);
1408 Sema::ObjCArgInfo ArgInfo;
1410 // Each iteration parses a single keyword argument.
1411 if (ExpectAndConsume(tok::colon))
1414 ArgInfo.Type = nullptr;
1415 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1416 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1417 Declarator::ObjCParameterContext,
1420 // If attributes exist before the argument name, parse them.
1421 // Regardless, collect all the attributes we've parsed so far.
1422 ArgInfo.ArgAttrs = nullptr;
1423 if (getLangOpts().ObjC2) {
1424 MaybeParseGNUAttributes(paramAttrs);
1425 ArgInfo.ArgAttrs = paramAttrs.getList();
1428 // Code completion for the next piece of the selector.
1429 if (Tok.is(tok::code_completion)) {
1430 KeyIdents.push_back(SelIdent);
1431 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1432 mType == tok::minus,
1433 /*AtParameterName=*/true,
1434 ReturnType, KeyIdents);
1439 if (expectIdentifier())
1440 break; // missing argument name.
1442 ArgInfo.Name = Tok.getIdentifierInfo();
1443 ArgInfo.NameLoc = Tok.getLocation();
1444 ConsumeToken(); // Eat the identifier.
1446 ArgInfos.push_back(ArgInfo);
1447 KeyIdents.push_back(SelIdent);
1448 KeyLocs.push_back(selLoc);
1450 // Make sure the attributes persist.
1451 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1453 // Code completion for the next piece of the selector.
1454 if (Tok.is(tok::code_completion)) {
1455 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1456 mType == tok::minus,
1457 /*AtParameterName=*/false,
1458 ReturnType, KeyIdents);
1463 // Check for another keyword selector.
1464 SelIdent = ParseObjCSelectorPiece(selLoc);
1465 if (!SelIdent && Tok.isNot(tok::colon))
1468 SourceLocation ColonLoc = Tok.getLocation();
1469 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1470 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1471 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1472 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1475 // We have a selector or a colon, continue parsing.
1478 bool isVariadic = false;
1479 bool cStyleParamWarned = false;
1480 // Parse the (optional) parameter list.
1481 while (Tok.is(tok::comma)) {
1483 if (Tok.is(tok::ellipsis)) {
1488 if (!cStyleParamWarned) {
1489 Diag(Tok, diag::warn_cstyle_param);
1490 cStyleParamWarned = true;
1492 DeclSpec DS(AttrFactory);
1493 ParseDeclarationSpecifiers(DS);
1494 // Parse the declarator.
1495 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1496 ParseDeclarator(ParmDecl);
1497 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1498 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1499 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1500 ParmDecl.getIdentifierLoc(),
1505 // FIXME: Add support for optional parameter list...
1506 // If attributes exist after the method, parse them.
1507 if (getLangOpts().ObjC2)
1508 MaybeParseGNUAttributes(methodAttrs);
1510 if (KeyIdents.size() == 0)
1513 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1516 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1517 mType, DSRet, ReturnType,
1518 KeyLocs, Sel, &ArgInfos[0],
1519 CParamInfo.data(), CParamInfo.size(),
1520 methodAttrs.getList(),
1521 MethodImplKind, isVariadic, MethodDefinition);
1523 PD.complete(Result);
1527 /// objc-protocol-refs:
1528 /// '<' identifier-list '>'
1531 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1532 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1533 bool WarnOnDeclarations, bool ForObjCContainer,
1534 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1535 bool consumeLastToken) {
1536 assert(Tok.is(tok::less) && "expected <");
1538 LAngleLoc = ConsumeToken(); // the "<"
1540 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1543 if (Tok.is(tok::code_completion)) {
1544 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1549 if (expectIdentifier()) {
1550 SkipUntil(tok::greater, StopAtSemi);
1553 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1554 Tok.getLocation()));
1555 ProtocolLocs.push_back(Tok.getLocation());
1558 if (!TryConsumeToken(tok::comma))
1563 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1564 /*ObjCGenericList=*/false))
1567 // Convert the list of protocols identifiers into a list of protocol decls.
1568 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1569 ProtocolIdents, Protocols);
1573 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1574 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1575 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1577 SourceLocation lAngleLoc;
1578 SmallVector<Decl *, 8> protocols;
1579 SmallVector<SourceLocation, 8> protocolLocs;
1580 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1581 lAngleLoc, rAngleLoc,
1582 /*consumeLastToken=*/true);
1583 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1587 if (result.isUsable()) {
1588 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1589 << FixItHint::CreateInsertion(lAngleLoc, "id")
1590 << SourceRange(lAngleLoc, rAngleLoc);
1596 /// Parse Objective-C type arguments or protocol qualifiers.
1598 /// objc-type-arguments:
1599 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1601 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1602 ParsedType baseType,
1603 SourceLocation &typeArgsLAngleLoc,
1604 SmallVectorImpl<ParsedType> &typeArgs,
1605 SourceLocation &typeArgsRAngleLoc,
1606 SourceLocation &protocolLAngleLoc,
1607 SmallVectorImpl<Decl *> &protocols,
1608 SmallVectorImpl<SourceLocation> &protocolLocs,
1609 SourceLocation &protocolRAngleLoc,
1610 bool consumeLastToken,
1611 bool warnOnIncompleteProtocols) {
1612 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1613 SourceLocation lAngleLoc = ConsumeToken();
1615 // Whether all of the elements we've parsed thus far are single
1616 // identifiers, which might be types or might be protocols.
1617 bool allSingleIdentifiers = true;
1618 SmallVector<IdentifierInfo *, 4> identifiers;
1619 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1621 // Parse a list of comma-separated identifiers, bailing out if we
1622 // see something different.
1624 // Parse a single identifier.
1625 if (Tok.is(tok::identifier) &&
1626 (NextToken().is(tok::comma) ||
1627 NextToken().is(tok::greater) ||
1628 NextToken().is(tok::greatergreater))) {
1629 identifiers.push_back(Tok.getIdentifierInfo());
1630 identifierLocs.push_back(ConsumeToken());
1634 if (Tok.is(tok::code_completion)) {
1635 // FIXME: Also include types here.
1636 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1637 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1638 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1639 identifierLocs[i]));
1642 QualType BaseT = Actions.GetTypeFromParser(baseType);
1643 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1644 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1646 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1652 allSingleIdentifiers = false;
1654 } while (TryConsumeToken(tok::comma));
1656 // If we parsed an identifier list, semantic analysis sorts out
1657 // whether it refers to protocols or to type arguments.
1658 if (allSingleIdentifiers) {
1659 // Parse the closing '>'.
1660 SourceLocation rAngleLoc;
1661 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1662 /*ObjCGenericList=*/true);
1664 // Let Sema figure out what we parsed.
1665 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1677 warnOnIncompleteProtocols);
1681 // We parsed an identifier list but stumbled into non single identifiers, this
1682 // means we might (a) check that what we already parsed is a legitimate type
1683 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1684 // must all be type args.
1686 // Convert the identifiers into type arguments.
1687 bool invalid = false;
1688 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1689 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1690 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1691 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1693 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1695 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1697 DeclSpec DS(AttrFactory);
1698 const char *prevSpec = nullptr;
1700 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1701 typeArg, Actions.getASTContext().getPrintingPolicy());
1703 // Form a declarator to turn this into a type.
1704 Declarator D(DS, Declarator::TypeNameContext);
1705 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1706 if (fullTypeArg.isUsable()) {
1707 typeArgs.push_back(fullTypeArg.get());
1708 if (!foundValidTypeId) {
1709 foundValidTypeId = identifiers[i];
1710 foundValidTypeSrcLoc = identifierLocs[i];
1714 unknownTypeArgs.push_back(identifiers[i]);
1715 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1719 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1720 unknownTypeArgs.push_back(identifiers[i]);
1721 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1722 } else if (!foundProtocolId) {
1723 foundProtocolId = identifiers[i];
1724 foundProtocolSrcLoc = identifierLocs[i];
1729 // Continue parsing type-names.
1731 Token CurTypeTok = Tok;
1732 TypeResult typeArg = ParseTypeName();
1734 // Consume the '...' for a pack expansion.
1735 SourceLocation ellipsisLoc;
1736 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1737 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1738 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1741 if (typeArg.isUsable()) {
1742 typeArgs.push_back(typeArg.get());
1743 if (!foundValidTypeId) {
1744 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1745 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1750 } while (TryConsumeToken(tok::comma));
1752 // Diagnose the mix between type args and protocols.
1753 if (foundProtocolId && foundValidTypeId)
1754 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1756 foundValidTypeSrcLoc);
1758 // Diagnose unknown arg types.
1760 if (unknownTypeArgs.size())
1761 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1762 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1763 getCurScope(), nullptr, T);
1765 // Parse the closing '>'.
1766 SourceLocation rAngleLoc;
1767 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1768 /*ObjCGenericList=*/true);
1775 // Record left/right angle locations.
1776 typeArgsLAngleLoc = lAngleLoc;
1777 typeArgsRAngleLoc = rAngleLoc;
1780 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1781 ParsedType baseType,
1782 SourceLocation &typeArgsLAngleLoc,
1783 SmallVectorImpl<ParsedType> &typeArgs,
1784 SourceLocation &typeArgsRAngleLoc,
1785 SourceLocation &protocolLAngleLoc,
1786 SmallVectorImpl<Decl *> &protocols,
1787 SmallVectorImpl<SourceLocation> &protocolLocs,
1788 SourceLocation &protocolRAngleLoc,
1789 bool consumeLastToken) {
1790 assert(Tok.is(tok::less));
1792 // Parse the first angle-bracket-delimited clause.
1793 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1802 /*warnOnIncompleteProtocols=*/false);
1803 if (Tok.is(tok::eof)) // Nothing else to do here...
1806 // An Objective-C object pointer followed by type arguments
1807 // can then be followed again by a set of protocol references, e.g.,
1808 // \c NSArray<NSView><NSTextDelegate>
1809 if ((consumeLastToken && Tok.is(tok::less)) ||
1810 (!consumeLastToken && NextToken().is(tok::less))) {
1811 // If we aren't consuming the last token, the prior '>' is still hanging
1812 // there. Consume it before we parse the protocol qualifiers.
1813 if (!consumeLastToken)
1816 if (!protocols.empty()) {
1817 SkipUntilFlags skipFlags = SkipUntilFlags();
1818 if (!consumeLastToken)
1819 skipFlags = skipFlags | StopBeforeMatch;
1820 Diag(Tok, diag::err_objc_type_args_after_protocols)
1821 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1822 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1824 ParseObjCProtocolReferences(protocols, protocolLocs,
1825 /*WarnOnDeclarations=*/false,
1826 /*ForObjCContainer=*/false,
1827 protocolLAngleLoc, protocolRAngleLoc,
1833 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1836 bool consumeLastToken,
1837 SourceLocation &endLoc) {
1838 assert(Tok.is(tok::less));
1839 SourceLocation typeArgsLAngleLoc;
1840 SmallVector<ParsedType, 4> typeArgs;
1841 SourceLocation typeArgsRAngleLoc;
1842 SourceLocation protocolLAngleLoc;
1843 SmallVector<Decl *, 4> protocols;
1844 SmallVector<SourceLocation, 4> protocolLocs;
1845 SourceLocation protocolRAngleLoc;
1847 // Parse type arguments and protocol qualifiers.
1848 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1849 typeArgsRAngleLoc, protocolLAngleLoc,
1850 protocols, protocolLocs,
1851 protocolRAngleLoc, consumeLastToken);
1853 if (Tok.is(tok::eof))
1854 return true; // Invalid type result.
1856 // Compute the location of the last token.
1857 if (consumeLastToken)
1858 endLoc = PrevTokLocation;
1860 endLoc = Tok.getLocation();
1862 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1875 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1876 BalancedDelimiterTracker &T,
1877 SmallVectorImpl<Decl *> &AllIvarDecls,
1878 bool RBraceMissing) {
1882 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1883 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1884 Actions.ActOnObjCContainerFinishDefinition();
1885 // Call ActOnFields() even if we don't have any decls. This is useful
1886 // for code rewriting tools that need to be aware of the empty list.
1887 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1889 T.getOpenLocation(), T.getCloseLocation(), nullptr);
1892 /// objc-class-instance-variables:
1893 /// '{' objc-instance-variable-decl-list[opt] '}'
1895 /// objc-instance-variable-decl-list:
1896 /// objc-visibility-spec
1897 /// objc-instance-variable-decl ';'
1899 /// objc-instance-variable-decl-list objc-visibility-spec
1900 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1901 /// objc-instance-variable-decl-list ';'
1903 /// objc-visibility-spec:
1907 /// @package [OBJC2]
1909 /// objc-instance-variable-decl:
1910 /// struct-declaration
1912 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1913 tok::ObjCKeywordKind visibility,
1914 SourceLocation atLoc) {
1915 assert(Tok.is(tok::l_brace) && "expected {");
1916 SmallVector<Decl *, 32> AllIvarDecls;
1918 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1919 ObjCDeclContextSwitch ObjCDC(*this);
1921 BalancedDelimiterTracker T(*this, tok::l_brace);
1923 // While we still have something to read, read the instance variables.
1924 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1925 // Each iteration of this loop reads one objc-instance-variable-decl.
1927 // Check for extraneous top-level semicolon.
1928 if (Tok.is(tok::semi)) {
1929 ConsumeExtraSemi(InstanceVariableList);
1933 // Set the default visibility to private.
1934 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1935 if (Tok.is(tok::code_completion)) {
1936 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1937 return cutOffParsing();
1940 switch (Tok.getObjCKeywordID()) {
1941 case tok::objc_private:
1942 case tok::objc_public:
1943 case tok::objc_protected:
1944 case tok::objc_package:
1945 visibility = Tok.getObjCKeywordID();
1950 Diag(Tok, diag::err_objc_unexpected_atend);
1951 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1952 Tok.setKind(tok::at);
1955 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1956 T, AllIvarDecls, true);
1960 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1965 if (Tok.is(tok::code_completion)) {
1966 Actions.CodeCompleteOrdinaryName(getCurScope(),
1967 Sema::PCC_ObjCInstanceVariableList);
1968 return cutOffParsing();
1971 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1972 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1973 // Install the declarator into the interface decl.
1974 FD.D.setObjCIvar(true);
1975 Decl *Field = Actions.ActOnIvar(
1976 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1977 FD.BitfieldSize, visibility);
1978 Actions.ActOnObjCContainerFinishDefinition();
1980 AllIvarDecls.push_back(Field);
1984 // Parse all the comma separated declarators.
1985 ParsingDeclSpec DS(*this);
1986 ParseStructDeclaration(DS, ObjCIvarCallback);
1988 if (Tok.is(tok::semi)) {
1991 Diag(Tok, diag::err_expected_semi_decl_list);
1992 // Skip to end of block or statement
1993 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1996 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1997 T, AllIvarDecls, false);
2000 /// objc-protocol-declaration:
2001 /// objc-protocol-definition
2002 /// objc-protocol-forward-reference
2004 /// objc-protocol-definition:
2005 /// \@protocol identifier
2006 /// objc-protocol-refs[opt]
2007 /// objc-interface-decl-list
2010 /// objc-protocol-forward-reference:
2011 /// \@protocol identifier-list ';'
2013 /// "\@protocol identifier ;" should be resolved as "\@protocol
2014 /// identifier-list ;": objc-interface-decl-list may not start with a
2015 /// semicolon in the first alternative if objc-protocol-refs are omitted.
2016 Parser::DeclGroupPtrTy
2017 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2018 ParsedAttributes &attrs) {
2019 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2020 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2021 ConsumeToken(); // the "protocol" identifier
2023 if (Tok.is(tok::code_completion)) {
2024 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2029 MaybeSkipAttributes(tok::objc_protocol);
2031 if (expectIdentifier())
2032 return nullptr; // missing protocol name.
2033 // Save the protocol name, then consume it.
2034 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2035 SourceLocation nameLoc = ConsumeToken();
2037 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2038 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2039 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo,
2043 CheckNestedObjCContexts(AtLoc);
2045 if (Tok.is(tok::comma)) { // list of forward declarations.
2046 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2047 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2049 // Parse the list of forward declarations.
2051 ConsumeToken(); // the ','
2052 if (expectIdentifier()) {
2053 SkipUntil(tok::semi);
2056 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2057 Tok.getLocation()));
2058 ConsumeToken(); // the identifier
2060 if (Tok.isNot(tok::comma))
2064 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2067 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs,
2071 // Last, and definitely not least, parse a protocol declaration.
2072 SourceLocation LAngleLoc, EndProtoLoc;
2074 SmallVector<Decl *, 8> ProtocolRefs;
2075 SmallVector<SourceLocation, 8> ProtocolLocs;
2076 if (Tok.is(tok::less) &&
2077 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2078 LAngleLoc, EndProtoLoc,
2079 /*consumeLastToken=*/true))
2083 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
2084 ProtocolRefs.data(),
2085 ProtocolRefs.size(),
2086 ProtocolLocs.data(),
2087 EndProtoLoc, attrs.getList());
2089 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2090 return Actions.ConvertDeclToDeclGroup(ProtoType);
2093 /// objc-implementation:
2094 /// objc-class-implementation-prologue
2095 /// objc-category-implementation-prologue
2097 /// objc-class-implementation-prologue:
2098 /// @implementation identifier objc-superclass[opt]
2099 /// objc-class-instance-variables[opt]
2101 /// objc-category-implementation-prologue:
2102 /// @implementation identifier ( identifier )
2103 Parser::DeclGroupPtrTy
2104 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
2105 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2106 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2107 CheckNestedObjCContexts(AtLoc);
2108 ConsumeToken(); // the "implementation" identifier
2110 // Code completion after '@implementation'.
2111 if (Tok.is(tok::code_completion)) {
2112 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2117 MaybeSkipAttributes(tok::objc_implementation);
2119 if (expectIdentifier())
2120 return nullptr; // missing class or category name.
2121 // We have a class or category name - consume it.
2122 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2123 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2124 Decl *ObjCImpDecl = nullptr;
2126 // Neither a type parameter list nor a list of protocol references is
2127 // permitted here. Parse and diagnose them.
2128 if (Tok.is(tok::less)) {
2129 SourceLocation lAngleLoc, rAngleLoc;
2130 SmallVector<IdentifierLocPair, 8> protocolIdents;
2131 SourceLocation diagLoc = Tok.getLocation();
2132 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2133 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2134 protocolIdents, rAngleLoc)) {
2135 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2136 << SourceRange(diagLoc, PrevTokLocation);
2137 } else if (lAngleLoc.isValid()) {
2138 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2139 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2143 if (Tok.is(tok::l_paren)) {
2144 // we have a category implementation.
2146 SourceLocation categoryLoc, rparenLoc;
2147 IdentifierInfo *categoryId = nullptr;
2149 if (Tok.is(tok::code_completion)) {
2150 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2155 if (Tok.is(tok::identifier)) {
2156 categoryId = Tok.getIdentifierInfo();
2157 categoryLoc = ConsumeToken();
2159 Diag(Tok, diag::err_expected)
2160 << tok::identifier; // missing category name.
2163 if (Tok.isNot(tok::r_paren)) {
2164 Diag(Tok, diag::err_expected) << tok::r_paren;
2165 SkipUntil(tok::r_paren); // don't stop at ';'
2168 rparenLoc = ConsumeParen();
2169 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2170 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2171 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2172 SmallVector<Decl *, 4> protocols;
2173 SmallVector<SourceLocation, 4> protocolLocs;
2174 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2175 /*warnOnIncompleteProtocols=*/false,
2176 /*ForObjCContainer=*/false,
2177 protocolLAngleLoc, protocolRAngleLoc,
2178 /*consumeLastToken=*/true);
2180 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2181 AtLoc, nameId, nameLoc, categoryId,
2185 // We have a class implementation
2186 SourceLocation superClassLoc;
2187 IdentifierInfo *superClassId = nullptr;
2188 if (TryConsumeToken(tok::colon)) {
2189 // We have a super class
2190 if (expectIdentifier())
2191 return nullptr; // missing super class name.
2192 superClassId = Tok.getIdentifierInfo();
2193 superClassLoc = ConsumeToken(); // Consume super class name
2195 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2196 AtLoc, nameId, nameLoc,
2197 superClassId, superClassLoc);
2199 if (Tok.is(tok::l_brace)) // we have ivars
2200 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2201 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2202 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2204 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2205 SmallVector<Decl *, 4> protocols;
2206 SmallVector<SourceLocation, 4> protocolLocs;
2207 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2208 /*warnOnIncompleteProtocols=*/false,
2209 /*ForObjCContainer=*/false,
2210 protocolLAngleLoc, protocolRAngleLoc,
2211 /*consumeLastToken=*/true);
2214 assert(ObjCImpDecl);
2216 SmallVector<Decl *, 8> DeclsInGroup;
2219 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2220 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2221 ParsedAttributesWithRange attrs(AttrFactory);
2222 MaybeParseCXX11Attributes(attrs);
2223 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2224 DeclGroupRef DG = DGP.get();
2225 DeclsInGroup.append(DG.begin(), DG.end());
2230 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2233 Parser::DeclGroupPtrTy
2234 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2235 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2236 "ParseObjCAtEndDeclaration(): Expected @end");
2237 ConsumeToken(); // the "end" identifier
2238 if (CurParsedObjCImpl)
2239 CurParsedObjCImpl->finish(atEnd);
2241 // missing @implementation
2242 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2246 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2248 finish(P.Tok.getLocation());
2249 if (P.isEofOrEom()) {
2250 P.Diag(P.Tok, diag::err_objc_missing_end)
2251 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2252 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
2253 << Sema::OCK_Implementation;
2256 P.CurParsedObjCImpl = nullptr;
2257 assert(LateParsedObjCMethods.empty());
2260 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2262 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2263 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2264 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2267 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2270 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2271 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2272 false/*c-functions*/);
2274 /// \brief Clear and free the cached objc methods.
2275 for (LateParsedObjCMethodContainer::iterator
2276 I = LateParsedObjCMethods.begin(),
2277 E = LateParsedObjCMethods.end(); I != E; ++I)
2279 LateParsedObjCMethods.clear();
2284 /// compatibility-alias-decl:
2285 /// @compatibility_alias alias-name class-name ';'
2287 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2288 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2289 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2290 ConsumeToken(); // consume compatibility_alias
2291 if (expectIdentifier())
2293 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2294 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2295 if (expectIdentifier())
2297 IdentifierInfo *classId = Tok.getIdentifierInfo();
2298 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2299 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2300 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2304 /// property-synthesis:
2305 /// @synthesize property-ivar-list ';'
2307 /// property-ivar-list:
2309 /// property-ivar-list ',' property-ivar
2313 /// identifier '=' identifier
2315 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2316 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2317 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2318 ConsumeToken(); // consume synthesize
2321 if (Tok.is(tok::code_completion)) {
2322 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2327 if (Tok.isNot(tok::identifier)) {
2328 Diag(Tok, diag::err_synthesized_property_name);
2329 SkipUntil(tok::semi);
2333 IdentifierInfo *propertyIvar = nullptr;
2334 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2335 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2336 SourceLocation propertyIvarLoc;
2337 if (TryConsumeToken(tok::equal)) {
2338 // property '=' ivar-name
2339 if (Tok.is(tok::code_completion)) {
2340 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2345 if (expectIdentifier())
2347 propertyIvar = Tok.getIdentifierInfo();
2348 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2350 Actions.ActOnPropertyImplDecl(
2351 getCurScope(), atLoc, propertyLoc, true,
2352 propertyId, propertyIvar, propertyIvarLoc,
2353 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2354 if (Tok.isNot(tok::comma))
2356 ConsumeToken(); // consume ','
2358 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2362 /// property-dynamic:
2363 /// @dynamic property-list
2367 /// property-list ',' identifier
2369 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2370 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2371 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2372 ConsumeToken(); // consume dynamic
2374 bool isClassProperty = false;
2375 if (Tok.is(tok::l_paren)) {
2377 const IdentifierInfo *II = Tok.getIdentifierInfo();
2380 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2381 SkipUntil(tok::r_paren, StopAtSemi);
2383 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2384 if (II->isStr("class")) {
2385 isClassProperty = true;
2386 if (Tok.isNot(tok::r_paren)) {
2387 Diag(Tok, diag::err_expected) << tok::r_paren;
2388 SkipUntil(tok::r_paren, StopAtSemi);
2392 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2393 SkipUntil(tok::r_paren, StopAtSemi);
2399 if (Tok.is(tok::code_completion)) {
2400 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2405 if (expectIdentifier()) {
2406 SkipUntil(tok::semi);
2410 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2411 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2412 Actions.ActOnPropertyImplDecl(
2413 getCurScope(), atLoc, propertyLoc, false,
2414 propertyId, nullptr, SourceLocation(),
2415 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2416 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2418 if (Tok.isNot(tok::comma))
2420 ConsumeToken(); // consume ','
2422 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2426 /// objc-throw-statement:
2427 /// throw expression[opt];
2429 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2431 ConsumeToken(); // consume throw
2432 if (Tok.isNot(tok::semi)) {
2433 Res = ParseExpression();
2434 if (Res.isInvalid()) {
2435 SkipUntil(tok::semi);
2440 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2441 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2444 /// objc-synchronized-statement:
2445 /// @synchronized '(' expression ')' compound-statement
2448 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2449 ConsumeToken(); // consume synchronized
2450 if (Tok.isNot(tok::l_paren)) {
2451 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2455 // The operand is surrounded with parentheses.
2456 ConsumeParen(); // '('
2457 ExprResult operand(ParseExpression());
2459 if (Tok.is(tok::r_paren)) {
2460 ConsumeParen(); // ')'
2462 if (!operand.isInvalid())
2463 Diag(Tok, diag::err_expected) << tok::r_paren;
2465 // Skip forward until we see a left brace, but don't consume it.
2466 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2469 // Require a compound statement.
2470 if (Tok.isNot(tok::l_brace)) {
2471 if (!operand.isInvalid())
2472 Diag(Tok, diag::err_expected) << tok::l_brace;
2476 // Check the @synchronized operand now.
2477 if (!operand.isInvalid())
2478 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2480 // Parse the compound statement within a new scope.
2481 ParseScope bodyScope(this, Scope::DeclScope);
2482 StmtResult body(ParseCompoundStatementBody());
2485 // If there was a semantic or parse error earlier with the
2486 // operand, fail now.
2487 if (operand.isInvalid())
2490 if (body.isInvalid())
2491 body = Actions.ActOnNullStmt(Tok.getLocation());
2493 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2496 /// objc-try-catch-statement:
2497 /// @try compound-statement objc-catch-list[opt]
2498 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2500 /// objc-catch-list:
2501 /// @catch ( parameter-declaration ) compound-statement
2502 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2503 /// catch-parameter-declaration:
2504 /// parameter-declaration
2507 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2508 bool catch_or_finally_seen = false;
2510 ConsumeToken(); // consume try
2511 if (Tok.isNot(tok::l_brace)) {
2512 Diag(Tok, diag::err_expected) << tok::l_brace;
2515 StmtVector CatchStmts;
2516 StmtResult FinallyStmt;
2517 ParseScope TryScope(this, Scope::DeclScope);
2518 StmtResult TryBody(ParseCompoundStatementBody());
2520 if (TryBody.isInvalid())
2521 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2523 while (Tok.is(tok::at)) {
2524 // At this point, we need to lookahead to determine if this @ is the start
2525 // of an @catch or @finally. We don't want to consume the @ token if this
2526 // is an @try or @encode or something else.
2527 Token AfterAt = GetLookAheadToken(1);
2528 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2529 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2532 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2533 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2534 Decl *FirstPart = nullptr;
2535 ConsumeToken(); // consume catch
2536 if (Tok.is(tok::l_paren)) {
2538 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
2539 if (Tok.isNot(tok::ellipsis)) {
2540 DeclSpec DS(AttrFactory);
2541 ParseDeclarationSpecifiers(DS);
2542 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
2543 ParseDeclarator(ParmDecl);
2545 // Inform the actions module about the declarator, so it
2546 // gets added to the current scope.
2547 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2549 ConsumeToken(); // consume '...'
2551 SourceLocation RParenLoc;
2553 if (Tok.is(tok::r_paren))
2554 RParenLoc = ConsumeParen();
2555 else // Skip over garbage, until we get to ')'. Eat the ')'.
2556 SkipUntil(tok::r_paren, StopAtSemi);
2558 StmtResult CatchBody(true);
2559 if (Tok.is(tok::l_brace))
2560 CatchBody = ParseCompoundStatementBody();
2562 Diag(Tok, diag::err_expected) << tok::l_brace;
2563 if (CatchBody.isInvalid())
2564 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2566 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2570 if (!Catch.isInvalid())
2571 CatchStmts.push_back(Catch.get());
2574 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2578 catch_or_finally_seen = true;
2580 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2581 ConsumeToken(); // consume finally
2582 ParseScope FinallyScope(this, Scope::DeclScope);
2584 StmtResult FinallyBody(true);
2585 if (Tok.is(tok::l_brace))
2586 FinallyBody = ParseCompoundStatementBody();
2588 Diag(Tok, diag::err_expected) << tok::l_brace;
2589 if (FinallyBody.isInvalid())
2590 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2591 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2593 catch_or_finally_seen = true;
2597 if (!catch_or_finally_seen) {
2598 Diag(atLoc, diag::err_missing_catch_finally);
2602 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2607 /// objc-autoreleasepool-statement:
2608 /// @autoreleasepool compound-statement
2611 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2612 ConsumeToken(); // consume autoreleasepool
2613 if (Tok.isNot(tok::l_brace)) {
2614 Diag(Tok, diag::err_expected) << tok::l_brace;
2617 // Enter a scope to hold everything within the compound stmt. Compound
2618 // statements can always hold declarations.
2619 ParseScope BodyScope(this, Scope::DeclScope);
2621 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2624 if (AutoreleasePoolBody.isInvalid())
2625 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2626 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2627 AutoreleasePoolBody.get());
2630 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2631 /// for later parsing.
2632 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2633 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2634 trySkippingFunctionBody()) {
2635 Actions.ActOnSkippedFunctionBody(MDecl);
2639 LexedMethod* LM = new LexedMethod(this, MDecl);
2640 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2641 CachedTokens &Toks = LM->Toks;
2642 // Begin by storing the '{' or 'try' or ':' token.
2643 Toks.push_back(Tok);
2644 if (Tok.is(tok::kw_try)) {
2646 if (Tok.is(tok::colon)) {
2647 Toks.push_back(Tok);
2649 while (Tok.isNot(tok::l_brace)) {
2650 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2651 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2654 Toks.push_back(Tok); // also store '{'
2656 else if (Tok.is(tok::colon)) {
2658 // FIXME: This is wrong, due to C++11 braced initialization.
2659 while (Tok.isNot(tok::l_brace)) {
2660 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2661 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2663 Toks.push_back(Tok); // also store '{'
2666 // Consume everything up to (and including) the matching right brace.
2667 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2668 while (Tok.is(tok::kw_catch)) {
2669 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2670 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2674 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2676 Decl *Parser::ParseObjCMethodDefinition() {
2677 Decl *MDecl = ParseObjCMethodPrototype();
2679 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2680 "parsing Objective-C method");
2682 // parse optional ';'
2683 if (Tok.is(tok::semi)) {
2684 if (CurParsedObjCImpl) {
2685 Diag(Tok, diag::warn_semicolon_before_method_body)
2686 << FixItHint::CreateRemoval(Tok.getLocation());
2691 // We should have an opening brace now.
2692 if (Tok.isNot(tok::l_brace)) {
2693 Diag(Tok, diag::err_expected_method_body);
2695 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2696 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2698 // If we didn't find the '{', bail out.
2699 if (Tok.isNot(tok::l_brace))
2705 SkipUntil(tok::r_brace);
2709 // Allow the rest of sema to find private method decl implementations.
2710 Actions.AddAnyMethodToGlobalPool(MDecl);
2711 assert (CurParsedObjCImpl
2712 && "ParseObjCMethodDefinition - Method out of @implementation");
2713 // Consume the tokens and store them for later parsing.
2714 StashAwayMethodOrFunctionBodyTokens(MDecl);
2718 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2719 if (Tok.is(tok::code_completion)) {
2720 Actions.CodeCompleteObjCAtStatement(getCurScope());
2725 if (Tok.isObjCAtKeyword(tok::objc_try))
2726 return ParseObjCTryStmt(AtLoc);
2728 if (Tok.isObjCAtKeyword(tok::objc_throw))
2729 return ParseObjCThrowStmt(AtLoc);
2731 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2732 return ParseObjCSynchronizedStmt(AtLoc);
2734 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2735 return ParseObjCAutoreleasePoolStmt(AtLoc);
2737 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2738 getLangOpts().DebuggerSupport) {
2739 SkipUntil(tok::semi);
2740 return Actions.ActOnNullStmt(Tok.getLocation());
2743 ExprStatementTokLoc = AtLoc;
2744 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2745 if (Res.isInvalid()) {
2746 // If the expression is invalid, skip ahead to the next semicolon. Not
2747 // doing this opens us up to the possibility of infinite loops if
2748 // ParseExpression does not consume any tokens.
2749 SkipUntil(tok::semi);
2753 // Otherwise, eat the semicolon.
2754 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2755 return Actions.ActOnExprStmt(Res);
2758 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2759 switch (Tok.getKind()) {
2760 case tok::code_completion:
2761 Actions.CodeCompleteObjCAtExpression(getCurScope());
2767 tok::TokenKind Kind = Tok.getKind();
2768 SourceLocation OpLoc = ConsumeToken();
2770 if (!Tok.is(tok::numeric_constant)) {
2771 const char *Symbol = nullptr;
2773 case tok::minus: Symbol = "-"; break;
2774 case tok::plus: Symbol = "+"; break;
2775 default: llvm_unreachable("missing unary operator case");
2777 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2782 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2783 if (Lit.isInvalid()) {
2786 ConsumeToken(); // Consume the literal token.
2788 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2789 if (Lit.isInvalid())
2792 return ParsePostfixExpressionSuffix(
2793 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2796 case tok::string_literal: // primary-expression: string-literal
2797 case tok::wide_string_literal:
2798 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2800 case tok::char_constant:
2801 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2803 case tok::numeric_constant:
2804 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2806 case tok::kw_true: // Objective-C++, etc.
2807 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2808 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2809 case tok::kw_false: // Objective-C++, etc.
2810 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2811 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2814 // Objective-C array literal
2815 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2818 // Objective-C dictionary literal
2819 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2822 // Objective-C boxed expression
2823 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2826 if (Tok.getIdentifierInfo() == nullptr)
2827 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2829 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2830 case tok::objc_encode:
2831 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2832 case tok::objc_protocol:
2833 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2834 case tok::objc_selector:
2835 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2836 case tok::objc_available:
2837 return ParseAvailabilityCheckExpr(AtLoc);
2839 const char *str = nullptr;
2840 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2841 // that this is a proper statement where such directives could actually
2843 if (GetLookAheadToken(1).is(tok::l_brace) &&
2844 ExprStatementTokLoc == AtLoc) {
2845 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2848 : (ch == 'f' ? "finally"
2849 : (ch == 'a' ? "autoreleasepool" : nullptr));
2852 SourceLocation kwLoc = Tok.getLocation();
2853 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2854 FixItHint::CreateReplacement(kwLoc, str));
2857 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2863 /// \brief Parse the receiver of an Objective-C++ message send.
2865 /// This routine parses the receiver of a message send in
2866 /// Objective-C++ either as a type or as an expression. Note that this
2867 /// routine must not be called to parse a send to 'super', since it
2868 /// has no way to return such a result.
2870 /// \param IsExpr Whether the receiver was parsed as an expression.
2872 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2873 /// IsExpr is true), the parsed expression. If the receiver was parsed
2874 /// as a type (\c IsExpr is false), the parsed type.
2876 /// \returns True if an error occurred during parsing or semantic
2877 /// analysis, in which case the arguments do not have valid
2878 /// values. Otherwise, returns false for a successful parse.
2880 /// objc-receiver: [C++]
2881 /// 'super' [not parsed here]
2883 /// simple-type-specifier
2884 /// typename-specifier
2885 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2886 InMessageExpressionRAIIObject InMessage(*this, true);
2888 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2889 tok::annot_cxxscope))
2890 TryAnnotateTypeOrScopeToken();
2892 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2895 // Make sure any typos in the receiver are corrected or diagnosed, so that
2896 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2897 // only the things that are valid ObjC receivers?
2898 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2899 if (Receiver.isInvalid())
2903 TypeOrExpr = Receiver.get();
2908 // typename-specifier
2909 // simple-type-specifier
2910 // expression (that starts with one of the above)
2911 DeclSpec DS(AttrFactory);
2912 ParseCXXSimpleTypeSpecifier(DS);
2914 if (Tok.is(tok::l_paren)) {
2915 // If we see an opening parentheses at this point, we are
2916 // actually parsing an expression that starts with a
2917 // function-style cast, e.g.,
2919 // postfix-expression:
2920 // simple-type-specifier ( expression-list [opt] )
2921 // typename-specifier ( expression-list [opt] )
2923 // Parse the remainder of this case, then the (optional)
2924 // postfix-expression suffix, followed by the (optional)
2925 // right-hand side of the binary expression. We have an
2927 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2928 if (!Receiver.isInvalid())
2929 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2930 if (!Receiver.isInvalid())
2931 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2932 if (Receiver.isInvalid())
2936 TypeOrExpr = Receiver.get();
2940 // We have a class message. Turn the simple-type-specifier or
2941 // typename-specifier we parsed into a type and parse the
2942 // remainder of the class message.
2943 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2944 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2945 if (Type.isInvalid())
2949 TypeOrExpr = Type.get().getAsOpaquePtr();
2953 /// \brief Determine whether the parser is currently referring to a an
2954 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2956 /// This routine will only return true for a subset of valid message-send
2958 bool Parser::isSimpleObjCMessageExpression() {
2959 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2960 "Incorrect start for isSimpleObjCMessageExpression");
2961 return GetLookAheadToken(1).is(tok::identifier) &&
2962 GetLookAheadToken(2).is(tok::identifier);
2965 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2966 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2967 InMessageExpression)
2972 if (Tok.is(tok::annot_typename))
2973 Type = getTypeAnnotation(Tok);
2974 else if (Tok.is(tok::identifier))
2975 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2980 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2981 const Token &AfterNext = GetLookAheadToken(2);
2982 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2983 if (Tok.is(tok::identifier))
2984 TryAnnotateTypeOrScopeToken();
2986 return Tok.is(tok::annot_typename);
2993 /// objc-message-expr:
2994 /// '[' objc-receiver objc-message-args ']'
2996 /// objc-receiver: [C]
3002 ExprResult Parser::ParseObjCMessageExpression() {
3003 assert(Tok.is(tok::l_square) && "'[' expected");
3004 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3006 if (Tok.is(tok::code_completion)) {
3007 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3012 InMessageExpressionRAIIObject InMessage(*this, true);
3014 if (getLangOpts().CPlusPlus) {
3015 // We completely separate the C and C++ cases because C++ requires
3016 // more complicated (read: slower) parsing.
3018 // Handle send to super.
3019 // FIXME: This doesn't benefit from the same typo-correction we
3020 // get in Objective-C.
3021 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3022 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3023 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3026 // Parse the receiver, which is either a type or an expression.
3028 void *TypeOrExpr = nullptr;
3029 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3030 SkipUntil(tok::r_square, StopAtSemi);
3035 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3036 static_cast<Expr *>(TypeOrExpr));
3038 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3039 ParsedType::getFromOpaquePtr(TypeOrExpr),
3043 if (Tok.is(tok::identifier)) {
3044 IdentifierInfo *Name = Tok.getIdentifierInfo();
3045 SourceLocation NameLoc = Tok.getLocation();
3046 ParsedType ReceiverType;
3047 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3048 Name == Ident_super,
3049 NextToken().is(tok::period),
3051 case Sema::ObjCSuperMessage:
3052 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3055 case Sema::ObjCClassMessage:
3056 if (!ReceiverType) {
3057 SkipUntil(tok::r_square, StopAtSemi);
3061 ConsumeToken(); // the type name
3063 // Parse type arguments and protocol qualifiers.
3064 if (Tok.is(tok::less)) {
3065 SourceLocation NewEndLoc;
3066 TypeResult NewReceiverType
3067 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3068 /*consumeLastToken=*/true,
3070 if (!NewReceiverType.isUsable()) {
3071 SkipUntil(tok::r_square, StopAtSemi);
3075 ReceiverType = NewReceiverType.get();
3078 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3079 ReceiverType, nullptr);
3081 case Sema::ObjCInstanceMessage:
3082 // Fall through to parse an expression.
3087 // Otherwise, an arbitrary expression can be the receiver of a send.
3088 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3089 if (Res.isInvalid()) {
3090 SkipUntil(tok::r_square, StopAtSemi);
3094 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3098 /// \brief Parse the remainder of an Objective-C message following the
3099 /// '[' objc-receiver.
3101 /// This routine handles sends to super, class messages (sent to a
3102 /// class name), and instance messages (sent to an object), and the
3103 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3104 /// ReceiverExpr, respectively. Only one of these parameters may have
3107 /// \param LBracLoc The location of the opening '['.
3109 /// \param SuperLoc If this is a send to 'super', the location of the
3110 /// 'super' keyword that indicates a send to the superclass.
3112 /// \param ReceiverType If this is a class message, the type of the
3113 /// class we are sending a message to.
3115 /// \param ReceiverExpr If this is an instance message, the expression
3116 /// used to compute the receiver object.
3118 /// objc-message-args:
3120 /// objc-keywordarg-list
3122 /// objc-keywordarg-list:
3124 /// objc-keywordarg-list objc-keywordarg
3126 /// objc-keywordarg:
3127 /// selector-name[opt] ':' objc-keywordexpr
3129 /// objc-keywordexpr:
3130 /// nonempty-expr-list
3132 /// nonempty-expr-list:
3133 /// assignment-expression
3134 /// nonempty-expr-list , assignment-expression
3137 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3138 SourceLocation SuperLoc,
3139 ParsedType ReceiverType,
3140 Expr *ReceiverExpr) {
3141 InMessageExpressionRAIIObject InMessage(*this, true);
3143 if (Tok.is(tok::code_completion)) {
3144 if (SuperLoc.isValid())
3145 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3147 else if (ReceiverType)
3148 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3151 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3157 // Parse objc-selector
3159 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3161 SmallVector<IdentifierInfo *, 12> KeyIdents;
3162 SmallVector<SourceLocation, 12> KeyLocs;
3163 ExprVector KeyExprs;
3165 if (Tok.is(tok::colon)) {
3167 // Each iteration parses a single keyword argument.
3168 KeyIdents.push_back(selIdent);
3169 KeyLocs.push_back(Loc);
3171 if (ExpectAndConsume(tok::colon)) {
3172 // We must manually skip to a ']', otherwise the expression skipper will
3173 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3174 // the enclosing expression.
3175 SkipUntil(tok::r_square, StopAtSemi);
3179 /// Parse the expression after ':'
3181 if (Tok.is(tok::code_completion)) {
3182 if (SuperLoc.isValid())
3183 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3185 /*AtArgumentEpression=*/true);
3186 else if (ReceiverType)
3187 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3189 /*AtArgumentEpression=*/true);
3191 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3193 /*AtArgumentEpression=*/true);
3200 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3201 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3202 Expr = ParseBraceInitializer();
3204 Expr = ParseAssignmentExpression();
3206 ExprResult Res(Expr);
3207 if (Res.isInvalid()) {
3208 // We must manually skip to a ']', otherwise the expression skipper will
3209 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3210 // the enclosing expression.
3211 SkipUntil(tok::r_square, StopAtSemi);
3215 // We have a valid expression.
3216 KeyExprs.push_back(Res.get());
3218 // Code completion after each argument.
3219 if (Tok.is(tok::code_completion)) {
3220 if (SuperLoc.isValid())
3221 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3223 /*AtArgumentEpression=*/false);
3224 else if (ReceiverType)
3225 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3227 /*AtArgumentEpression=*/false);
3229 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3231 /*AtArgumentEpression=*/false);
3236 // Check for another keyword selector.
3237 selIdent = ParseObjCSelectorPiece(Loc);
3238 if (!selIdent && Tok.isNot(tok::colon))
3240 // We have a selector or a colon, continue parsing.
3242 // Parse the, optional, argument list, comma separated.
3243 while (Tok.is(tok::comma)) {
3244 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3245 /// Parse the expression after ','
3246 ExprResult Res(ParseAssignmentExpression());
3247 if (Tok.is(tok::colon))
3248 Res = Actions.CorrectDelayedTyposInExpr(Res);
3249 if (Res.isInvalid()) {
3250 if (Tok.is(tok::colon)) {
3251 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3252 FixItHint::CreateRemoval(commaLoc);
3254 // We must manually skip to a ']', otherwise the expression skipper will
3255 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3256 // the enclosing expression.
3257 SkipUntil(tok::r_square, StopAtSemi);
3261 // We have a valid expression.
3262 KeyExprs.push_back(Res.get());
3264 } else if (!selIdent) {
3265 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3267 // We must manually skip to a ']', otherwise the expression skipper will
3268 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3269 // the enclosing expression.
3270 SkipUntil(tok::r_square, StopAtSemi);
3274 if (Tok.isNot(tok::r_square)) {
3275 Diag(Tok, diag::err_expected)
3276 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3277 // We must manually skip to a ']', otherwise the expression skipper will
3278 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3279 // the enclosing expression.
3280 SkipUntil(tok::r_square, StopAtSemi);
3284 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3286 unsigned nKeys = KeyIdents.size();
3288 KeyIdents.push_back(selIdent);
3289 KeyLocs.push_back(Loc);
3291 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3293 if (SuperLoc.isValid())
3294 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3295 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3296 else if (ReceiverType)
3297 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3298 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3299 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3300 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3303 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3304 ExprResult Res(ParseStringLiteralExpression());
3305 if (Res.isInvalid()) return Res;
3307 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3308 // expressions. At this point, we know that the only valid thing that starts
3309 // with '@' is an @"".
3310 SmallVector<SourceLocation, 4> AtLocs;
3311 ExprVector AtStrings;
3312 AtLocs.push_back(AtLoc);
3313 AtStrings.push_back(Res.get());
3315 while (Tok.is(tok::at)) {
3316 AtLocs.push_back(ConsumeToken()); // eat the @.
3318 // Invalid unless there is a string literal.
3319 if (!isTokenStringLiteral())
3320 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3322 ExprResult Lit(ParseStringLiteralExpression());
3323 if (Lit.isInvalid())
3326 AtStrings.push_back(Lit.get());
3329 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3332 /// ParseObjCBooleanLiteral -
3333 /// objc-scalar-literal : '@' boolean-keyword
3335 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3337 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3339 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3340 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3343 /// ParseObjCCharacterLiteral -
3344 /// objc-scalar-literal : '@' character-literal
3346 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3347 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3348 if (Lit.isInvalid()) {
3351 ConsumeToken(); // Consume the literal token.
3352 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3355 /// ParseObjCNumericLiteral -
3356 /// objc-scalar-literal : '@' scalar-literal
3358 /// scalar-literal : | numeric-constant /* any numeric constant. */
3360 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3361 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3362 if (Lit.isInvalid()) {
3365 ConsumeToken(); // Consume the literal token.
3366 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3369 /// ParseObjCBoxedExpr -
3370 /// objc-box-expression:
3371 /// @( assignment-expression )
3373 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3374 if (Tok.isNot(tok::l_paren))
3375 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3377 BalancedDelimiterTracker T(*this, tok::l_paren);
3379 ExprResult ValueExpr(ParseAssignmentExpression());
3380 if (T.consumeClose())
3383 if (ValueExpr.isInvalid())
3386 // Wrap the sub-expression in a parenthesized expression, to distinguish
3387 // a boxed expression from a literal.
3388 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3389 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3390 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3394 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3395 ExprVector ElementExprs; // array elements.
3396 ConsumeBracket(); // consume the l_square.
3398 bool HasInvalidEltExpr = false;
3399 while (Tok.isNot(tok::r_square)) {
3400 // Parse list of array element expressions (all must be id types).
3401 ExprResult Res(ParseAssignmentExpression());
3402 if (Res.isInvalid()) {
3403 // We must manually skip to a ']', otherwise the expression skipper will
3404 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3405 // the enclosing expression.
3406 SkipUntil(tok::r_square, StopAtSemi);
3410 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3411 if (Res.isInvalid())
3412 HasInvalidEltExpr = true;
3414 // Parse the ellipsis that indicates a pack expansion.
3415 if (Tok.is(tok::ellipsis))
3416 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3417 if (Res.isInvalid())
3418 HasInvalidEltExpr = true;
3420 ElementExprs.push_back(Res.get());
3422 if (Tok.is(tok::comma))
3423 ConsumeToken(); // Eat the ','.
3424 else if (Tok.isNot(tok::r_square))
3425 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3428 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3430 if (HasInvalidEltExpr)
3433 MultiExprArg Args(ElementExprs);
3434 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3437 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3438 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3439 ConsumeBrace(); // consume the l_square.
3440 bool HasInvalidEltExpr = false;
3441 while (Tok.isNot(tok::r_brace)) {
3442 // Parse the comma separated key : value expressions.
3445 ColonProtectionRAIIObject X(*this);
3446 KeyExpr = ParseAssignmentExpression();
3447 if (KeyExpr.isInvalid()) {
3448 // We must manually skip to a '}', otherwise the expression skipper will
3449 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3450 // the enclosing expression.
3451 SkipUntil(tok::r_brace, StopAtSemi);
3456 if (ExpectAndConsume(tok::colon)) {
3457 SkipUntil(tok::r_brace, StopAtSemi);
3461 ExprResult ValueExpr(ParseAssignmentExpression());
3462 if (ValueExpr.isInvalid()) {
3463 // We must manually skip to a '}', otherwise the expression skipper will
3464 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3465 // the enclosing expression.
3466 SkipUntil(tok::r_brace, StopAtSemi);
3470 // Check the key and value for possible typos
3471 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3472 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3473 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3474 HasInvalidEltExpr = true;
3476 // Parse the ellipsis that designates this as a pack expansion. Do not
3477 // ActOnPackExpansion here, leave it to template instantiation time where
3478 // we can get better diagnostics.
3479 SourceLocation EllipsisLoc;
3480 if (getLangOpts().CPlusPlus)
3481 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3483 // We have a valid expression. Collect it in a vector so we can
3484 // build the argument list.
3485 ObjCDictionaryElement Element = {
3486 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3488 Elements.push_back(Element);
3490 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3491 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3494 SourceLocation EndLoc = ConsumeBrace();
3496 if (HasInvalidEltExpr)
3499 // Create the ObjCDictionaryLiteral.
3500 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3504 /// objc-encode-expression:
3505 /// \@encode ( type-name )
3507 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3508 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3510 SourceLocation EncLoc = ConsumeToken();
3512 if (Tok.isNot(tok::l_paren))
3513 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3515 BalancedDelimiterTracker T(*this, tok::l_paren);
3518 TypeResult Ty = ParseTypeName();
3525 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3526 Ty.get(), T.getCloseLocation());
3529 /// objc-protocol-expression
3530 /// \@protocol ( protocol-name )
3532 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3533 SourceLocation ProtoLoc = ConsumeToken();
3535 if (Tok.isNot(tok::l_paren))
3536 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3538 BalancedDelimiterTracker T(*this, tok::l_paren);
3541 if (expectIdentifier())
3544 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3545 SourceLocation ProtoIdLoc = ConsumeToken();
3549 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3550 T.getOpenLocation(), ProtoIdLoc,
3551 T.getCloseLocation());
3554 /// objc-selector-expression
3555 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3556 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3557 SourceLocation SelectorLoc = ConsumeToken();
3559 if (Tok.isNot(tok::l_paren))
3560 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3562 SmallVector<IdentifierInfo *, 12> KeyIdents;
3563 SourceLocation sLoc;
3565 BalancedDelimiterTracker T(*this, tok::l_paren);
3567 bool HasOptionalParen = Tok.is(tok::l_paren);
3568 if (HasOptionalParen)
3571 if (Tok.is(tok::code_completion)) {
3572 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3577 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3578 if (!SelIdent && // missing selector name.
3579 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3580 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3582 KeyIdents.push_back(SelIdent);
3584 unsigned nColons = 0;
3585 if (Tok.isNot(tok::r_paren)) {
3587 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3589 KeyIdents.push_back(nullptr);
3590 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3594 if (Tok.is(tok::r_paren))
3597 if (Tok.is(tok::code_completion)) {
3598 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3603 // Check for another keyword selector.
3605 SelIdent = ParseObjCSelectorPiece(Loc);
3606 KeyIdents.push_back(SelIdent);
3607 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3611 if (HasOptionalParen && Tok.is(tok::r_paren))
3612 ConsumeParen(); // ')'
3614 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3615 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3616 T.getOpenLocation(),
3617 T.getCloseLocation(),
3621 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3622 // MCDecl might be null due to error in method or c-function prototype, etc.
3623 Decl *MCDecl = LM.D;
3624 bool skip = MCDecl &&
3625 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3626 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3630 // Save the current token position.
3631 SourceLocation OrigLoc = Tok.getLocation();
3633 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3634 // Store an artificial EOF token to ensure that we don't run off the end of
3635 // the method's body when we come to parse it.
3638 Eof.setKind(tok::eof);
3639 Eof.setEofData(MCDecl);
3640 Eof.setLocation(OrigLoc);
3641 LM.Toks.push_back(Eof);
3642 // Append the current token at the end of the new token stream so that it
3643 // doesn't get lost.
3644 LM.Toks.push_back(Tok);
3645 PP.EnterTokenStream(LM.Toks, true);
3647 // Consume the previously pushed token.
3648 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3650 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3651 "Inline objective-c method not starting with '{' or 'try' or ':'");
3652 // Enter a scope for the method or c-function body.
3653 ParseScope BodyScope(this,
3655 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
3656 : Scope::FnScope|Scope::DeclScope);
3658 // Tell the actions module that we have entered a method or c-function definition
3659 // with the specified Declarator for the method/function.
3661 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3663 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3664 if (Tok.is(tok::kw_try))
3665 ParseFunctionTryBlock(MCDecl, BodyScope);
3667 if (Tok.is(tok::colon))
3668 ParseConstructorInitializer(MCDecl);
3670 Actions.ActOnDefaultCtorInitializers(MCDecl);
3671 ParseFunctionStatementBody(MCDecl, BodyScope);
3674 if (Tok.getLocation() != OrigLoc) {
3675 // Due to parsing error, we either went over the cached tokens or
3676 // there are still cached tokens left. If it's the latter case skip the
3678 // Since this is an uncommon situation that should be avoided, use the
3679 // expensive isBeforeInTranslationUnit call.
3680 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3682 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3685 // Clean up the remaining EOF token.