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 SingleDecl = ParseModuleImport(AtLoc);
88 Diag(AtLoc, diag::err_atimport);
90 return Actions.ConvertDeclToDeclGroup(nullptr);
92 Diag(AtLoc, diag::err_unexpected_at);
97 return Actions.ConvertDeclToDeclGroup(SingleDecl);
100 /// Class to handle popping type parameters when leaving the scope.
101 class Parser::ObjCTypeParamListScope {
104 ObjCTypeParamList *Params;
107 ObjCTypeParamListScope(Sema &Actions, Scope *S)
108 : Actions(Actions), S(S), Params(nullptr) {}
110 ~ObjCTypeParamListScope() {
114 void enter(ObjCTypeParamList *P) {
121 Actions.popObjCTypeParamList(S, Params);
127 /// objc-class-declaration:
128 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
130 /// objc-class-forward-decl:
131 /// identifier objc-type-parameter-list[opt]
133 Parser::DeclGroupPtrTy
134 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
135 ConsumeToken(); // the identifier "class"
136 SmallVector<IdentifierInfo *, 8> ClassNames;
137 SmallVector<SourceLocation, 8> ClassLocs;
138 SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
141 MaybeSkipAttributes(tok::objc_class);
142 if (expectIdentifier()) {
143 SkipUntil(tok::semi);
144 return Actions.ConvertDeclToDeclGroup(nullptr);
146 ClassNames.push_back(Tok.getIdentifierInfo());
147 ClassLocs.push_back(Tok.getLocation());
150 // Parse the optional objc-type-parameter-list.
151 ObjCTypeParamList *TypeParams = nullptr;
152 if (Tok.is(tok::less))
153 TypeParams = parseObjCTypeParamList();
154 ClassTypeParams.push_back(TypeParams);
155 if (!TryConsumeToken(tok::comma))
160 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
161 return Actions.ConvertDeclToDeclGroup(nullptr);
163 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
169 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
171 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
172 if (ock == Sema::OCK_None)
175 Decl *Decl = Actions.getObjCDeclContext();
176 if (CurParsedObjCImpl) {
177 CurParsedObjCImpl->finish(AtLoc);
179 Actions.ActOnAtEnd(getCurScope(), AtLoc);
181 Diag(AtLoc, diag::err_objc_missing_end)
182 << FixItHint::CreateInsertion(AtLoc, "@end\n");
184 Diag(Decl->getLocStart(), diag::note_objc_container_start)
190 /// objc-class-interface-attributes[opt] objc-class-interface
191 /// objc-category-interface
193 /// objc-class-interface:
194 /// '@' 'interface' identifier objc-type-parameter-list[opt]
195 /// objc-superclass[opt] objc-protocol-refs[opt]
196 /// objc-class-instance-variables[opt]
197 /// objc-interface-decl-list
200 /// objc-category-interface:
201 /// '@' 'interface' identifier objc-type-parameter-list[opt]
202 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
203 /// objc-interface-decl-list
207 /// ':' identifier objc-type-arguments[opt]
209 /// objc-class-interface-attributes:
210 /// __attribute__((visibility("default")))
211 /// __attribute__((visibility("hidden")))
212 /// __attribute__((deprecated))
213 /// __attribute__((unavailable))
214 /// __attribute__((objc_exception)) - used by NSException on 64-bit
215 /// __attribute__((objc_root_class))
217 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
218 ParsedAttributes &attrs) {
219 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
220 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
221 CheckNestedObjCContexts(AtLoc);
222 ConsumeToken(); // the "interface" identifier
224 // Code completion after '@interface'.
225 if (Tok.is(tok::code_completion)) {
226 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
231 MaybeSkipAttributes(tok::objc_interface);
233 if (expectIdentifier())
234 return nullptr; // missing class or category name.
236 // We have a class or category name - consume it.
237 IdentifierInfo *nameId = Tok.getIdentifierInfo();
238 SourceLocation nameLoc = ConsumeToken();
240 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
241 // case, LAngleLoc will be valid and ProtocolIdents will capture the
242 // protocol references (that have not yet been resolved).
243 SourceLocation LAngleLoc, EndProtoLoc;
244 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
245 ObjCTypeParamList *typeParameterList = nullptr;
246 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
247 if (Tok.is(tok::less))
248 typeParameterList = parseObjCTypeParamListOrProtocolRefs(
249 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
251 if (Tok.is(tok::l_paren) &&
252 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
254 BalancedDelimiterTracker T(*this, tok::l_paren);
257 SourceLocation categoryLoc;
258 IdentifierInfo *categoryId = nullptr;
259 if (Tok.is(tok::code_completion)) {
260 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
265 // For ObjC2, the category name is optional (not an error).
266 if (Tok.is(tok::identifier)) {
267 categoryId = Tok.getIdentifierInfo();
268 categoryLoc = ConsumeToken();
270 else if (!getLangOpts().ObjC2) {
271 Diag(Tok, diag::err_expected)
272 << tok::identifier; // missing category name.
277 if (T.getCloseLocation().isInvalid())
280 // Next, we need to check for any protocol references.
281 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
282 SmallVector<Decl *, 8> ProtocolRefs;
283 SmallVector<SourceLocation, 8> ProtocolLocs;
284 if (Tok.is(tok::less) &&
285 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
286 LAngleLoc, EndProtoLoc,
287 /*consumeLastToken=*/true))
290 Decl *CategoryType = Actions.ActOnStartCategoryInterface(
291 AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
292 ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
293 EndProtoLoc, attrs.getList());
295 if (Tok.is(tok::l_brace))
296 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
298 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
302 // Parse a class interface.
303 IdentifierInfo *superClassId = nullptr;
304 SourceLocation superClassLoc;
305 SourceLocation typeArgsLAngleLoc;
306 SmallVector<ParsedType, 4> typeArgs;
307 SourceLocation typeArgsRAngleLoc;
308 SmallVector<Decl *, 4> protocols;
309 SmallVector<SourceLocation, 4> protocolLocs;
310 if (Tok.is(tok::colon)) { // a super class is specified.
313 // Code completion of superclass names.
314 if (Tok.is(tok::code_completion)) {
315 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
320 if (expectIdentifier())
321 return nullptr; // missing super class name.
322 superClassId = Tok.getIdentifierInfo();
323 superClassLoc = ConsumeToken();
325 // Type arguments for the superclass or protocol conformances.
326 if (Tok.is(tok::less)) {
327 parseObjCTypeArgsOrProtocolQualifiers(
328 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
329 protocols, protocolLocs, EndProtoLoc,
330 /*consumeLastToken=*/true,
331 /*warnOnIncompleteProtocols=*/true);
332 if (Tok.is(tok::eof))
337 // Next, we need to check for any protocol references.
338 if (LAngleLoc.isValid()) {
339 if (!ProtocolIdents.empty()) {
340 // We already parsed the protocols named when we thought we had a
341 // type parameter list. Translate them into actual protocol references.
342 for (const auto &pair : ProtocolIdents) {
343 protocolLocs.push_back(pair.second);
345 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
346 /*ForObjCContainer=*/true,
347 ProtocolIdents, protocols);
349 } else if (protocols.empty() && Tok.is(tok::less) &&
350 ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
351 LAngleLoc, EndProtoLoc,
352 /*consumeLastToken=*/true)) {
356 if (Tok.isNot(tok::less))
357 Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
358 superClassId, superClassLoc);
361 Actions.ActOnStartClassInterface(getCurScope(), AtLoc, nameId, nameLoc,
362 typeParameterList, superClassId,
365 SourceRange(typeArgsLAngleLoc,
367 protocols.data(), protocols.size(),
369 EndProtoLoc, attrs.getList());
371 if (Tok.is(tok::l_brace))
372 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
374 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
379 /// Add an attribute for a context-sensitive type nullability to the given
381 static void addContextSensitiveTypeNullability(Parser &P,
383 NullabilityKind nullability,
384 SourceLocation nullabilityLoc,
385 bool &addedToDeclSpec) {
386 // Create the attribute.
387 auto getNullabilityAttr = [&]() -> AttributeList * {
388 return D.getAttributePool().create(
389 P.getNullabilityKeyword(nullability),
390 SourceRange(nullabilityLoc),
391 nullptr, SourceLocation(),
393 AttributeList::AS_ContextSensitiveKeyword);
396 if (D.getNumTypeObjects() > 0) {
397 // Add the attribute to the declarator chunk nearest the declarator.
398 auto nullabilityAttr = getNullabilityAttr();
399 DeclaratorChunk &chunk = D.getTypeObject(0);
400 nullabilityAttr->setNext(chunk.getAttrListRef());
401 chunk.getAttrListRef() = nullabilityAttr;
402 } else if (!addedToDeclSpec) {
403 // Otherwise, just put it on the declaration specifiers (if one
404 // isn't there already).
405 D.getMutableDeclSpec().addAttributes(getNullabilityAttr());
406 addedToDeclSpec = true;
410 /// Parse an Objective-C type parameter list, if present, or capture
411 /// the locations of the protocol identifiers for a list of protocol
414 /// objc-type-parameter-list:
415 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
417 /// objc-type-parameter:
418 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
420 /// objc-type-parameter-bound:
423 /// objc-type-parameter-variance:
425 /// '__contravariant'
427 /// \param lAngleLoc The location of the starting '<'.
429 /// \param protocolIdents Will capture the list of identifiers, if the
430 /// angle brackets contain a list of protocol references rather than a
431 /// type parameter list.
433 /// \param rAngleLoc The location of the ending '>'.
434 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
435 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
436 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
437 SourceLocation &rAngleLoc, bool mayBeProtocolList) {
438 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
440 // Within the type parameter list, don't treat '>' as an operator.
441 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
443 // Local function to "flush" the protocol identifiers, turning them into
445 SmallVector<Decl *, 4> typeParams;
446 auto makeProtocolIdentsIntoTypeParameters = [&]() {
448 for (const auto &pair : protocolIdents) {
449 DeclResult typeParam = Actions.actOnObjCTypeParam(
450 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
451 index++, pair.first, pair.second, SourceLocation(), nullptr);
452 if (typeParam.isUsable())
453 typeParams.push_back(typeParam.get());
456 protocolIdents.clear();
457 mayBeProtocolList = false;
460 bool invalid = false;
461 lAngleLoc = ConsumeToken();
464 // Parse the variance, if any.
465 SourceLocation varianceLoc;
466 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
467 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
468 variance = Tok.is(tok::kw___covariant)
469 ? ObjCTypeParamVariance::Covariant
470 : ObjCTypeParamVariance::Contravariant;
471 varianceLoc = ConsumeToken();
473 // Once we've seen a variance specific , we know this is not a
474 // list of protocol references.
475 if (mayBeProtocolList) {
476 // Up until now, we have been queuing up parameters because they
477 // might be protocol references. Turn them into parameters now.
478 makeProtocolIdentsIntoTypeParameters();
482 // Parse the identifier.
483 if (!Tok.is(tok::identifier)) {
485 if (Tok.is(tok::code_completion)) {
486 // FIXME: If these aren't protocol references, we'll need different
488 Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
491 // FIXME: Better recovery here?.
495 Diag(Tok, diag::err_objc_expected_type_parameter);
500 IdentifierInfo *paramName = Tok.getIdentifierInfo();
501 SourceLocation paramLoc = ConsumeToken();
503 // If there is a bound, parse it.
504 SourceLocation colonLoc;
505 TypeResult boundType;
506 if (TryConsumeToken(tok::colon, colonLoc)) {
507 // Once we've seen a bound, we know this is not a list of protocol
509 if (mayBeProtocolList) {
510 // Up until now, we have been queuing up parameters because they
511 // might be protocol references. Turn them into parameters now.
512 makeProtocolIdentsIntoTypeParameters();
516 boundType = ParseTypeName();
517 if (boundType.isInvalid())
519 } else if (mayBeProtocolList) {
520 // If this could still be a protocol list, just capture the identifier.
521 // We don't want to turn it into a parameter.
522 protocolIdents.push_back(std::make_pair(paramName, paramLoc));
526 // Create the type parameter.
527 DeclResult typeParam = Actions.actOnObjCTypeParam(
528 getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
529 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
530 if (typeParam.isUsable())
531 typeParams.push_back(typeParam.get());
532 } while (TryConsumeToken(tok::comma));
536 SkipUntil(tok::greater, tok::at, StopBeforeMatch);
537 if (Tok.is(tok::greater))
539 } else if (ParseGreaterThanInTemplateList(rAngleLoc,
540 /*ConsumeLastToken=*/true,
541 /*ObjCGenericList=*/true)) {
542 Diag(lAngleLoc, diag::note_matching) << "'<'";
543 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
544 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
545 tok::comma, tok::semi },
547 if (Tok.is(tok::greater))
551 if (mayBeProtocolList) {
552 // A type parameter list must be followed by either a ':' (indicating the
553 // presence of a superclass) or a '(' (indicating that this is a category
554 // or extension). This disambiguates between an objc-type-parameter-list
555 // and a objc-protocol-refs.
556 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
557 // Returning null indicates that we don't have a type parameter list.
558 // The results the caller needs to handle the protocol references are
559 // captured in the reference parameters already.
563 // We have a type parameter list that looks like a list of protocol
564 // references. Turn that parameter list into type parameters.
565 makeProtocolIdentsIntoTypeParameters();
568 // Form the type parameter list and enter its scope.
569 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
576 // Clear out the angle locations; they're used by the caller to indicate
577 // whether there are any protocol references.
578 lAngleLoc = SourceLocation();
579 rAngleLoc = SourceLocation();
580 return invalid ? nullptr : list;
583 /// Parse an objc-type-parameter-list.
584 ObjCTypeParamList *Parser::parseObjCTypeParamList() {
585 SourceLocation lAngleLoc;
586 SmallVector<IdentifierLocPair, 1> protocolIdents;
587 SourceLocation rAngleLoc;
589 ObjCTypeParamListScope Scope(Actions, getCurScope());
590 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
592 /*mayBeProtocolList=*/false);
595 /// objc-interface-decl-list:
597 /// objc-interface-decl-list objc-property-decl [OBJC2]
598 /// objc-interface-decl-list objc-method-requirement [OBJC2]
599 /// objc-interface-decl-list objc-method-proto ';'
600 /// objc-interface-decl-list declaration
601 /// objc-interface-decl-list ';'
603 /// objc-method-requirement: [OBJC2]
607 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
609 SmallVector<Decl *, 32> allMethods;
610 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
611 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
616 // If this is a method prototype, parse it.
617 if (Tok.isOneOf(tok::minus, tok::plus)) {
618 if (Decl *methodPrototype =
619 ParseObjCMethodPrototype(MethodImplKind, false))
620 allMethods.push_back(methodPrototype);
621 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
622 // method definitions.
623 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
624 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
625 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
626 if (Tok.is(tok::semi))
631 if (Tok.is(tok::l_paren)) {
632 Diag(Tok, diag::err_expected_minus_or_plus);
633 ParseObjCMethodDecl(Tok.getLocation(),
635 MethodImplKind, false);
638 // Ignore excess semicolons.
639 if (Tok.is(tok::semi)) {
644 // If we got to the end of the file, exit the loop.
648 // Code completion within an Objective-C interface.
649 if (Tok.is(tok::code_completion)) {
650 Actions.CodeCompleteOrdinaryName(getCurScope(),
651 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
652 : Sema::PCC_ObjCInterface);
653 return cutOffParsing();
656 // If we don't have an @ directive, parse it as a function definition.
657 if (Tok.isNot(tok::at)) {
658 // The code below does not consume '}'s because it is afraid of eating the
659 // end of a namespace. Because of the way this code is structured, an
660 // erroneous r_brace would cause an infinite loop if not handled here.
661 if (Tok.is(tok::r_brace))
663 ParsedAttributesWithRange attrs(AttrFactory);
664 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
668 // Otherwise, we have an @ directive, eat the @.
669 SourceLocation AtLoc = ConsumeToken(); // the "@"
670 if (Tok.is(tok::code_completion)) {
671 Actions.CodeCompleteObjCAtDirective(getCurScope());
672 return cutOffParsing();
675 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
677 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
678 AtEnd.setBegin(AtLoc);
679 AtEnd.setEnd(Tok.getLocation());
681 } else if (DirectiveKind == tok::objc_not_keyword) {
682 Diag(Tok, diag::err_objc_unknown_at);
683 SkipUntil(tok::semi);
687 // Eat the identifier.
690 switch (DirectiveKind) {
692 // FIXME: If someone forgets an @end on a protocol, this loop will
693 // continue to eat up tons of stuff and spew lots of nonsense errors. It
694 // would probably be better to bail out if we saw an @class or @interface
695 // or something like that.
696 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
697 // Skip until we see an '@' or '}' or ';'.
698 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
701 case tok::objc_implementation:
702 case tok::objc_interface:
703 Diag(AtLoc, diag::err_objc_missing_end)
704 << FixItHint::CreateInsertion(AtLoc, "@end\n");
705 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
706 << (int) Actions.getObjCContainerKind();
710 case tok::objc_required:
711 case tok::objc_optional:
712 // This is only valid on protocols.
713 // FIXME: Should this check for ObjC2 being enabled?
714 if (contextKey != tok::objc_protocol)
715 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
717 MethodImplKind = DirectiveKind;
720 case tok::objc_property:
721 if (!getLangOpts().ObjC2)
722 Diag(AtLoc, diag::err_objc_properties_require_objc2);
725 SourceLocation LParenLoc;
726 // Parse property attribute list, if any.
727 if (Tok.is(tok::l_paren)) {
728 LParenLoc = Tok.getLocation();
729 ParseObjCPropertyAttribute(OCDS);
732 bool addedToDeclSpec = false;
733 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
734 if (FD.D.getIdentifier() == nullptr) {
735 Diag(AtLoc, diag::err_objc_property_requires_field_name)
736 << FD.D.getSourceRange();
739 if (FD.BitfieldSize) {
740 Diag(AtLoc, diag::err_objc_property_bitfield)
741 << FD.D.getSourceRange();
745 // Map a nullability property attribute to a context-sensitive keyword
747 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
748 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
749 OCDS.getNullabilityLoc(),
752 // Install the property declarator into interfaceDecl.
753 IdentifierInfo *SelName =
754 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
756 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
757 IdentifierInfo *SetterName = OCDS.getSetterName();
760 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
762 SetterSel = SelectorTable::constructSetterSelector(
763 PP.getIdentifierTable(), PP.getSelectorTable(),
764 FD.D.getIdentifier());
765 Decl *Property = Actions.ActOnProperty(
766 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
769 FD.complete(Property);
772 // Parse all the comma separated declarators.
773 ParsingDeclSpec DS(*this);
774 ParseStructDeclaration(DS, ObjCPropertyCallback);
776 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
781 // We break out of the big loop in two cases: when we see @end or when we see
782 // EOF. In the former case, eat the @end. In the later case, emit an error.
783 if (Tok.is(tok::code_completion)) {
784 Actions.CodeCompleteObjCAtDirective(getCurScope());
785 return cutOffParsing();
786 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
787 ConsumeToken(); // the "end" identifier
789 Diag(Tok, diag::err_objc_missing_end)
790 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
791 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
792 << (int) Actions.getObjCContainerKind();
793 AtEnd.setBegin(Tok.getLocation());
794 AtEnd.setEnd(Tok.getLocation());
797 // Insert collected methods declarations into the @interface object.
798 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
799 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
802 /// Diagnose redundant or conflicting nullability information.
803 static void diagnoseRedundantPropertyNullability(Parser &P,
805 NullabilityKind nullability,
806 SourceLocation nullabilityLoc){
807 if (DS.getNullability() == nullability) {
808 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
809 << DiagNullabilityKind(nullability, true)
810 << SourceRange(DS.getNullabilityLoc());
814 P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
815 << DiagNullabilityKind(nullability, true)
816 << DiagNullabilityKind(DS.getNullability(), true)
817 << SourceRange(DS.getNullabilityLoc());
820 /// Parse property attribute declarations.
822 /// property-attr-decl: '(' property-attrlist ')'
823 /// property-attrlist:
824 /// property-attribute
825 /// property-attrlist ',' property-attribute
826 /// property-attribute:
827 /// getter '=' identifier
828 /// setter '=' identifier ':'
838 /// unsafe_unretained
845 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
846 assert(Tok.getKind() == tok::l_paren);
847 BalancedDelimiterTracker T(*this, tok::l_paren);
851 if (Tok.is(tok::code_completion)) {
852 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
853 return cutOffParsing();
855 const IdentifierInfo *II = Tok.getIdentifierInfo();
857 // If this is not an identifier at all, bail out early.
863 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
865 if (II->isStr("readonly"))
866 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
867 else if (II->isStr("assign"))
868 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
869 else if (II->isStr("unsafe_unretained"))
870 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
871 else if (II->isStr("readwrite"))
872 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
873 else if (II->isStr("retain"))
874 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
875 else if (II->isStr("strong"))
876 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
877 else if (II->isStr("copy"))
878 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
879 else if (II->isStr("nonatomic"))
880 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
881 else if (II->isStr("atomic"))
882 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
883 else if (II->isStr("weak"))
884 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
885 else if (II->isStr("getter") || II->isStr("setter")) {
886 bool IsSetter = II->getNameStart()[0] == 's';
888 // getter/setter require extra treatment.
889 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
890 diag::err_objc_expected_equal_for_getter;
892 if (ExpectAndConsume(tok::equal, DiagID)) {
893 SkipUntil(tok::r_paren, StopAtSemi);
897 if (Tok.is(tok::code_completion)) {
899 Actions.CodeCompleteObjCPropertySetter(getCurScope());
901 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
902 return cutOffParsing();
905 SourceLocation SelLoc;
906 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
909 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
911 SkipUntil(tok::r_paren, StopAtSemi);
916 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
917 DS.setSetterName(SelIdent, SelLoc);
919 if (ExpectAndConsume(tok::colon,
920 diag::err_expected_colon_after_setter_name)) {
921 SkipUntil(tok::r_paren, StopAtSemi);
925 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
926 DS.setGetterName(SelIdent, SelLoc);
928 } else if (II->isStr("nonnull")) {
929 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
930 diagnoseRedundantPropertyNullability(*this, DS,
931 NullabilityKind::NonNull,
933 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
934 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
935 } else if (II->isStr("nullable")) {
936 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
937 diagnoseRedundantPropertyNullability(*this, DS,
938 NullabilityKind::Nullable,
940 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
941 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
942 } else if (II->isStr("null_unspecified")) {
943 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
944 diagnoseRedundantPropertyNullability(*this, DS,
945 NullabilityKind::Unspecified,
947 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
948 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
949 } else if (II->isStr("null_resettable")) {
950 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
951 diagnoseRedundantPropertyNullability(*this, DS,
952 NullabilityKind::Unspecified,
954 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
955 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
957 // Also set the null_resettable bit.
958 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable);
959 } else if (II->isStr("class")) {
960 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class);
962 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
963 SkipUntil(tok::r_paren, StopAtSemi);
967 if (Tok.isNot(tok::comma))
976 /// objc-method-proto:
977 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
978 /// objc-class-method objc-method-decl objc-method-attributes[opt]
980 /// objc-instance-method: '-'
981 /// objc-class-method: '+'
983 /// objc-method-attributes: [OBJC2]
984 /// __attribute__((deprecated))
986 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
987 bool MethodDefinition) {
988 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
990 tok::TokenKind methodType = Tok.getKind();
991 SourceLocation mLoc = ConsumeToken();
992 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
994 // Since this rule is used for both method declarations and definitions,
995 // the caller is (optionally) responsible for consuming the ';'.
1002 /// enum struct union if else while do for switch case default
1003 /// break continue return goto asm sizeof typeof __alignof
1004 /// unsigned long const short volatile signed restrict _Complex
1005 /// in out inout bycopy byref oneway int char float double void _Bool
1007 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
1009 switch (Tok.getKind()) {
1013 // Empty selector piece uses the location of the ':'.
1014 SelectorLoc = Tok.getLocation();
1022 case tok::exclaimequal:
1024 case tok::pipeequal:
1026 case tok::caretequal: {
1027 std::string ThisTok(PP.getSpelling(Tok));
1028 if (isLetter(ThisTok[0])) {
1029 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1030 Tok.setKind(tok::identifier);
1031 SelectorLoc = ConsumeToken();
1037 case tok::identifier:
1047 case tok::kw_const_cast:
1048 case tok::kw_continue:
1049 case tok::kw_default:
1050 case tok::kw_delete:
1052 case tok::kw_double:
1053 case tok::kw_dynamic_cast:
1056 case tok::kw_explicit:
1057 case tok::kw_export:
1058 case tok::kw_extern:
1062 case tok::kw_friend:
1065 case tok::kw_inline:
1068 case tok::kw_mutable:
1069 case tok::kw_namespace:
1071 case tok::kw_operator:
1072 case tok::kw_private:
1073 case tok::kw_protected:
1074 case tok::kw_public:
1075 case tok::kw_register:
1076 case tok::kw_reinterpret_cast:
1077 case tok::kw_restrict:
1078 case tok::kw_return:
1080 case tok::kw_signed:
1081 case tok::kw_sizeof:
1082 case tok::kw_static:
1083 case tok::kw_static_cast:
1084 case tok::kw_struct:
1085 case tok::kw_switch:
1086 case tok::kw_template:
1091 case tok::kw_typedef:
1092 case tok::kw_typeid:
1093 case tok::kw_typename:
1094 case tok::kw_typeof:
1096 case tok::kw_unsigned:
1098 case tok::kw_virtual:
1100 case tok::kw_volatile:
1101 case tok::kw_wchar_t:
1104 case tok::kw__Complex:
1105 case tok::kw___alignof:
1106 case tok::kw___auto_type:
1107 IdentifierInfo *II = Tok.getIdentifierInfo();
1108 SelectorLoc = ConsumeToken();
1113 /// objc-for-collection-in: 'in'
1115 bool Parser::isTokIdentifier_in() const {
1116 // FIXME: May have to do additional look-ahead to only allow for
1117 // valid tokens following an 'in'; such as an identifier, unary operators,
1119 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
1120 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1123 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1124 /// qualifier list and builds their bitmask representation in the input
1127 /// objc-type-qualifiers:
1128 /// objc-type-qualifier
1129 /// objc-type-qualifiers objc-type-qualifier
1131 /// objc-type-qualifier:
1140 /// 'null_unspecified'
1142 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1143 DeclaratorContext Context) {
1144 assert(Context == DeclaratorContext::ObjCParameterContext ||
1145 Context == DeclaratorContext::ObjCResultContext);
1148 if (Tok.is(tok::code_completion)) {
1149 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
1150 Context == DeclaratorContext::ObjCParameterContext);
1151 return cutOffParsing();
1154 if (Tok.isNot(tok::identifier))
1157 const IdentifierInfo *II = Tok.getIdentifierInfo();
1158 for (unsigned i = 0; i != objc_NumQuals; ++i) {
1159 if (II != ObjCTypeQuals[i] ||
1160 NextToken().is(tok::less) ||
1161 NextToken().is(tok::coloncolon))
1164 ObjCDeclSpec::ObjCDeclQualifier Qual;
1165 NullabilityKind Nullability;
1167 default: llvm_unreachable("Unknown decl qualifier");
1168 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
1169 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
1170 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
1171 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1172 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1173 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
1176 Qual = ObjCDeclSpec::DQ_CSNullability;
1177 Nullability = NullabilityKind::NonNull;
1181 Qual = ObjCDeclSpec::DQ_CSNullability;
1182 Nullability = NullabilityKind::Nullable;
1185 case objc_null_unspecified:
1186 Qual = ObjCDeclSpec::DQ_CSNullability;
1187 Nullability = NullabilityKind::Unspecified;
1191 // FIXME: Diagnose redundant specifiers.
1192 DS.setObjCDeclQualifier(Qual);
1193 if (Qual == ObjCDeclSpec::DQ_CSNullability)
1194 DS.setNullability(Tok.getLocation(), Nullability);
1201 // If this wasn't a recognized qualifier, bail out.
1206 /// Take all the decl attributes out of the given list and add
1207 /// them to the given attribute set.
1208 static void takeDeclAttributes(ParsedAttributes &attrs,
1209 AttributeList *list) {
1211 AttributeList *cur = list;
1212 list = cur->getNext();
1214 if (!cur->isUsedAsTypeAttr()) {
1215 // Clear out the next pointer. We're really completely
1216 // destroying the internal invariants of the declarator here,
1217 // but it doesn't matter because we're done with it.
1218 cur->setNext(nullptr);
1224 /// takeDeclAttributes - Take all the decl attributes from the given
1225 /// declarator and add them to the given list.
1226 static void takeDeclAttributes(ParsedAttributes &attrs,
1228 // First, take ownership of all attributes.
1229 attrs.getPool().takeAllFrom(D.getAttributePool());
1230 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1232 // Now actually move the attributes over.
1233 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
1234 takeDeclAttributes(attrs, D.getAttributes());
1235 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1236 takeDeclAttributes(attrs,
1237 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
1241 /// '(' objc-type-qualifiers[opt] type-name ')'
1242 /// '(' objc-type-qualifiers[opt] ')'
1244 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1245 DeclaratorContext context,
1246 ParsedAttributes *paramAttrs) {
1247 assert(context == DeclaratorContext::ObjCParameterContext ||
1248 context == DeclaratorContext::ObjCResultContext);
1249 assert((paramAttrs != nullptr) ==
1250 (context == DeclaratorContext::ObjCParameterContext));
1252 assert(Tok.is(tok::l_paren) && "expected (");
1254 BalancedDelimiterTracker T(*this, tok::l_paren);
1257 SourceLocation TypeStartLoc = Tok.getLocation();
1258 ObjCDeclContextSwitch ObjCDC(*this);
1260 // Parse type qualifiers, in, inout, etc.
1261 ParseObjCTypeQualifierList(DS, context);
1264 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1265 // Parse an abstract declarator.
1266 DeclSpec declSpec(AttrFactory);
1267 declSpec.setObjCQualifiers(&DS);
1268 DeclSpecContext dsContext = DeclSpecContext::DSC_normal;
1269 if (context == DeclaratorContext::ObjCResultContext)
1270 dsContext = DeclSpecContext::DSC_objc_method_result;
1271 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1272 Declarator declarator(declSpec, context);
1273 ParseDeclarator(declarator);
1275 // If that's not invalid, extract a type.
1276 if (!declarator.isInvalidType()) {
1277 // Map a nullability specifier to a context-sensitive keyword attribute.
1278 bool addedToDeclSpec = false;
1279 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1280 addContextSensitiveTypeNullability(*this, declarator,
1281 DS.getNullability(),
1282 DS.getNullabilityLoc(),
1285 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1286 if (!type.isInvalid())
1289 // If we're parsing a parameter, steal all the decl attributes
1290 // and add them to the decl spec.
1291 if (context == DeclaratorContext::ObjCParameterContext)
1292 takeDeclAttributes(*paramAttrs, declarator);
1296 if (Tok.is(tok::r_paren))
1298 else if (Tok.getLocation() == TypeStartLoc) {
1299 // If we didn't eat any tokens, then this isn't a type.
1300 Diag(Tok, diag::err_expected_type);
1301 SkipUntil(tok::r_paren, StopAtSemi);
1303 // Otherwise, we found *something*, but didn't get a ')' in the right
1304 // place. Emit an error then return what we have as the type.
1310 /// objc-method-decl:
1312 /// objc-keyword-selector objc-parmlist[opt]
1313 /// objc-type-name objc-selector
1314 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1316 /// objc-keyword-selector:
1317 /// objc-keyword-decl
1318 /// objc-keyword-selector objc-keyword-decl
1320 /// objc-keyword-decl:
1321 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1322 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1323 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1324 /// ':' objc-keyword-attributes[opt] identifier
1327 /// objc-parms objc-ellipsis[opt]
1330 /// objc-parms , parameter-declaration
1335 /// objc-keyword-attributes: [OBJC2]
1336 /// __attribute__((unused))
1338 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1339 tok::TokenKind mType,
1340 tok::ObjCKeywordKind MethodImplKind,
1341 bool MethodDefinition) {
1342 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1344 if (Tok.is(tok::code_completion)) {
1345 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1346 /*ReturnType=*/nullptr);
1351 // Parse the return type if present.
1352 ParsedType ReturnType;
1354 if (Tok.is(tok::l_paren))
1355 ReturnType = ParseObjCTypeName(DSRet, DeclaratorContext::ObjCResultContext,
1358 // If attributes exist before the method, parse them.
1359 ParsedAttributes methodAttrs(AttrFactory);
1360 if (getLangOpts().ObjC2)
1361 MaybeParseGNUAttributes(methodAttrs);
1363 if (Tok.is(tok::code_completion)) {
1364 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1370 // Now parse the selector.
1371 SourceLocation selLoc;
1372 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1374 // An unnamed colon is valid.
1375 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1376 Diag(Tok, diag::err_expected_selector_for_method)
1377 << SourceRange(mLoc, Tok.getLocation());
1378 // Skip until we get a ; or @.
1379 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1383 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1384 if (Tok.isNot(tok::colon)) {
1385 // If attributes exist after the method, parse them.
1386 if (getLangOpts().ObjC2)
1387 MaybeParseGNUAttributes(methodAttrs);
1389 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1391 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1392 mType, DSRet, ReturnType,
1393 selLoc, Sel, nullptr,
1394 CParamInfo.data(), CParamInfo.size(),
1395 methodAttrs.getList(), MethodImplKind,
1396 false, MethodDefinition);
1397 PD.complete(Result);
1401 SmallVector<IdentifierInfo *, 12> KeyIdents;
1402 SmallVector<SourceLocation, 12> KeyLocs;
1403 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1404 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1405 Scope::FunctionDeclarationScope | Scope::DeclScope);
1407 AttributePool allParamAttrs(AttrFactory);
1409 ParsedAttributes paramAttrs(AttrFactory);
1410 Sema::ObjCArgInfo ArgInfo;
1412 // Each iteration parses a single keyword argument.
1413 if (ExpectAndConsume(tok::colon))
1416 ArgInfo.Type = nullptr;
1417 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1418 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1419 DeclaratorContext::ObjCParameterContext,
1422 // If attributes exist before the argument name, parse them.
1423 // Regardless, collect all the attributes we've parsed so far.
1424 ArgInfo.ArgAttrs = nullptr;
1425 if (getLangOpts().ObjC2) {
1426 MaybeParseGNUAttributes(paramAttrs);
1427 ArgInfo.ArgAttrs = paramAttrs.getList();
1430 // Code completion for the next piece of the selector.
1431 if (Tok.is(tok::code_completion)) {
1432 KeyIdents.push_back(SelIdent);
1433 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1434 mType == tok::minus,
1435 /*AtParameterName=*/true,
1436 ReturnType, KeyIdents);
1441 if (expectIdentifier())
1442 break; // missing argument name.
1444 ArgInfo.Name = Tok.getIdentifierInfo();
1445 ArgInfo.NameLoc = Tok.getLocation();
1446 ConsumeToken(); // Eat the identifier.
1448 ArgInfos.push_back(ArgInfo);
1449 KeyIdents.push_back(SelIdent);
1450 KeyLocs.push_back(selLoc);
1452 // Make sure the attributes persist.
1453 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1455 // Code completion for the next piece of the selector.
1456 if (Tok.is(tok::code_completion)) {
1457 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1458 mType == tok::minus,
1459 /*AtParameterName=*/false,
1460 ReturnType, KeyIdents);
1465 // Check for another keyword selector.
1466 SelIdent = ParseObjCSelectorPiece(selLoc);
1467 if (!SelIdent && Tok.isNot(tok::colon))
1470 SourceLocation ColonLoc = Tok.getLocation();
1471 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1472 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1473 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1474 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1477 // We have a selector or a colon, continue parsing.
1480 bool isVariadic = false;
1481 bool cStyleParamWarned = false;
1482 // Parse the (optional) parameter list.
1483 while (Tok.is(tok::comma)) {
1485 if (Tok.is(tok::ellipsis)) {
1490 if (!cStyleParamWarned) {
1491 Diag(Tok, diag::warn_cstyle_param);
1492 cStyleParamWarned = true;
1494 DeclSpec DS(AttrFactory);
1495 ParseDeclarationSpecifiers(DS);
1496 // Parse the declarator.
1497 Declarator ParmDecl(DS, DeclaratorContext::PrototypeContext);
1498 ParseDeclarator(ParmDecl);
1499 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1500 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1501 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1502 ParmDecl.getIdentifierLoc(),
1507 // FIXME: Add support for optional parameter list...
1508 // If attributes exist after the method, parse them.
1509 if (getLangOpts().ObjC2)
1510 MaybeParseGNUAttributes(methodAttrs);
1512 if (KeyIdents.size() == 0)
1515 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1518 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1519 mType, DSRet, ReturnType,
1520 KeyLocs, Sel, &ArgInfos[0],
1521 CParamInfo.data(), CParamInfo.size(),
1522 methodAttrs.getList(),
1523 MethodImplKind, isVariadic, MethodDefinition);
1525 PD.complete(Result);
1529 /// objc-protocol-refs:
1530 /// '<' identifier-list '>'
1533 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1534 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1535 bool WarnOnDeclarations, bool ForObjCContainer,
1536 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1537 bool consumeLastToken) {
1538 assert(Tok.is(tok::less) && "expected <");
1540 LAngleLoc = ConsumeToken(); // the "<"
1542 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1545 if (Tok.is(tok::code_completion)) {
1546 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1551 if (expectIdentifier()) {
1552 SkipUntil(tok::greater, StopAtSemi);
1555 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1556 Tok.getLocation()));
1557 ProtocolLocs.push_back(Tok.getLocation());
1560 if (!TryConsumeToken(tok::comma))
1565 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1566 /*ObjCGenericList=*/false))
1569 // Convert the list of protocols identifiers into a list of protocol decls.
1570 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1571 ProtocolIdents, Protocols);
1575 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1576 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1577 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1579 SourceLocation lAngleLoc;
1580 SmallVector<Decl *, 8> protocols;
1581 SmallVector<SourceLocation, 8> protocolLocs;
1582 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1583 lAngleLoc, rAngleLoc,
1584 /*consumeLastToken=*/true);
1585 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1589 if (result.isUsable()) {
1590 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1591 << FixItHint::CreateInsertion(lAngleLoc, "id")
1592 << SourceRange(lAngleLoc, rAngleLoc);
1598 /// Parse Objective-C type arguments or protocol qualifiers.
1600 /// objc-type-arguments:
1601 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1603 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1604 ParsedType baseType,
1605 SourceLocation &typeArgsLAngleLoc,
1606 SmallVectorImpl<ParsedType> &typeArgs,
1607 SourceLocation &typeArgsRAngleLoc,
1608 SourceLocation &protocolLAngleLoc,
1609 SmallVectorImpl<Decl *> &protocols,
1610 SmallVectorImpl<SourceLocation> &protocolLocs,
1611 SourceLocation &protocolRAngleLoc,
1612 bool consumeLastToken,
1613 bool warnOnIncompleteProtocols) {
1614 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1615 SourceLocation lAngleLoc = ConsumeToken();
1617 // Whether all of the elements we've parsed thus far are single
1618 // identifiers, which might be types or might be protocols.
1619 bool allSingleIdentifiers = true;
1620 SmallVector<IdentifierInfo *, 4> identifiers;
1621 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1623 // Parse a list of comma-separated identifiers, bailing out if we
1624 // see something different.
1626 // Parse a single identifier.
1627 if (Tok.is(tok::identifier) &&
1628 (NextToken().is(tok::comma) ||
1629 NextToken().is(tok::greater) ||
1630 NextToken().is(tok::greatergreater))) {
1631 identifiers.push_back(Tok.getIdentifierInfo());
1632 identifierLocs.push_back(ConsumeToken());
1636 if (Tok.is(tok::code_completion)) {
1637 // FIXME: Also include types here.
1638 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1639 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1640 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1641 identifierLocs[i]));
1644 QualType BaseT = Actions.GetTypeFromParser(baseType);
1645 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1646 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1648 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1654 allSingleIdentifiers = false;
1656 } while (TryConsumeToken(tok::comma));
1658 // If we parsed an identifier list, semantic analysis sorts out
1659 // whether it refers to protocols or to type arguments.
1660 if (allSingleIdentifiers) {
1661 // Parse the closing '>'.
1662 SourceLocation rAngleLoc;
1663 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1664 /*ObjCGenericList=*/true);
1666 // Let Sema figure out what we parsed.
1667 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1679 warnOnIncompleteProtocols);
1683 // We parsed an identifier list but stumbled into non single identifiers, this
1684 // means we might (a) check that what we already parsed is a legitimate type
1685 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1686 // must all be type args.
1688 // Convert the identifiers into type arguments.
1689 bool invalid = false;
1690 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1691 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1692 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1693 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1695 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1697 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1699 DeclSpec DS(AttrFactory);
1700 const char *prevSpec = nullptr;
1702 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1703 typeArg, Actions.getASTContext().getPrintingPolicy());
1705 // Form a declarator to turn this into a type.
1706 Declarator D(DS, DeclaratorContext::TypeNameContext);
1707 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1708 if (fullTypeArg.isUsable()) {
1709 typeArgs.push_back(fullTypeArg.get());
1710 if (!foundValidTypeId) {
1711 foundValidTypeId = identifiers[i];
1712 foundValidTypeSrcLoc = identifierLocs[i];
1716 unknownTypeArgs.push_back(identifiers[i]);
1717 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1721 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1722 unknownTypeArgs.push_back(identifiers[i]);
1723 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1724 } else if (!foundProtocolId) {
1725 foundProtocolId = identifiers[i];
1726 foundProtocolSrcLoc = identifierLocs[i];
1731 // Continue parsing type-names.
1733 Token CurTypeTok = Tok;
1734 TypeResult typeArg = ParseTypeName();
1736 // Consume the '...' for a pack expansion.
1737 SourceLocation ellipsisLoc;
1738 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1739 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1740 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1743 if (typeArg.isUsable()) {
1744 typeArgs.push_back(typeArg.get());
1745 if (!foundValidTypeId) {
1746 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1747 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1752 } while (TryConsumeToken(tok::comma));
1754 // Diagnose the mix between type args and protocols.
1755 if (foundProtocolId && foundValidTypeId)
1756 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1758 foundValidTypeSrcLoc);
1760 // Diagnose unknown arg types.
1762 if (unknownTypeArgs.size())
1763 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1764 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1765 getCurScope(), nullptr, T);
1767 // Parse the closing '>'.
1768 SourceLocation rAngleLoc;
1769 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1770 /*ObjCGenericList=*/true);
1777 // Record left/right angle locations.
1778 typeArgsLAngleLoc = lAngleLoc;
1779 typeArgsRAngleLoc = rAngleLoc;
1782 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1783 ParsedType baseType,
1784 SourceLocation &typeArgsLAngleLoc,
1785 SmallVectorImpl<ParsedType> &typeArgs,
1786 SourceLocation &typeArgsRAngleLoc,
1787 SourceLocation &protocolLAngleLoc,
1788 SmallVectorImpl<Decl *> &protocols,
1789 SmallVectorImpl<SourceLocation> &protocolLocs,
1790 SourceLocation &protocolRAngleLoc,
1791 bool consumeLastToken) {
1792 assert(Tok.is(tok::less));
1794 // Parse the first angle-bracket-delimited clause.
1795 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1804 /*warnOnIncompleteProtocols=*/false);
1805 if (Tok.is(tok::eof)) // Nothing else to do here...
1808 // An Objective-C object pointer followed by type arguments
1809 // can then be followed again by a set of protocol references, e.g.,
1810 // \c NSArray<NSView><NSTextDelegate>
1811 if ((consumeLastToken && Tok.is(tok::less)) ||
1812 (!consumeLastToken && NextToken().is(tok::less))) {
1813 // If we aren't consuming the last token, the prior '>' is still hanging
1814 // there. Consume it before we parse the protocol qualifiers.
1815 if (!consumeLastToken)
1818 if (!protocols.empty()) {
1819 SkipUntilFlags skipFlags = SkipUntilFlags();
1820 if (!consumeLastToken)
1821 skipFlags = skipFlags | StopBeforeMatch;
1822 Diag(Tok, diag::err_objc_type_args_after_protocols)
1823 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1824 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1826 ParseObjCProtocolReferences(protocols, protocolLocs,
1827 /*WarnOnDeclarations=*/false,
1828 /*ForObjCContainer=*/false,
1829 protocolLAngleLoc, protocolRAngleLoc,
1835 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1838 bool consumeLastToken,
1839 SourceLocation &endLoc) {
1840 assert(Tok.is(tok::less));
1841 SourceLocation typeArgsLAngleLoc;
1842 SmallVector<ParsedType, 4> typeArgs;
1843 SourceLocation typeArgsRAngleLoc;
1844 SourceLocation protocolLAngleLoc;
1845 SmallVector<Decl *, 4> protocols;
1846 SmallVector<SourceLocation, 4> protocolLocs;
1847 SourceLocation protocolRAngleLoc;
1849 // Parse type arguments and protocol qualifiers.
1850 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1851 typeArgsRAngleLoc, protocolLAngleLoc,
1852 protocols, protocolLocs,
1853 protocolRAngleLoc, consumeLastToken);
1855 if (Tok.is(tok::eof))
1856 return true; // Invalid type result.
1858 // Compute the location of the last token.
1859 if (consumeLastToken)
1860 endLoc = PrevTokLocation;
1862 endLoc = Tok.getLocation();
1864 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1877 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1878 BalancedDelimiterTracker &T,
1879 SmallVectorImpl<Decl *> &AllIvarDecls,
1880 bool RBraceMissing) {
1884 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1885 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1886 Actions.ActOnObjCContainerFinishDefinition();
1887 // Call ActOnFields() even if we don't have any decls. This is useful
1888 // for code rewriting tools that need to be aware of the empty list.
1889 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1891 T.getOpenLocation(), T.getCloseLocation(), nullptr);
1894 /// objc-class-instance-variables:
1895 /// '{' objc-instance-variable-decl-list[opt] '}'
1897 /// objc-instance-variable-decl-list:
1898 /// objc-visibility-spec
1899 /// objc-instance-variable-decl ';'
1901 /// objc-instance-variable-decl-list objc-visibility-spec
1902 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1903 /// objc-instance-variable-decl-list ';'
1905 /// objc-visibility-spec:
1909 /// @package [OBJC2]
1911 /// objc-instance-variable-decl:
1912 /// struct-declaration
1914 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1915 tok::ObjCKeywordKind visibility,
1916 SourceLocation atLoc) {
1917 assert(Tok.is(tok::l_brace) && "expected {");
1918 SmallVector<Decl *, 32> AllIvarDecls;
1920 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1921 ObjCDeclContextSwitch ObjCDC(*this);
1923 BalancedDelimiterTracker T(*this, tok::l_brace);
1925 // While we still have something to read, read the instance variables.
1926 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1927 // Each iteration of this loop reads one objc-instance-variable-decl.
1929 // Check for extraneous top-level semicolon.
1930 if (Tok.is(tok::semi)) {
1931 ConsumeExtraSemi(InstanceVariableList);
1935 // Set the default visibility to private.
1936 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1937 if (Tok.is(tok::code_completion)) {
1938 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1939 return cutOffParsing();
1942 switch (Tok.getObjCKeywordID()) {
1943 case tok::objc_private:
1944 case tok::objc_public:
1945 case tok::objc_protected:
1946 case tok::objc_package:
1947 visibility = Tok.getObjCKeywordID();
1952 Diag(Tok, diag::err_objc_unexpected_atend);
1953 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1954 Tok.setKind(tok::at);
1957 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1958 T, AllIvarDecls, true);
1962 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1967 if (Tok.is(tok::code_completion)) {
1968 Actions.CodeCompleteOrdinaryName(getCurScope(),
1969 Sema::PCC_ObjCInstanceVariableList);
1970 return cutOffParsing();
1973 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1974 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1975 // Install the declarator into the interface decl.
1976 FD.D.setObjCIvar(true);
1977 Decl *Field = Actions.ActOnIvar(
1978 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1979 FD.BitfieldSize, visibility);
1980 Actions.ActOnObjCContainerFinishDefinition();
1982 AllIvarDecls.push_back(Field);
1986 // Parse all the comma separated declarators.
1987 ParsingDeclSpec DS(*this);
1988 ParseStructDeclaration(DS, ObjCIvarCallback);
1990 if (Tok.is(tok::semi)) {
1993 Diag(Tok, diag::err_expected_semi_decl_list);
1994 // Skip to end of block or statement
1995 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1998 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1999 T, AllIvarDecls, false);
2002 /// objc-protocol-declaration:
2003 /// objc-protocol-definition
2004 /// objc-protocol-forward-reference
2006 /// objc-protocol-definition:
2007 /// \@protocol identifier
2008 /// objc-protocol-refs[opt]
2009 /// objc-interface-decl-list
2012 /// objc-protocol-forward-reference:
2013 /// \@protocol identifier-list ';'
2015 /// "\@protocol identifier ;" should be resolved as "\@protocol
2016 /// identifier-list ;": objc-interface-decl-list may not start with a
2017 /// semicolon in the first alternative if objc-protocol-refs are omitted.
2018 Parser::DeclGroupPtrTy
2019 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2020 ParsedAttributes &attrs) {
2021 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2022 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2023 ConsumeToken(); // the "protocol" identifier
2025 if (Tok.is(tok::code_completion)) {
2026 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2031 MaybeSkipAttributes(tok::objc_protocol);
2033 if (expectIdentifier())
2034 return nullptr; // missing protocol name.
2035 // Save the protocol name, then consume it.
2036 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2037 SourceLocation nameLoc = ConsumeToken();
2039 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2040 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2041 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo,
2045 CheckNestedObjCContexts(AtLoc);
2047 if (Tok.is(tok::comma)) { // list of forward declarations.
2048 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2049 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2051 // Parse the list of forward declarations.
2053 ConsumeToken(); // the ','
2054 if (expectIdentifier()) {
2055 SkipUntil(tok::semi);
2058 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2059 Tok.getLocation()));
2060 ConsumeToken(); // the identifier
2062 if (Tok.isNot(tok::comma))
2066 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2069 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs,
2073 // Last, and definitely not least, parse a protocol declaration.
2074 SourceLocation LAngleLoc, EndProtoLoc;
2076 SmallVector<Decl *, 8> ProtocolRefs;
2077 SmallVector<SourceLocation, 8> ProtocolLocs;
2078 if (Tok.is(tok::less) &&
2079 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2080 LAngleLoc, EndProtoLoc,
2081 /*consumeLastToken=*/true))
2085 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
2086 ProtocolRefs.data(),
2087 ProtocolRefs.size(),
2088 ProtocolLocs.data(),
2089 EndProtoLoc, attrs.getList());
2091 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2092 return Actions.ConvertDeclToDeclGroup(ProtoType);
2095 /// objc-implementation:
2096 /// objc-class-implementation-prologue
2097 /// objc-category-implementation-prologue
2099 /// objc-class-implementation-prologue:
2100 /// @implementation identifier objc-superclass[opt]
2101 /// objc-class-instance-variables[opt]
2103 /// objc-category-implementation-prologue:
2104 /// @implementation identifier ( identifier )
2105 Parser::DeclGroupPtrTy
2106 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
2107 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2108 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2109 CheckNestedObjCContexts(AtLoc);
2110 ConsumeToken(); // the "implementation" identifier
2112 // Code completion after '@implementation'.
2113 if (Tok.is(tok::code_completion)) {
2114 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2119 MaybeSkipAttributes(tok::objc_implementation);
2121 if (expectIdentifier())
2122 return nullptr; // missing class or category name.
2123 // We have a class or category name - consume it.
2124 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2125 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2126 Decl *ObjCImpDecl = nullptr;
2128 // Neither a type parameter list nor a list of protocol references is
2129 // permitted here. Parse and diagnose them.
2130 if (Tok.is(tok::less)) {
2131 SourceLocation lAngleLoc, rAngleLoc;
2132 SmallVector<IdentifierLocPair, 8> protocolIdents;
2133 SourceLocation diagLoc = Tok.getLocation();
2134 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2135 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2136 protocolIdents, rAngleLoc)) {
2137 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2138 << SourceRange(diagLoc, PrevTokLocation);
2139 } else if (lAngleLoc.isValid()) {
2140 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2141 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2145 if (Tok.is(tok::l_paren)) {
2146 // we have a category implementation.
2148 SourceLocation categoryLoc, rparenLoc;
2149 IdentifierInfo *categoryId = nullptr;
2151 if (Tok.is(tok::code_completion)) {
2152 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2157 if (Tok.is(tok::identifier)) {
2158 categoryId = Tok.getIdentifierInfo();
2159 categoryLoc = ConsumeToken();
2161 Diag(Tok, diag::err_expected)
2162 << tok::identifier; // missing category name.
2165 if (Tok.isNot(tok::r_paren)) {
2166 Diag(Tok, diag::err_expected) << tok::r_paren;
2167 SkipUntil(tok::r_paren); // don't stop at ';'
2170 rparenLoc = ConsumeParen();
2171 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2172 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2173 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2174 SmallVector<Decl *, 4> protocols;
2175 SmallVector<SourceLocation, 4> protocolLocs;
2176 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2177 /*warnOnIncompleteProtocols=*/false,
2178 /*ForObjCContainer=*/false,
2179 protocolLAngleLoc, protocolRAngleLoc,
2180 /*consumeLastToken=*/true);
2182 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2183 AtLoc, nameId, nameLoc, categoryId,
2187 // We have a class implementation
2188 SourceLocation superClassLoc;
2189 IdentifierInfo *superClassId = nullptr;
2190 if (TryConsumeToken(tok::colon)) {
2191 // We have a super class
2192 if (expectIdentifier())
2193 return nullptr; // missing super class name.
2194 superClassId = Tok.getIdentifierInfo();
2195 superClassLoc = ConsumeToken(); // Consume super class name
2197 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2198 AtLoc, nameId, nameLoc,
2199 superClassId, superClassLoc);
2201 if (Tok.is(tok::l_brace)) // we have ivars
2202 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2203 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2204 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2206 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2207 SmallVector<Decl *, 4> protocols;
2208 SmallVector<SourceLocation, 4> protocolLocs;
2209 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2210 /*warnOnIncompleteProtocols=*/false,
2211 /*ForObjCContainer=*/false,
2212 protocolLAngleLoc, protocolRAngleLoc,
2213 /*consumeLastToken=*/true);
2216 assert(ObjCImpDecl);
2218 SmallVector<Decl *, 8> DeclsInGroup;
2221 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2222 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2223 ParsedAttributesWithRange attrs(AttrFactory);
2224 MaybeParseCXX11Attributes(attrs);
2225 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2226 DeclGroupRef DG = DGP.get();
2227 DeclsInGroup.append(DG.begin(), DG.end());
2232 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2235 Parser::DeclGroupPtrTy
2236 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2237 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2238 "ParseObjCAtEndDeclaration(): Expected @end");
2239 ConsumeToken(); // the "end" identifier
2240 if (CurParsedObjCImpl)
2241 CurParsedObjCImpl->finish(atEnd);
2243 // missing @implementation
2244 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2248 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2250 finish(P.Tok.getLocation());
2251 if (P.isEofOrEom()) {
2252 P.Diag(P.Tok, diag::err_objc_missing_end)
2253 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2254 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
2255 << Sema::OCK_Implementation;
2258 P.CurParsedObjCImpl = nullptr;
2259 assert(LateParsedObjCMethods.empty());
2262 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2264 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2265 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2266 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2269 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2272 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2273 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2274 false/*c-functions*/);
2276 /// \brief Clear and free the cached objc methods.
2277 for (LateParsedObjCMethodContainer::iterator
2278 I = LateParsedObjCMethods.begin(),
2279 E = LateParsedObjCMethods.end(); I != E; ++I)
2281 LateParsedObjCMethods.clear();
2286 /// compatibility-alias-decl:
2287 /// @compatibility_alias alias-name class-name ';'
2289 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2290 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2291 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2292 ConsumeToken(); // consume compatibility_alias
2293 if (expectIdentifier())
2295 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2296 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2297 if (expectIdentifier())
2299 IdentifierInfo *classId = Tok.getIdentifierInfo();
2300 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2301 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2302 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2306 /// property-synthesis:
2307 /// @synthesize property-ivar-list ';'
2309 /// property-ivar-list:
2311 /// property-ivar-list ',' property-ivar
2315 /// identifier '=' identifier
2317 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2318 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2319 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2320 ConsumeToken(); // consume synthesize
2323 if (Tok.is(tok::code_completion)) {
2324 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2329 if (Tok.isNot(tok::identifier)) {
2330 Diag(Tok, diag::err_synthesized_property_name);
2331 SkipUntil(tok::semi);
2335 IdentifierInfo *propertyIvar = nullptr;
2336 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2337 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2338 SourceLocation propertyIvarLoc;
2339 if (TryConsumeToken(tok::equal)) {
2340 // property '=' ivar-name
2341 if (Tok.is(tok::code_completion)) {
2342 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2347 if (expectIdentifier())
2349 propertyIvar = Tok.getIdentifierInfo();
2350 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2352 Actions.ActOnPropertyImplDecl(
2353 getCurScope(), atLoc, propertyLoc, true,
2354 propertyId, propertyIvar, propertyIvarLoc,
2355 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2356 if (Tok.isNot(tok::comma))
2358 ConsumeToken(); // consume ','
2360 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2364 /// property-dynamic:
2365 /// @dynamic property-list
2369 /// property-list ',' identifier
2371 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2372 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2373 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2374 ConsumeToken(); // consume dynamic
2376 bool isClassProperty = false;
2377 if (Tok.is(tok::l_paren)) {
2379 const IdentifierInfo *II = Tok.getIdentifierInfo();
2382 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2383 SkipUntil(tok::r_paren, StopAtSemi);
2385 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2386 if (II->isStr("class")) {
2387 isClassProperty = true;
2388 if (Tok.isNot(tok::r_paren)) {
2389 Diag(Tok, diag::err_expected) << tok::r_paren;
2390 SkipUntil(tok::r_paren, StopAtSemi);
2394 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2395 SkipUntil(tok::r_paren, StopAtSemi);
2401 if (Tok.is(tok::code_completion)) {
2402 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2407 if (expectIdentifier()) {
2408 SkipUntil(tok::semi);
2412 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2413 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2414 Actions.ActOnPropertyImplDecl(
2415 getCurScope(), atLoc, propertyLoc, false,
2416 propertyId, nullptr, SourceLocation(),
2417 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2418 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2420 if (Tok.isNot(tok::comma))
2422 ConsumeToken(); // consume ','
2424 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2428 /// objc-throw-statement:
2429 /// throw expression[opt];
2431 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2433 ConsumeToken(); // consume throw
2434 if (Tok.isNot(tok::semi)) {
2435 Res = ParseExpression();
2436 if (Res.isInvalid()) {
2437 SkipUntil(tok::semi);
2442 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2443 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2446 /// objc-synchronized-statement:
2447 /// @synchronized '(' expression ')' compound-statement
2450 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2451 ConsumeToken(); // consume synchronized
2452 if (Tok.isNot(tok::l_paren)) {
2453 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2457 // The operand is surrounded with parentheses.
2458 ConsumeParen(); // '('
2459 ExprResult operand(ParseExpression());
2461 if (Tok.is(tok::r_paren)) {
2462 ConsumeParen(); // ')'
2464 if (!operand.isInvalid())
2465 Diag(Tok, diag::err_expected) << tok::r_paren;
2467 // Skip forward until we see a left brace, but don't consume it.
2468 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2471 // Require a compound statement.
2472 if (Tok.isNot(tok::l_brace)) {
2473 if (!operand.isInvalid())
2474 Diag(Tok, diag::err_expected) << tok::l_brace;
2478 // Check the @synchronized operand now.
2479 if (!operand.isInvalid())
2480 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2482 // Parse the compound statement within a new scope.
2483 ParseScope bodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2484 StmtResult body(ParseCompoundStatementBody());
2487 // If there was a semantic or parse error earlier with the
2488 // operand, fail now.
2489 if (operand.isInvalid())
2492 if (body.isInvalid())
2493 body = Actions.ActOnNullStmt(Tok.getLocation());
2495 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2498 /// objc-try-catch-statement:
2499 /// @try compound-statement objc-catch-list[opt]
2500 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2502 /// objc-catch-list:
2503 /// @catch ( parameter-declaration ) compound-statement
2504 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2505 /// catch-parameter-declaration:
2506 /// parameter-declaration
2509 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2510 bool catch_or_finally_seen = false;
2512 ConsumeToken(); // consume try
2513 if (Tok.isNot(tok::l_brace)) {
2514 Diag(Tok, diag::err_expected) << tok::l_brace;
2517 StmtVector CatchStmts;
2518 StmtResult FinallyStmt;
2519 ParseScope TryScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2520 StmtResult TryBody(ParseCompoundStatementBody());
2522 if (TryBody.isInvalid())
2523 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2525 while (Tok.is(tok::at)) {
2526 // At this point, we need to lookahead to determine if this @ is the start
2527 // of an @catch or @finally. We don't want to consume the @ token if this
2528 // is an @try or @encode or something else.
2529 Token AfterAt = GetLookAheadToken(1);
2530 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2531 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2534 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2535 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2536 Decl *FirstPart = nullptr;
2537 ConsumeToken(); // consume catch
2538 if (Tok.is(tok::l_paren)) {
2540 ParseScope CatchScope(this, Scope::DeclScope |
2541 Scope::CompoundStmtScope |
2542 Scope::AtCatchScope);
2543 if (Tok.isNot(tok::ellipsis)) {
2544 DeclSpec DS(AttrFactory);
2545 ParseDeclarationSpecifiers(DS);
2546 Declarator ParmDecl(DS, DeclaratorContext::ObjCCatchContext);
2547 ParseDeclarator(ParmDecl);
2549 // Inform the actions module about the declarator, so it
2550 // gets added to the current scope.
2551 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2553 ConsumeToken(); // consume '...'
2555 SourceLocation RParenLoc;
2557 if (Tok.is(tok::r_paren))
2558 RParenLoc = ConsumeParen();
2559 else // Skip over garbage, until we get to ')'. Eat the ')'.
2560 SkipUntil(tok::r_paren, StopAtSemi);
2562 StmtResult CatchBody(true);
2563 if (Tok.is(tok::l_brace))
2564 CatchBody = ParseCompoundStatementBody();
2566 Diag(Tok, diag::err_expected) << tok::l_brace;
2567 if (CatchBody.isInvalid())
2568 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2570 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2574 if (!Catch.isInvalid())
2575 CatchStmts.push_back(Catch.get());
2578 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2582 catch_or_finally_seen = true;
2584 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2585 ConsumeToken(); // consume finally
2586 ParseScope FinallyScope(this,
2587 Scope::DeclScope | Scope::CompoundStmtScope);
2589 StmtResult FinallyBody(true);
2590 if (Tok.is(tok::l_brace))
2591 FinallyBody = ParseCompoundStatementBody();
2593 Diag(Tok, diag::err_expected) << tok::l_brace;
2594 if (FinallyBody.isInvalid())
2595 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2596 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2598 catch_or_finally_seen = true;
2602 if (!catch_or_finally_seen) {
2603 Diag(atLoc, diag::err_missing_catch_finally);
2607 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2612 /// objc-autoreleasepool-statement:
2613 /// @autoreleasepool compound-statement
2616 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2617 ConsumeToken(); // consume autoreleasepool
2618 if (Tok.isNot(tok::l_brace)) {
2619 Diag(Tok, diag::err_expected) << tok::l_brace;
2622 // Enter a scope to hold everything within the compound stmt. Compound
2623 // statements can always hold declarations.
2624 ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2626 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2629 if (AutoreleasePoolBody.isInvalid())
2630 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2631 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2632 AutoreleasePoolBody.get());
2635 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2636 /// for later parsing.
2637 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2638 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2639 trySkippingFunctionBody()) {
2640 Actions.ActOnSkippedFunctionBody(MDecl);
2644 LexedMethod* LM = new LexedMethod(this, MDecl);
2645 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2646 CachedTokens &Toks = LM->Toks;
2647 // Begin by storing the '{' or 'try' or ':' token.
2648 Toks.push_back(Tok);
2649 if (Tok.is(tok::kw_try)) {
2651 if (Tok.is(tok::colon)) {
2652 Toks.push_back(Tok);
2654 while (Tok.isNot(tok::l_brace)) {
2655 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2656 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2659 Toks.push_back(Tok); // also store '{'
2661 else if (Tok.is(tok::colon)) {
2663 // FIXME: This is wrong, due to C++11 braced initialization.
2664 while (Tok.isNot(tok::l_brace)) {
2665 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2666 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2668 Toks.push_back(Tok); // also store '{'
2671 // Consume everything up to (and including) the matching right brace.
2672 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2673 while (Tok.is(tok::kw_catch)) {
2674 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2675 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2679 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2681 Decl *Parser::ParseObjCMethodDefinition() {
2682 Decl *MDecl = ParseObjCMethodPrototype();
2684 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2685 "parsing Objective-C method");
2687 // parse optional ';'
2688 if (Tok.is(tok::semi)) {
2689 if (CurParsedObjCImpl) {
2690 Diag(Tok, diag::warn_semicolon_before_method_body)
2691 << FixItHint::CreateRemoval(Tok.getLocation());
2696 // We should have an opening brace now.
2697 if (Tok.isNot(tok::l_brace)) {
2698 Diag(Tok, diag::err_expected_method_body);
2700 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2701 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2703 // If we didn't find the '{', bail out.
2704 if (Tok.isNot(tok::l_brace))
2710 SkipUntil(tok::r_brace);
2714 // Allow the rest of sema to find private method decl implementations.
2715 Actions.AddAnyMethodToGlobalPool(MDecl);
2716 assert (CurParsedObjCImpl
2717 && "ParseObjCMethodDefinition - Method out of @implementation");
2718 // Consume the tokens and store them for later parsing.
2719 StashAwayMethodOrFunctionBodyTokens(MDecl);
2723 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2724 if (Tok.is(tok::code_completion)) {
2725 Actions.CodeCompleteObjCAtStatement(getCurScope());
2730 if (Tok.isObjCAtKeyword(tok::objc_try))
2731 return ParseObjCTryStmt(AtLoc);
2733 if (Tok.isObjCAtKeyword(tok::objc_throw))
2734 return ParseObjCThrowStmt(AtLoc);
2736 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2737 return ParseObjCSynchronizedStmt(AtLoc);
2739 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2740 return ParseObjCAutoreleasePoolStmt(AtLoc);
2742 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2743 getLangOpts().DebuggerSupport) {
2744 SkipUntil(tok::semi);
2745 return Actions.ActOnNullStmt(Tok.getLocation());
2748 ExprStatementTokLoc = AtLoc;
2749 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2750 if (Res.isInvalid()) {
2751 // If the expression is invalid, skip ahead to the next semicolon. Not
2752 // doing this opens us up to the possibility of infinite loops if
2753 // ParseExpression does not consume any tokens.
2754 SkipUntil(tok::semi);
2758 // Otherwise, eat the semicolon.
2759 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2760 return Actions.ActOnExprStmt(Res);
2763 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2764 switch (Tok.getKind()) {
2765 case tok::code_completion:
2766 Actions.CodeCompleteObjCAtExpression(getCurScope());
2772 tok::TokenKind Kind = Tok.getKind();
2773 SourceLocation OpLoc = ConsumeToken();
2775 if (!Tok.is(tok::numeric_constant)) {
2776 const char *Symbol = nullptr;
2778 case tok::minus: Symbol = "-"; break;
2779 case tok::plus: Symbol = "+"; break;
2780 default: llvm_unreachable("missing unary operator case");
2782 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2787 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2788 if (Lit.isInvalid()) {
2791 ConsumeToken(); // Consume the literal token.
2793 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2794 if (Lit.isInvalid())
2797 return ParsePostfixExpressionSuffix(
2798 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2801 case tok::string_literal: // primary-expression: string-literal
2802 case tok::wide_string_literal:
2803 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2805 case tok::char_constant:
2806 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2808 case tok::numeric_constant:
2809 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2811 case tok::kw_true: // Objective-C++, etc.
2812 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2813 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2814 case tok::kw_false: // Objective-C++, etc.
2815 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2816 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2819 // Objective-C array literal
2820 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2823 // Objective-C dictionary literal
2824 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2827 // Objective-C boxed expression
2828 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2831 if (Tok.getIdentifierInfo() == nullptr)
2832 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2834 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2835 case tok::objc_encode:
2836 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2837 case tok::objc_protocol:
2838 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2839 case tok::objc_selector:
2840 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2841 case tok::objc_available:
2842 return ParseAvailabilityCheckExpr(AtLoc);
2844 const char *str = nullptr;
2845 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2846 // that this is a proper statement where such directives could actually
2848 if (GetLookAheadToken(1).is(tok::l_brace) &&
2849 ExprStatementTokLoc == AtLoc) {
2850 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2853 : (ch == 'f' ? "finally"
2854 : (ch == 'a' ? "autoreleasepool" : nullptr));
2857 SourceLocation kwLoc = Tok.getLocation();
2858 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2859 FixItHint::CreateReplacement(kwLoc, str));
2862 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2868 /// \brief Parse the receiver of an Objective-C++ message send.
2870 /// This routine parses the receiver of a message send in
2871 /// Objective-C++ either as a type or as an expression. Note that this
2872 /// routine must not be called to parse a send to 'super', since it
2873 /// has no way to return such a result.
2875 /// \param IsExpr Whether the receiver was parsed as an expression.
2877 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2878 /// IsExpr is true), the parsed expression. If the receiver was parsed
2879 /// as a type (\c IsExpr is false), the parsed type.
2881 /// \returns True if an error occurred during parsing or semantic
2882 /// analysis, in which case the arguments do not have valid
2883 /// values. Otherwise, returns false for a successful parse.
2885 /// objc-receiver: [C++]
2886 /// 'super' [not parsed here]
2888 /// simple-type-specifier
2889 /// typename-specifier
2890 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2891 InMessageExpressionRAIIObject InMessage(*this, true);
2893 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2894 tok::annot_cxxscope))
2895 TryAnnotateTypeOrScopeToken();
2897 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2900 // Make sure any typos in the receiver are corrected or diagnosed, so that
2901 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2902 // only the things that are valid ObjC receivers?
2903 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2904 if (Receiver.isInvalid())
2908 TypeOrExpr = Receiver.get();
2913 // typename-specifier
2914 // simple-type-specifier
2915 // expression (that starts with one of the above)
2916 DeclSpec DS(AttrFactory);
2917 ParseCXXSimpleTypeSpecifier(DS);
2919 if (Tok.is(tok::l_paren)) {
2920 // If we see an opening parentheses at this point, we are
2921 // actually parsing an expression that starts with a
2922 // function-style cast, e.g.,
2924 // postfix-expression:
2925 // simple-type-specifier ( expression-list [opt] )
2926 // typename-specifier ( expression-list [opt] )
2928 // Parse the remainder of this case, then the (optional)
2929 // postfix-expression suffix, followed by the (optional)
2930 // right-hand side of the binary expression. We have an
2932 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2933 if (!Receiver.isInvalid())
2934 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2935 if (!Receiver.isInvalid())
2936 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2937 if (Receiver.isInvalid())
2941 TypeOrExpr = Receiver.get();
2945 // We have a class message. Turn the simple-type-specifier or
2946 // typename-specifier we parsed into a type and parse the
2947 // remainder of the class message.
2948 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2949 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2950 if (Type.isInvalid())
2954 TypeOrExpr = Type.get().getAsOpaquePtr();
2958 /// \brief Determine whether the parser is currently referring to a an
2959 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2961 /// This routine will only return true for a subset of valid message-send
2963 bool Parser::isSimpleObjCMessageExpression() {
2964 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2965 "Incorrect start for isSimpleObjCMessageExpression");
2966 return GetLookAheadToken(1).is(tok::identifier) &&
2967 GetLookAheadToken(2).is(tok::identifier);
2970 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2971 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2972 InMessageExpression)
2977 if (Tok.is(tok::annot_typename))
2978 Type = getTypeAnnotation(Tok);
2979 else if (Tok.is(tok::identifier))
2980 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2985 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2986 const Token &AfterNext = GetLookAheadToken(2);
2987 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2988 if (Tok.is(tok::identifier))
2989 TryAnnotateTypeOrScopeToken();
2991 return Tok.is(tok::annot_typename);
2998 /// objc-message-expr:
2999 /// '[' objc-receiver objc-message-args ']'
3001 /// objc-receiver: [C]
3007 ExprResult Parser::ParseObjCMessageExpression() {
3008 assert(Tok.is(tok::l_square) && "'[' expected");
3009 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3011 if (Tok.is(tok::code_completion)) {
3012 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3017 InMessageExpressionRAIIObject InMessage(*this, true);
3019 if (getLangOpts().CPlusPlus) {
3020 // We completely separate the C and C++ cases because C++ requires
3021 // more complicated (read: slower) parsing.
3023 // Handle send to super.
3024 // FIXME: This doesn't benefit from the same typo-correction we
3025 // get in Objective-C.
3026 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3027 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3028 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3031 // Parse the receiver, which is either a type or an expression.
3033 void *TypeOrExpr = nullptr;
3034 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3035 SkipUntil(tok::r_square, StopAtSemi);
3040 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3041 static_cast<Expr *>(TypeOrExpr));
3043 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3044 ParsedType::getFromOpaquePtr(TypeOrExpr),
3048 if (Tok.is(tok::identifier)) {
3049 IdentifierInfo *Name = Tok.getIdentifierInfo();
3050 SourceLocation NameLoc = Tok.getLocation();
3051 ParsedType ReceiverType;
3052 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3053 Name == Ident_super,
3054 NextToken().is(tok::period),
3056 case Sema::ObjCSuperMessage:
3057 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3060 case Sema::ObjCClassMessage:
3061 if (!ReceiverType) {
3062 SkipUntil(tok::r_square, StopAtSemi);
3066 ConsumeToken(); // the type name
3068 // Parse type arguments and protocol qualifiers.
3069 if (Tok.is(tok::less)) {
3070 SourceLocation NewEndLoc;
3071 TypeResult NewReceiverType
3072 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3073 /*consumeLastToken=*/true,
3075 if (!NewReceiverType.isUsable()) {
3076 SkipUntil(tok::r_square, StopAtSemi);
3080 ReceiverType = NewReceiverType.get();
3083 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3084 ReceiverType, nullptr);
3086 case Sema::ObjCInstanceMessage:
3087 // Fall through to parse an expression.
3092 // Otherwise, an arbitrary expression can be the receiver of a send.
3093 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3094 if (Res.isInvalid()) {
3095 SkipUntil(tok::r_square, StopAtSemi);
3099 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3103 /// \brief Parse the remainder of an Objective-C message following the
3104 /// '[' objc-receiver.
3106 /// This routine handles sends to super, class messages (sent to a
3107 /// class name), and instance messages (sent to an object), and the
3108 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3109 /// ReceiverExpr, respectively. Only one of these parameters may have
3112 /// \param LBracLoc The location of the opening '['.
3114 /// \param SuperLoc If this is a send to 'super', the location of the
3115 /// 'super' keyword that indicates a send to the superclass.
3117 /// \param ReceiverType If this is a class message, the type of the
3118 /// class we are sending a message to.
3120 /// \param ReceiverExpr If this is an instance message, the expression
3121 /// used to compute the receiver object.
3123 /// objc-message-args:
3125 /// objc-keywordarg-list
3127 /// objc-keywordarg-list:
3129 /// objc-keywordarg-list objc-keywordarg
3131 /// objc-keywordarg:
3132 /// selector-name[opt] ':' objc-keywordexpr
3134 /// objc-keywordexpr:
3135 /// nonempty-expr-list
3137 /// nonempty-expr-list:
3138 /// assignment-expression
3139 /// nonempty-expr-list , assignment-expression
3142 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3143 SourceLocation SuperLoc,
3144 ParsedType ReceiverType,
3145 Expr *ReceiverExpr) {
3146 InMessageExpressionRAIIObject InMessage(*this, true);
3148 if (Tok.is(tok::code_completion)) {
3149 if (SuperLoc.isValid())
3150 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3152 else if (ReceiverType)
3153 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3156 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3162 // Parse objc-selector
3164 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3166 SmallVector<IdentifierInfo *, 12> KeyIdents;
3167 SmallVector<SourceLocation, 12> KeyLocs;
3168 ExprVector KeyExprs;
3170 if (Tok.is(tok::colon)) {
3172 // Each iteration parses a single keyword argument.
3173 KeyIdents.push_back(selIdent);
3174 KeyLocs.push_back(Loc);
3176 if (ExpectAndConsume(tok::colon)) {
3177 // We must manually skip to a ']', otherwise the expression skipper will
3178 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3179 // the enclosing expression.
3180 SkipUntil(tok::r_square, StopAtSemi);
3184 /// Parse the expression after ':'
3186 if (Tok.is(tok::code_completion)) {
3187 if (SuperLoc.isValid())
3188 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3190 /*AtArgumentEpression=*/true);
3191 else if (ReceiverType)
3192 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3194 /*AtArgumentEpression=*/true);
3196 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3198 /*AtArgumentEpression=*/true);
3205 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3206 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3207 Expr = ParseBraceInitializer();
3209 Expr = ParseAssignmentExpression();
3211 ExprResult Res(Expr);
3212 if (Res.isInvalid()) {
3213 // We must manually skip to a ']', otherwise the expression skipper will
3214 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3215 // the enclosing expression.
3216 SkipUntil(tok::r_square, StopAtSemi);
3220 // We have a valid expression.
3221 KeyExprs.push_back(Res.get());
3223 // Code completion after each argument.
3224 if (Tok.is(tok::code_completion)) {
3225 if (SuperLoc.isValid())
3226 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3228 /*AtArgumentEpression=*/false);
3229 else if (ReceiverType)
3230 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3232 /*AtArgumentEpression=*/false);
3234 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3236 /*AtArgumentEpression=*/false);
3241 // Check for another keyword selector.
3242 selIdent = ParseObjCSelectorPiece(Loc);
3243 if (!selIdent && Tok.isNot(tok::colon))
3245 // We have a selector or a colon, continue parsing.
3247 // Parse the, optional, argument list, comma separated.
3248 while (Tok.is(tok::comma)) {
3249 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3250 /// Parse the expression after ','
3251 ExprResult Res(ParseAssignmentExpression());
3252 if (Tok.is(tok::colon))
3253 Res = Actions.CorrectDelayedTyposInExpr(Res);
3254 if (Res.isInvalid()) {
3255 if (Tok.is(tok::colon)) {
3256 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3257 FixItHint::CreateRemoval(commaLoc);
3259 // We must manually skip to a ']', otherwise the expression skipper will
3260 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3261 // the enclosing expression.
3262 SkipUntil(tok::r_square, StopAtSemi);
3266 // We have a valid expression.
3267 KeyExprs.push_back(Res.get());
3269 } else if (!selIdent) {
3270 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3272 // We must manually skip to a ']', otherwise the expression skipper will
3273 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3274 // the enclosing expression.
3275 SkipUntil(tok::r_square, StopAtSemi);
3279 if (Tok.isNot(tok::r_square)) {
3280 Diag(Tok, diag::err_expected)
3281 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3282 // We must manually skip to a ']', otherwise the expression skipper will
3283 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3284 // the enclosing expression.
3285 SkipUntil(tok::r_square, StopAtSemi);
3289 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3291 unsigned nKeys = KeyIdents.size();
3293 KeyIdents.push_back(selIdent);
3294 KeyLocs.push_back(Loc);
3296 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3298 if (SuperLoc.isValid())
3299 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3300 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3301 else if (ReceiverType)
3302 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3303 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3304 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3305 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3308 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3309 ExprResult Res(ParseStringLiteralExpression());
3310 if (Res.isInvalid()) return Res;
3312 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3313 // expressions. At this point, we know that the only valid thing that starts
3314 // with '@' is an @"".
3315 SmallVector<SourceLocation, 4> AtLocs;
3316 ExprVector AtStrings;
3317 AtLocs.push_back(AtLoc);
3318 AtStrings.push_back(Res.get());
3320 while (Tok.is(tok::at)) {
3321 AtLocs.push_back(ConsumeToken()); // eat the @.
3323 // Invalid unless there is a string literal.
3324 if (!isTokenStringLiteral())
3325 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3327 ExprResult Lit(ParseStringLiteralExpression());
3328 if (Lit.isInvalid())
3331 AtStrings.push_back(Lit.get());
3334 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3337 /// ParseObjCBooleanLiteral -
3338 /// objc-scalar-literal : '@' boolean-keyword
3340 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3342 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3344 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3345 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3348 /// ParseObjCCharacterLiteral -
3349 /// objc-scalar-literal : '@' character-literal
3351 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3352 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3353 if (Lit.isInvalid()) {
3356 ConsumeToken(); // Consume the literal token.
3357 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3360 /// ParseObjCNumericLiteral -
3361 /// objc-scalar-literal : '@' scalar-literal
3363 /// scalar-literal : | numeric-constant /* any numeric constant. */
3365 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3366 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3367 if (Lit.isInvalid()) {
3370 ConsumeToken(); // Consume the literal token.
3371 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3374 /// ParseObjCBoxedExpr -
3375 /// objc-box-expression:
3376 /// @( assignment-expression )
3378 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3379 if (Tok.isNot(tok::l_paren))
3380 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3382 BalancedDelimiterTracker T(*this, tok::l_paren);
3384 ExprResult ValueExpr(ParseAssignmentExpression());
3385 if (T.consumeClose())
3388 if (ValueExpr.isInvalid())
3391 // Wrap the sub-expression in a parenthesized expression, to distinguish
3392 // a boxed expression from a literal.
3393 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3394 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3395 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3399 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3400 ExprVector ElementExprs; // array elements.
3401 ConsumeBracket(); // consume the l_square.
3403 bool HasInvalidEltExpr = false;
3404 while (Tok.isNot(tok::r_square)) {
3405 // Parse list of array element expressions (all must be id types).
3406 ExprResult Res(ParseAssignmentExpression());
3407 if (Res.isInvalid()) {
3408 // We must manually skip to a ']', otherwise the expression skipper will
3409 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3410 // the enclosing expression.
3411 SkipUntil(tok::r_square, StopAtSemi);
3415 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3416 if (Res.isInvalid())
3417 HasInvalidEltExpr = true;
3419 // Parse the ellipsis that indicates a pack expansion.
3420 if (Tok.is(tok::ellipsis))
3421 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3422 if (Res.isInvalid())
3423 HasInvalidEltExpr = true;
3425 ElementExprs.push_back(Res.get());
3427 if (Tok.is(tok::comma))
3428 ConsumeToken(); // Eat the ','.
3429 else if (Tok.isNot(tok::r_square))
3430 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3433 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3435 if (HasInvalidEltExpr)
3438 MultiExprArg Args(ElementExprs);
3439 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3442 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3443 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3444 ConsumeBrace(); // consume the l_square.
3445 bool HasInvalidEltExpr = false;
3446 while (Tok.isNot(tok::r_brace)) {
3447 // Parse the comma separated key : value expressions.
3450 ColonProtectionRAIIObject X(*this);
3451 KeyExpr = ParseAssignmentExpression();
3452 if (KeyExpr.isInvalid()) {
3453 // We must manually skip to a '}', otherwise the expression skipper will
3454 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3455 // the enclosing expression.
3456 SkipUntil(tok::r_brace, StopAtSemi);
3461 if (ExpectAndConsume(tok::colon)) {
3462 SkipUntil(tok::r_brace, StopAtSemi);
3466 ExprResult ValueExpr(ParseAssignmentExpression());
3467 if (ValueExpr.isInvalid()) {
3468 // We must manually skip to a '}', otherwise the expression skipper will
3469 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3470 // the enclosing expression.
3471 SkipUntil(tok::r_brace, StopAtSemi);
3475 // Check the key and value for possible typos
3476 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3477 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3478 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3479 HasInvalidEltExpr = true;
3481 // Parse the ellipsis that designates this as a pack expansion. Do not
3482 // ActOnPackExpansion here, leave it to template instantiation time where
3483 // we can get better diagnostics.
3484 SourceLocation EllipsisLoc;
3485 if (getLangOpts().CPlusPlus)
3486 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3488 // We have a valid expression. Collect it in a vector so we can
3489 // build the argument list.
3490 ObjCDictionaryElement Element = {
3491 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3493 Elements.push_back(Element);
3495 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3496 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3499 SourceLocation EndLoc = ConsumeBrace();
3501 if (HasInvalidEltExpr)
3504 // Create the ObjCDictionaryLiteral.
3505 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3509 /// objc-encode-expression:
3510 /// \@encode ( type-name )
3512 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3513 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3515 SourceLocation EncLoc = ConsumeToken();
3517 if (Tok.isNot(tok::l_paren))
3518 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3520 BalancedDelimiterTracker T(*this, tok::l_paren);
3523 TypeResult Ty = ParseTypeName();
3530 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3531 Ty.get(), T.getCloseLocation());
3534 /// objc-protocol-expression
3535 /// \@protocol ( protocol-name )
3537 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3538 SourceLocation ProtoLoc = ConsumeToken();
3540 if (Tok.isNot(tok::l_paren))
3541 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3543 BalancedDelimiterTracker T(*this, tok::l_paren);
3546 if (expectIdentifier())
3549 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3550 SourceLocation ProtoIdLoc = ConsumeToken();
3554 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3555 T.getOpenLocation(), ProtoIdLoc,
3556 T.getCloseLocation());
3559 /// objc-selector-expression
3560 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3561 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3562 SourceLocation SelectorLoc = ConsumeToken();
3564 if (Tok.isNot(tok::l_paren))
3565 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3567 SmallVector<IdentifierInfo *, 12> KeyIdents;
3568 SourceLocation sLoc;
3570 BalancedDelimiterTracker T(*this, tok::l_paren);
3572 bool HasOptionalParen = Tok.is(tok::l_paren);
3573 if (HasOptionalParen)
3576 if (Tok.is(tok::code_completion)) {
3577 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3582 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3583 if (!SelIdent && // missing selector name.
3584 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3585 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3587 KeyIdents.push_back(SelIdent);
3589 unsigned nColons = 0;
3590 if (Tok.isNot(tok::r_paren)) {
3592 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3594 KeyIdents.push_back(nullptr);
3595 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3599 if (Tok.is(tok::r_paren))
3602 if (Tok.is(tok::code_completion)) {
3603 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3608 // Check for another keyword selector.
3610 SelIdent = ParseObjCSelectorPiece(Loc);
3611 KeyIdents.push_back(SelIdent);
3612 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3616 if (HasOptionalParen && Tok.is(tok::r_paren))
3617 ConsumeParen(); // ')'
3619 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3620 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3621 T.getOpenLocation(),
3622 T.getCloseLocation(),
3626 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3627 // MCDecl might be null due to error in method or c-function prototype, etc.
3628 Decl *MCDecl = LM.D;
3629 bool skip = MCDecl &&
3630 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3631 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3635 // Save the current token position.
3636 SourceLocation OrigLoc = Tok.getLocation();
3638 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3639 // Store an artificial EOF token to ensure that we don't run off the end of
3640 // the method's body when we come to parse it.
3643 Eof.setKind(tok::eof);
3644 Eof.setEofData(MCDecl);
3645 Eof.setLocation(OrigLoc);
3646 LM.Toks.push_back(Eof);
3647 // Append the current token at the end of the new token stream so that it
3648 // doesn't get lost.
3649 LM.Toks.push_back(Tok);
3650 PP.EnterTokenStream(LM.Toks, true);
3652 // Consume the previously pushed token.
3653 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3655 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3656 "Inline objective-c method not starting with '{' or 'try' or ':'");
3657 // Enter a scope for the method or c-function body.
3658 ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
3659 Scope::FnScope | Scope::DeclScope |
3660 Scope::CompoundStmtScope);
3662 // Tell the actions module that we have entered a method or c-function definition
3663 // with the specified Declarator for the method/function.
3665 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3667 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3668 if (Tok.is(tok::kw_try))
3669 ParseFunctionTryBlock(MCDecl, BodyScope);
3671 if (Tok.is(tok::colon))
3672 ParseConstructorInitializer(MCDecl);
3674 Actions.ActOnDefaultCtorInitializers(MCDecl);
3675 ParseFunctionStatementBody(MCDecl, BodyScope);
3678 if (Tok.getLocation() != OrigLoc) {
3679 // Due to parsing error, we either went over the cached tokens or
3680 // there are still cached tokens left. If it's the latter case skip the
3682 // Since this is an uncommon situation that should be avoided, use the
3683 // expensive isBeforeInTranslationUnit call.
3684 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3686 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3689 // Clean up the remaining EOF token.