1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Objective-C portions of the Parser interface.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/PrettyDeclStackTrace.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/Scope.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringExtras.h"
24 using namespace clang;
26 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
27 void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
28 ParsedAttributes attrs(AttrFactory);
29 if (Tok.is(tok::kw___attribute)) {
30 if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
31 Diag(Tok, diag::err_objc_postfix_attribute_hint)
32 << (Kind == tok::objc_protocol);
34 Diag(Tok, diag::err_objc_postfix_attribute);
35 ParseGNUAttributes(attrs);
39 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
40 /// external-declaration: [C99 6.9]
41 /// [OBJC] objc-class-definition
42 /// [OBJC] objc-class-declaration
43 /// [OBJC] objc-alias-declaration
44 /// [OBJC] objc-protocol-definition
45 /// [OBJC] objc-method-definition
47 Parser::DeclGroupPtrTy
48 Parser::ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs) {
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 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, Attrs);
64 case tok::objc_protocol:
65 return ParseObjCAtProtocolDeclaration(AtLoc, Attrs);
66 case tok::objc_implementation:
67 return ParseObjCAtImplementationDeclaration(AtLoc, Attrs);
69 return ParseObjCAtEndDeclaration(AtLoc);
70 case tok::objc_compatibility_alias:
71 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
73 case tok::objc_synthesize:
74 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
76 case tok::objc_dynamic:
77 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
79 case tok::objc_import:
80 if (getLangOpts().Modules || getLangOpts().DebuggerSupport) {
81 SingleDecl = ParseModuleImport(AtLoc);
84 Diag(AtLoc, diag::err_atimport);
86 return Actions.ConvertDeclToDeclGroup(nullptr);
88 Diag(AtLoc, diag::err_unexpected_at);
93 return Actions.ConvertDeclToDeclGroup(SingleDecl);
96 /// Class to handle popping type parameters when leaving the scope.
97 class Parser::ObjCTypeParamListScope {
100 ObjCTypeParamList *Params;
103 ObjCTypeParamListScope(Sema &Actions, Scope *S)
104 : Actions(Actions), S(S), Params(nullptr) {}
106 ~ObjCTypeParamListScope() {
110 void enter(ObjCTypeParamList *P) {
117 Actions.popObjCTypeParamList(S, Params);
123 /// objc-class-declaration:
124 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
126 /// objc-class-forward-decl:
127 /// identifier objc-type-parameter-list[opt]
129 Parser::DeclGroupPtrTy
130 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
131 ConsumeToken(); // the identifier "class"
132 SmallVector<IdentifierInfo *, 8> ClassNames;
133 SmallVector<SourceLocation, 8> ClassLocs;
134 SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
137 MaybeSkipAttributes(tok::objc_class);
138 if (expectIdentifier()) {
139 SkipUntil(tok::semi);
140 return Actions.ConvertDeclToDeclGroup(nullptr);
142 ClassNames.push_back(Tok.getIdentifierInfo());
143 ClassLocs.push_back(Tok.getLocation());
146 // Parse the optional objc-type-parameter-list.
147 ObjCTypeParamList *TypeParams = nullptr;
148 if (Tok.is(tok::less))
149 TypeParams = parseObjCTypeParamList();
150 ClassTypeParams.push_back(TypeParams);
151 if (!TryConsumeToken(tok::comma))
156 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
157 return Actions.ConvertDeclToDeclGroup(nullptr);
159 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
165 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
167 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
168 if (ock == Sema::OCK_None)
171 Decl *Decl = Actions.getObjCDeclContext();
172 if (CurParsedObjCImpl) {
173 CurParsedObjCImpl->finish(AtLoc);
175 Actions.ActOnAtEnd(getCurScope(), AtLoc);
177 Diag(AtLoc, diag::err_objc_missing_end)
178 << FixItHint::CreateInsertion(AtLoc, "@end\n");
180 Diag(Decl->getBeginLoc(), diag::note_objc_container_start) << (int)ock;
185 /// objc-class-interface-attributes[opt] objc-class-interface
186 /// objc-category-interface
188 /// objc-class-interface:
189 /// '@' 'interface' identifier objc-type-parameter-list[opt]
190 /// objc-superclass[opt] objc-protocol-refs[opt]
191 /// objc-class-instance-variables[opt]
192 /// objc-interface-decl-list
195 /// objc-category-interface:
196 /// '@' 'interface' identifier objc-type-parameter-list[opt]
197 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
198 /// objc-interface-decl-list
202 /// ':' identifier objc-type-arguments[opt]
204 /// objc-class-interface-attributes:
205 /// __attribute__((visibility("default")))
206 /// __attribute__((visibility("hidden")))
207 /// __attribute__((deprecated))
208 /// __attribute__((unavailable))
209 /// __attribute__((objc_exception)) - used by NSException on 64-bit
210 /// __attribute__((objc_root_class))
212 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
213 ParsedAttributes &attrs) {
214 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
215 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
216 CheckNestedObjCContexts(AtLoc);
217 ConsumeToken(); // the "interface" identifier
219 // Code completion after '@interface'.
220 if (Tok.is(tok::code_completion)) {
221 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
226 MaybeSkipAttributes(tok::objc_interface);
228 if (expectIdentifier())
229 return nullptr; // missing class or category name.
231 // We have a class or category name - consume it.
232 IdentifierInfo *nameId = Tok.getIdentifierInfo();
233 SourceLocation nameLoc = ConsumeToken();
235 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
236 // case, LAngleLoc will be valid and ProtocolIdents will capture the
237 // protocol references (that have not yet been resolved).
238 SourceLocation LAngleLoc, EndProtoLoc;
239 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
240 ObjCTypeParamList *typeParameterList = nullptr;
241 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
242 if (Tok.is(tok::less))
243 typeParameterList = parseObjCTypeParamListOrProtocolRefs(
244 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
246 if (Tok.is(tok::l_paren) &&
247 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
249 BalancedDelimiterTracker T(*this, tok::l_paren);
252 SourceLocation categoryLoc;
253 IdentifierInfo *categoryId = nullptr;
254 if (Tok.is(tok::code_completion)) {
255 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
260 // For ObjC2, the category name is optional (not an error).
261 if (Tok.is(tok::identifier)) {
262 categoryId = Tok.getIdentifierInfo();
263 categoryLoc = ConsumeToken();
265 else if (!getLangOpts().ObjC) {
266 Diag(Tok, diag::err_expected)
267 << tok::identifier; // missing category name.
272 if (T.getCloseLocation().isInvalid())
275 // Next, we need to check for any protocol references.
276 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
277 SmallVector<Decl *, 8> ProtocolRefs;
278 SmallVector<SourceLocation, 8> ProtocolLocs;
279 if (Tok.is(tok::less) &&
280 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
281 LAngleLoc, EndProtoLoc,
282 /*consumeLastToken=*/true))
285 Decl *CategoryType = Actions.ActOnStartCategoryInterface(
286 AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
287 ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
290 if (Tok.is(tok::l_brace))
291 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
293 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
297 // Parse a class interface.
298 IdentifierInfo *superClassId = nullptr;
299 SourceLocation superClassLoc;
300 SourceLocation typeArgsLAngleLoc;
301 SmallVector<ParsedType, 4> typeArgs;
302 SourceLocation typeArgsRAngleLoc;
303 SmallVector<Decl *, 4> protocols;
304 SmallVector<SourceLocation, 4> protocolLocs;
305 if (Tok.is(tok::colon)) { // a super class is specified.
308 // Code completion of superclass names.
309 if (Tok.is(tok::code_completion)) {
310 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
315 if (expectIdentifier())
316 return nullptr; // missing super class name.
317 superClassId = Tok.getIdentifierInfo();
318 superClassLoc = ConsumeToken();
320 // Type arguments for the superclass or protocol conformances.
321 if (Tok.is(tok::less)) {
322 parseObjCTypeArgsOrProtocolQualifiers(
323 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
324 protocols, protocolLocs, EndProtoLoc,
325 /*consumeLastToken=*/true,
326 /*warnOnIncompleteProtocols=*/true);
327 if (Tok.is(tok::eof))
332 // Next, we need to check for any protocol references.
333 if (LAngleLoc.isValid()) {
334 if (!ProtocolIdents.empty()) {
335 // We already parsed the protocols named when we thought we had a
336 // type parameter list. Translate them into actual protocol references.
337 for (const auto &pair : ProtocolIdents) {
338 protocolLocs.push_back(pair.second);
340 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
341 /*ForObjCContainer=*/true,
342 ProtocolIdents, protocols);
344 } else if (protocols.empty() && Tok.is(tok::less) &&
345 ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
346 LAngleLoc, EndProtoLoc,
347 /*consumeLastToken=*/true)) {
351 if (Tok.isNot(tok::less))
352 Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
353 superClassId, superClassLoc);
355 Decl *ClsType = Actions.ActOnStartClassInterface(
356 getCurScope(), AtLoc, nameId, nameLoc, typeParameterList, superClassId,
357 superClassLoc, typeArgs,
358 SourceRange(typeArgsLAngleLoc, typeArgsRAngleLoc), protocols.data(),
359 protocols.size(), protocolLocs.data(), EndProtoLoc, attrs);
361 if (Tok.is(tok::l_brace))
362 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
364 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
369 /// Add an attribute for a context-sensitive type nullability to the given
371 static void addContextSensitiveTypeNullability(Parser &P,
373 NullabilityKind nullability,
374 SourceLocation nullabilityLoc,
375 bool &addedToDeclSpec) {
376 // Create the attribute.
377 auto getNullabilityAttr = [&](AttributePool &Pool) -> ParsedAttr * {
378 return Pool.create(P.getNullabilityKeyword(nullability),
379 SourceRange(nullabilityLoc), nullptr, SourceLocation(),
380 nullptr, 0, ParsedAttr::AS_ContextSensitiveKeyword);
383 if (D.getNumTypeObjects() > 0) {
384 // Add the attribute to the declarator chunk nearest the declarator.
385 D.getTypeObject(0).getAttrs().addAtEnd(
386 getNullabilityAttr(D.getAttributePool()));
387 } else if (!addedToDeclSpec) {
388 // Otherwise, just put it on the declaration specifiers (if one
389 // isn't there already).
390 D.getMutableDeclSpec().getAttributes().addAtEnd(
391 getNullabilityAttr(D.getMutableDeclSpec().getAttributes().getPool()));
392 addedToDeclSpec = true;
396 /// Parse an Objective-C type parameter list, if present, or capture
397 /// the locations of the protocol identifiers for a list of protocol
400 /// objc-type-parameter-list:
401 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
403 /// objc-type-parameter:
404 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
406 /// objc-type-parameter-bound:
409 /// objc-type-parameter-variance:
411 /// '__contravariant'
413 /// \param lAngleLoc The location of the starting '<'.
415 /// \param protocolIdents Will capture the list of identifiers, if the
416 /// angle brackets contain a list of protocol references rather than a
417 /// type parameter list.
419 /// \param rAngleLoc The location of the ending '>'.
420 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
421 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
422 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
423 SourceLocation &rAngleLoc, bool mayBeProtocolList) {
424 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
426 // Within the type parameter list, don't treat '>' as an operator.
427 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
429 // Local function to "flush" the protocol identifiers, turning them into
431 SmallVector<Decl *, 4> typeParams;
432 auto makeProtocolIdentsIntoTypeParameters = [&]() {
434 for (const auto &pair : protocolIdents) {
435 DeclResult typeParam = Actions.actOnObjCTypeParam(
436 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
437 index++, pair.first, pair.second, SourceLocation(), nullptr);
438 if (typeParam.isUsable())
439 typeParams.push_back(typeParam.get());
442 protocolIdents.clear();
443 mayBeProtocolList = false;
446 bool invalid = false;
447 lAngleLoc = ConsumeToken();
450 // Parse the variance, if any.
451 SourceLocation varianceLoc;
452 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
453 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
454 variance = Tok.is(tok::kw___covariant)
455 ? ObjCTypeParamVariance::Covariant
456 : ObjCTypeParamVariance::Contravariant;
457 varianceLoc = ConsumeToken();
459 // Once we've seen a variance specific , we know this is not a
460 // list of protocol references.
461 if (mayBeProtocolList) {
462 // Up until now, we have been queuing up parameters because they
463 // might be protocol references. Turn them into parameters now.
464 makeProtocolIdentsIntoTypeParameters();
468 // Parse the identifier.
469 if (!Tok.is(tok::identifier)) {
471 if (Tok.is(tok::code_completion)) {
472 // FIXME: If these aren't protocol references, we'll need different
474 Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
477 // FIXME: Better recovery here?.
481 Diag(Tok, diag::err_objc_expected_type_parameter);
486 IdentifierInfo *paramName = Tok.getIdentifierInfo();
487 SourceLocation paramLoc = ConsumeToken();
489 // If there is a bound, parse it.
490 SourceLocation colonLoc;
491 TypeResult boundType;
492 if (TryConsumeToken(tok::colon, colonLoc)) {
493 // Once we've seen a bound, we know this is not a list of protocol
495 if (mayBeProtocolList) {
496 // Up until now, we have been queuing up parameters because they
497 // might be protocol references. Turn them into parameters now.
498 makeProtocolIdentsIntoTypeParameters();
502 boundType = ParseTypeName();
503 if (boundType.isInvalid())
505 } else if (mayBeProtocolList) {
506 // If this could still be a protocol list, just capture the identifier.
507 // We don't want to turn it into a parameter.
508 protocolIdents.push_back(std::make_pair(paramName, paramLoc));
512 // Create the type parameter.
513 DeclResult typeParam = Actions.actOnObjCTypeParam(
514 getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
515 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
516 if (typeParam.isUsable())
517 typeParams.push_back(typeParam.get());
518 } while (TryConsumeToken(tok::comma));
522 SkipUntil(tok::greater, tok::at, StopBeforeMatch);
523 if (Tok.is(tok::greater))
525 } else if (ParseGreaterThanInTemplateList(rAngleLoc,
526 /*ConsumeLastToken=*/true,
527 /*ObjCGenericList=*/true)) {
528 Diag(lAngleLoc, diag::note_matching) << "'<'";
529 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
530 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
531 tok::comma, tok::semi },
533 if (Tok.is(tok::greater))
537 if (mayBeProtocolList) {
538 // A type parameter list must be followed by either a ':' (indicating the
539 // presence of a superclass) or a '(' (indicating that this is a category
540 // or extension). This disambiguates between an objc-type-parameter-list
541 // and a objc-protocol-refs.
542 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
543 // Returning null indicates that we don't have a type parameter list.
544 // The results the caller needs to handle the protocol references are
545 // captured in the reference parameters already.
549 // We have a type parameter list that looks like a list of protocol
550 // references. Turn that parameter list into type parameters.
551 makeProtocolIdentsIntoTypeParameters();
554 // Form the type parameter list and enter its scope.
555 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
562 // Clear out the angle locations; they're used by the caller to indicate
563 // whether there are any protocol references.
564 lAngleLoc = SourceLocation();
565 rAngleLoc = SourceLocation();
566 return invalid ? nullptr : list;
569 /// Parse an objc-type-parameter-list.
570 ObjCTypeParamList *Parser::parseObjCTypeParamList() {
571 SourceLocation lAngleLoc;
572 SmallVector<IdentifierLocPair, 1> protocolIdents;
573 SourceLocation rAngleLoc;
575 ObjCTypeParamListScope Scope(Actions, getCurScope());
576 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
578 /*mayBeProtocolList=*/false);
581 /// objc-interface-decl-list:
583 /// objc-interface-decl-list objc-property-decl [OBJC2]
584 /// objc-interface-decl-list objc-method-requirement [OBJC2]
585 /// objc-interface-decl-list objc-method-proto ';'
586 /// objc-interface-decl-list declaration
587 /// objc-interface-decl-list ';'
589 /// objc-method-requirement: [OBJC2]
593 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
595 SmallVector<Decl *, 32> allMethods;
596 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
597 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
602 // If this is a method prototype, parse it.
603 if (Tok.isOneOf(tok::minus, tok::plus)) {
604 if (Decl *methodPrototype =
605 ParseObjCMethodPrototype(MethodImplKind, false))
606 allMethods.push_back(methodPrototype);
607 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
608 // method definitions.
609 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
610 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
611 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
612 if (Tok.is(tok::semi))
617 if (Tok.is(tok::l_paren)) {
618 Diag(Tok, diag::err_expected_minus_or_plus);
619 ParseObjCMethodDecl(Tok.getLocation(),
621 MethodImplKind, false);
624 // Ignore excess semicolons.
625 if (Tok.is(tok::semi)) {
626 // FIXME: This should use ConsumeExtraSemi() for extraneous semicolons,
627 // to make -Wextra-semi diagnose them.
632 // If we got to the end of the file, exit the loop.
636 // Code completion within an Objective-C interface.
637 if (Tok.is(tok::code_completion)) {
638 Actions.CodeCompleteOrdinaryName(getCurScope(),
639 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
640 : Sema::PCC_ObjCInterface);
641 return cutOffParsing();
644 // If we don't have an @ directive, parse it as a function definition.
645 if (Tok.isNot(tok::at)) {
646 // The code below does not consume '}'s because it is afraid of eating the
647 // end of a namespace. Because of the way this code is structured, an
648 // erroneous r_brace would cause an infinite loop if not handled here.
649 if (Tok.is(tok::r_brace))
652 ParsedAttributesWithRange attrs(AttrFactory);
654 // Since we call ParseDeclarationOrFunctionDefinition() instead of
655 // ParseExternalDeclaration() below (so that this doesn't parse nested
656 // @interfaces), this needs to duplicate some code from the latter.
657 if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
658 SourceLocation DeclEnd;
659 allTUVariables.push_back(
660 ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs));
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->getBeginLoc(), 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().ObjC)
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->getBeginLoc(), 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().ObjC && 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(ParsedAttributesView &attrs,
1209 ParsedAttributesView &from) {
1210 for (auto &AL : llvm::reverse(from)) {
1211 if (!AL.isUsedAsTypeAttr()) {
1213 attrs.addAtEnd(&AL);
1218 /// takeDeclAttributes - Take all the decl attributes from the given
1219 /// declarator and add them to the given list.
1220 static void takeDeclAttributes(ParsedAttributes &attrs,
1222 // First, take ownership of all attributes.
1223 attrs.getPool().takeAllFrom(D.getAttributePool());
1224 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1226 // Now actually move the attributes over.
1227 takeDeclAttributes(attrs, D.getMutableDeclSpec().getAttributes());
1228 takeDeclAttributes(attrs, D.getAttributes());
1229 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1230 takeDeclAttributes(attrs, D.getTypeObject(i).getAttrs());
1234 /// '(' objc-type-qualifiers[opt] type-name ')'
1235 /// '(' objc-type-qualifiers[opt] ')'
1237 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1238 DeclaratorContext context,
1239 ParsedAttributes *paramAttrs) {
1240 assert(context == DeclaratorContext::ObjCParameterContext ||
1241 context == DeclaratorContext::ObjCResultContext);
1242 assert((paramAttrs != nullptr) ==
1243 (context == DeclaratorContext::ObjCParameterContext));
1245 assert(Tok.is(tok::l_paren) && "expected (");
1247 BalancedDelimiterTracker T(*this, tok::l_paren);
1250 ObjCDeclContextSwitch ObjCDC(*this);
1252 // Parse type qualifiers, in, inout, etc.
1253 ParseObjCTypeQualifierList(DS, context);
1254 SourceLocation TypeStartLoc = Tok.getLocation();
1257 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1258 // Parse an abstract declarator.
1259 DeclSpec declSpec(AttrFactory);
1260 declSpec.setObjCQualifiers(&DS);
1261 DeclSpecContext dsContext = DeclSpecContext::DSC_normal;
1262 if (context == DeclaratorContext::ObjCResultContext)
1263 dsContext = DeclSpecContext::DSC_objc_method_result;
1264 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1265 Declarator declarator(declSpec, context);
1266 ParseDeclarator(declarator);
1268 // If that's not invalid, extract a type.
1269 if (!declarator.isInvalidType()) {
1270 // Map a nullability specifier to a context-sensitive keyword attribute.
1271 bool addedToDeclSpec = false;
1272 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1273 addContextSensitiveTypeNullability(*this, declarator,
1274 DS.getNullability(),
1275 DS.getNullabilityLoc(),
1278 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1279 if (!type.isInvalid())
1282 // If we're parsing a parameter, steal all the decl attributes
1283 // and add them to the decl spec.
1284 if (context == DeclaratorContext::ObjCParameterContext)
1285 takeDeclAttributes(*paramAttrs, declarator);
1289 if (Tok.is(tok::r_paren))
1291 else if (Tok.getLocation() == TypeStartLoc) {
1292 // If we didn't eat any tokens, then this isn't a type.
1293 Diag(Tok, diag::err_expected_type);
1294 SkipUntil(tok::r_paren, StopAtSemi);
1296 // Otherwise, we found *something*, but didn't get a ')' in the right
1297 // place. Emit an error then return what we have as the type.
1303 /// objc-method-decl:
1305 /// objc-keyword-selector objc-parmlist[opt]
1306 /// objc-type-name objc-selector
1307 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1309 /// objc-keyword-selector:
1310 /// objc-keyword-decl
1311 /// objc-keyword-selector objc-keyword-decl
1313 /// objc-keyword-decl:
1314 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1315 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1316 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1317 /// ':' objc-keyword-attributes[opt] identifier
1320 /// objc-parms objc-ellipsis[opt]
1323 /// objc-parms , parameter-declaration
1328 /// objc-keyword-attributes: [OBJC2]
1329 /// __attribute__((unused))
1331 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1332 tok::TokenKind mType,
1333 tok::ObjCKeywordKind MethodImplKind,
1334 bool MethodDefinition) {
1335 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1337 if (Tok.is(tok::code_completion)) {
1338 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1339 /*ReturnType=*/nullptr);
1344 // Parse the return type if present.
1345 ParsedType ReturnType;
1347 if (Tok.is(tok::l_paren))
1348 ReturnType = ParseObjCTypeName(DSRet, DeclaratorContext::ObjCResultContext,
1351 // If attributes exist before the method, parse them.
1352 ParsedAttributes methodAttrs(AttrFactory);
1353 if (getLangOpts().ObjC)
1354 MaybeParseGNUAttributes(methodAttrs);
1355 MaybeParseCXX11Attributes(methodAttrs);
1357 if (Tok.is(tok::code_completion)) {
1358 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1364 // Now parse the selector.
1365 SourceLocation selLoc;
1366 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1368 // An unnamed colon is valid.
1369 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1370 Diag(Tok, diag::err_expected_selector_for_method)
1371 << SourceRange(mLoc, Tok.getLocation());
1372 // Skip until we get a ; or @.
1373 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1377 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1378 if (Tok.isNot(tok::colon)) {
1379 // If attributes exist after the method, parse them.
1380 if (getLangOpts().ObjC)
1381 MaybeParseGNUAttributes(methodAttrs);
1382 MaybeParseCXX11Attributes(methodAttrs);
1384 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1385 Decl *Result = Actions.ActOnMethodDeclaration(
1386 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType,
1387 selLoc, Sel, nullptr, CParamInfo.data(), CParamInfo.size(), methodAttrs,
1388 MethodImplKind, false, MethodDefinition);
1389 PD.complete(Result);
1393 SmallVector<IdentifierInfo *, 12> KeyIdents;
1394 SmallVector<SourceLocation, 12> KeyLocs;
1395 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1396 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1397 Scope::FunctionDeclarationScope | Scope::DeclScope);
1399 AttributePool allParamAttrs(AttrFactory);
1401 ParsedAttributes paramAttrs(AttrFactory);
1402 Sema::ObjCArgInfo ArgInfo;
1404 // Each iteration parses a single keyword argument.
1405 if (ExpectAndConsume(tok::colon))
1408 ArgInfo.Type = nullptr;
1409 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1410 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1411 DeclaratorContext::ObjCParameterContext,
1414 // If attributes exist before the argument name, parse them.
1415 // Regardless, collect all the attributes we've parsed so far.
1416 if (getLangOpts().ObjC)
1417 MaybeParseGNUAttributes(paramAttrs);
1418 MaybeParseCXX11Attributes(paramAttrs);
1419 ArgInfo.ArgAttrs = paramAttrs;
1421 // Code completion for the next piece of the selector.
1422 if (Tok.is(tok::code_completion)) {
1423 KeyIdents.push_back(SelIdent);
1424 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1425 mType == tok::minus,
1426 /*AtParameterName=*/true,
1427 ReturnType, KeyIdents);
1432 if (expectIdentifier())
1433 break; // missing argument name.
1435 ArgInfo.Name = Tok.getIdentifierInfo();
1436 ArgInfo.NameLoc = Tok.getLocation();
1437 ConsumeToken(); // Eat the identifier.
1439 ArgInfos.push_back(ArgInfo);
1440 KeyIdents.push_back(SelIdent);
1441 KeyLocs.push_back(selLoc);
1443 // Make sure the attributes persist.
1444 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1446 // Code completion for the next piece of the selector.
1447 if (Tok.is(tok::code_completion)) {
1448 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1449 mType == tok::minus,
1450 /*AtParameterName=*/false,
1451 ReturnType, KeyIdents);
1456 // Check for another keyword selector.
1457 SelIdent = ParseObjCSelectorPiece(selLoc);
1458 if (!SelIdent && Tok.isNot(tok::colon))
1461 SourceLocation ColonLoc = Tok.getLocation();
1462 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1463 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1464 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1465 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1468 // We have a selector or a colon, continue parsing.
1471 bool isVariadic = false;
1472 bool cStyleParamWarned = false;
1473 // Parse the (optional) parameter list.
1474 while (Tok.is(tok::comma)) {
1476 if (Tok.is(tok::ellipsis)) {
1481 if (!cStyleParamWarned) {
1482 Diag(Tok, diag::warn_cstyle_param);
1483 cStyleParamWarned = true;
1485 DeclSpec DS(AttrFactory);
1486 ParseDeclarationSpecifiers(DS);
1487 // Parse the declarator.
1488 Declarator ParmDecl(DS, DeclaratorContext::PrototypeContext);
1489 ParseDeclarator(ParmDecl);
1490 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1491 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1492 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1493 ParmDecl.getIdentifierLoc(),
1498 // FIXME: Add support for optional parameter list...
1499 // If attributes exist after the method, parse them.
1500 if (getLangOpts().ObjC)
1501 MaybeParseGNUAttributes(methodAttrs);
1502 MaybeParseCXX11Attributes(methodAttrs);
1504 if (KeyIdents.size() == 0)
1507 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1509 Decl *Result = Actions.ActOnMethodDeclaration(
1510 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, KeyLocs,
1511 Sel, &ArgInfos[0], CParamInfo.data(), CParamInfo.size(), methodAttrs,
1512 MethodImplKind, isVariadic, MethodDefinition);
1514 PD.complete(Result);
1518 /// objc-protocol-refs:
1519 /// '<' identifier-list '>'
1522 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1523 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1524 bool WarnOnDeclarations, bool ForObjCContainer,
1525 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1526 bool consumeLastToken) {
1527 assert(Tok.is(tok::less) && "expected <");
1529 LAngleLoc = ConsumeToken(); // the "<"
1531 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1534 if (Tok.is(tok::code_completion)) {
1535 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1540 if (expectIdentifier()) {
1541 SkipUntil(tok::greater, StopAtSemi);
1544 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1545 Tok.getLocation()));
1546 ProtocolLocs.push_back(Tok.getLocation());
1549 if (!TryConsumeToken(tok::comma))
1554 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1555 /*ObjCGenericList=*/false))
1558 // Convert the list of protocols identifiers into a list of protocol decls.
1559 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1560 ProtocolIdents, Protocols);
1564 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1565 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1566 assert(getLangOpts().ObjC && "Protocol qualifiers only exist in Objective-C");
1568 SourceLocation lAngleLoc;
1569 SmallVector<Decl *, 8> protocols;
1570 SmallVector<SourceLocation, 8> protocolLocs;
1571 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1572 lAngleLoc, rAngleLoc,
1573 /*consumeLastToken=*/true);
1574 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1578 if (result.isUsable()) {
1579 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1580 << FixItHint::CreateInsertion(lAngleLoc, "id")
1581 << SourceRange(lAngleLoc, rAngleLoc);
1587 /// Parse Objective-C type arguments or protocol qualifiers.
1589 /// objc-type-arguments:
1590 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1592 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1593 ParsedType baseType,
1594 SourceLocation &typeArgsLAngleLoc,
1595 SmallVectorImpl<ParsedType> &typeArgs,
1596 SourceLocation &typeArgsRAngleLoc,
1597 SourceLocation &protocolLAngleLoc,
1598 SmallVectorImpl<Decl *> &protocols,
1599 SmallVectorImpl<SourceLocation> &protocolLocs,
1600 SourceLocation &protocolRAngleLoc,
1601 bool consumeLastToken,
1602 bool warnOnIncompleteProtocols) {
1603 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1604 SourceLocation lAngleLoc = ConsumeToken();
1606 // Whether all of the elements we've parsed thus far are single
1607 // identifiers, which might be types or might be protocols.
1608 bool allSingleIdentifiers = true;
1609 SmallVector<IdentifierInfo *, 4> identifiers;
1610 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1612 // Parse a list of comma-separated identifiers, bailing out if we
1613 // see something different.
1615 // Parse a single identifier.
1616 if (Tok.is(tok::identifier) &&
1617 (NextToken().is(tok::comma) ||
1618 NextToken().is(tok::greater) ||
1619 NextToken().is(tok::greatergreater))) {
1620 identifiers.push_back(Tok.getIdentifierInfo());
1621 identifierLocs.push_back(ConsumeToken());
1625 if (Tok.is(tok::code_completion)) {
1626 // FIXME: Also include types here.
1627 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1628 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1629 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1630 identifierLocs[i]));
1633 QualType BaseT = Actions.GetTypeFromParser(baseType);
1634 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1635 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1637 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1643 allSingleIdentifiers = false;
1645 } while (TryConsumeToken(tok::comma));
1647 // If we parsed an identifier list, semantic analysis sorts out
1648 // whether it refers to protocols or to type arguments.
1649 if (allSingleIdentifiers) {
1650 // Parse the closing '>'.
1651 SourceLocation rAngleLoc;
1652 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1653 /*ObjCGenericList=*/true);
1655 // Let Sema figure out what we parsed.
1656 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1668 warnOnIncompleteProtocols);
1672 // We parsed an identifier list but stumbled into non single identifiers, this
1673 // means we might (a) check that what we already parsed is a legitimate type
1674 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1675 // must all be type args.
1677 // Convert the identifiers into type arguments.
1678 bool invalid = false;
1679 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1680 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1681 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1682 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1684 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1686 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1688 DeclSpec DS(AttrFactory);
1689 const char *prevSpec = nullptr;
1691 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1692 typeArg, Actions.getASTContext().getPrintingPolicy());
1694 // Form a declarator to turn this into a type.
1695 Declarator D(DS, DeclaratorContext::TypeNameContext);
1696 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1697 if (fullTypeArg.isUsable()) {
1698 typeArgs.push_back(fullTypeArg.get());
1699 if (!foundValidTypeId) {
1700 foundValidTypeId = identifiers[i];
1701 foundValidTypeSrcLoc = identifierLocs[i];
1705 unknownTypeArgs.push_back(identifiers[i]);
1706 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1710 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1711 unknownTypeArgs.push_back(identifiers[i]);
1712 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1713 } else if (!foundProtocolId) {
1714 foundProtocolId = identifiers[i];
1715 foundProtocolSrcLoc = identifierLocs[i];
1720 // Continue parsing type-names.
1722 Token CurTypeTok = Tok;
1723 TypeResult typeArg = ParseTypeName();
1725 // Consume the '...' for a pack expansion.
1726 SourceLocation ellipsisLoc;
1727 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1728 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1729 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1732 if (typeArg.isUsable()) {
1733 typeArgs.push_back(typeArg.get());
1734 if (!foundValidTypeId) {
1735 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1736 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1741 } while (TryConsumeToken(tok::comma));
1743 // Diagnose the mix between type args and protocols.
1744 if (foundProtocolId && foundValidTypeId)
1745 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1747 foundValidTypeSrcLoc);
1749 // Diagnose unknown arg types.
1751 if (unknownTypeArgs.size())
1752 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1753 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1754 getCurScope(), nullptr, T);
1756 // Parse the closing '>'.
1757 SourceLocation rAngleLoc;
1758 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1759 /*ObjCGenericList=*/true);
1766 // Record left/right angle locations.
1767 typeArgsLAngleLoc = lAngleLoc;
1768 typeArgsRAngleLoc = rAngleLoc;
1771 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1772 ParsedType baseType,
1773 SourceLocation &typeArgsLAngleLoc,
1774 SmallVectorImpl<ParsedType> &typeArgs,
1775 SourceLocation &typeArgsRAngleLoc,
1776 SourceLocation &protocolLAngleLoc,
1777 SmallVectorImpl<Decl *> &protocols,
1778 SmallVectorImpl<SourceLocation> &protocolLocs,
1779 SourceLocation &protocolRAngleLoc,
1780 bool consumeLastToken) {
1781 assert(Tok.is(tok::less));
1783 // Parse the first angle-bracket-delimited clause.
1784 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1793 /*warnOnIncompleteProtocols=*/false);
1794 if (Tok.is(tok::eof)) // Nothing else to do here...
1797 // An Objective-C object pointer followed by type arguments
1798 // can then be followed again by a set of protocol references, e.g.,
1799 // \c NSArray<NSView><NSTextDelegate>
1800 if ((consumeLastToken && Tok.is(tok::less)) ||
1801 (!consumeLastToken && NextToken().is(tok::less))) {
1802 // If we aren't consuming the last token, the prior '>' is still hanging
1803 // there. Consume it before we parse the protocol qualifiers.
1804 if (!consumeLastToken)
1807 if (!protocols.empty()) {
1808 SkipUntilFlags skipFlags = SkipUntilFlags();
1809 if (!consumeLastToken)
1810 skipFlags = skipFlags | StopBeforeMatch;
1811 Diag(Tok, diag::err_objc_type_args_after_protocols)
1812 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1813 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1815 ParseObjCProtocolReferences(protocols, protocolLocs,
1816 /*WarnOnDeclarations=*/false,
1817 /*ForObjCContainer=*/false,
1818 protocolLAngleLoc, protocolRAngleLoc,
1824 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1827 bool consumeLastToken,
1828 SourceLocation &endLoc) {
1829 assert(Tok.is(tok::less));
1830 SourceLocation typeArgsLAngleLoc;
1831 SmallVector<ParsedType, 4> typeArgs;
1832 SourceLocation typeArgsRAngleLoc;
1833 SourceLocation protocolLAngleLoc;
1834 SmallVector<Decl *, 4> protocols;
1835 SmallVector<SourceLocation, 4> protocolLocs;
1836 SourceLocation protocolRAngleLoc;
1838 // Parse type arguments and protocol qualifiers.
1839 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1840 typeArgsRAngleLoc, protocolLAngleLoc,
1841 protocols, protocolLocs,
1842 protocolRAngleLoc, consumeLastToken);
1844 if (Tok.is(tok::eof))
1845 return true; // Invalid type result.
1847 // Compute the location of the last token.
1848 if (consumeLastToken)
1849 endLoc = PrevTokLocation;
1851 endLoc = Tok.getLocation();
1853 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1866 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1867 BalancedDelimiterTracker &T,
1868 SmallVectorImpl<Decl *> &AllIvarDecls,
1869 bool RBraceMissing) {
1873 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1874 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1875 Actions.ActOnObjCContainerFinishDefinition();
1876 // Call ActOnFields() even if we don't have any decls. This is useful
1877 // for code rewriting tools that need to be aware of the empty list.
1878 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, AllIvarDecls,
1879 T.getOpenLocation(), T.getCloseLocation(),
1880 ParsedAttributesView());
1883 /// objc-class-instance-variables:
1884 /// '{' objc-instance-variable-decl-list[opt] '}'
1886 /// objc-instance-variable-decl-list:
1887 /// objc-visibility-spec
1888 /// objc-instance-variable-decl ';'
1890 /// objc-instance-variable-decl-list objc-visibility-spec
1891 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1892 /// objc-instance-variable-decl-list static_assert-declaration
1893 /// objc-instance-variable-decl-list ';'
1895 /// objc-visibility-spec:
1899 /// @package [OBJC2]
1901 /// objc-instance-variable-decl:
1902 /// struct-declaration
1904 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1905 tok::ObjCKeywordKind visibility,
1906 SourceLocation atLoc) {
1907 assert(Tok.is(tok::l_brace) && "expected {");
1908 SmallVector<Decl *, 32> AllIvarDecls;
1910 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1911 ObjCDeclContextSwitch ObjCDC(*this);
1913 BalancedDelimiterTracker T(*this, tok::l_brace);
1915 // While we still have something to read, read the instance variables.
1916 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1917 // Each iteration of this loop reads one objc-instance-variable-decl.
1919 // Check for extraneous top-level semicolon.
1920 if (Tok.is(tok::semi)) {
1921 ConsumeExtraSemi(InstanceVariableList);
1925 // Set the default visibility to private.
1926 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1927 if (Tok.is(tok::code_completion)) {
1928 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1929 return cutOffParsing();
1932 switch (Tok.getObjCKeywordID()) {
1933 case tok::objc_private:
1934 case tok::objc_public:
1935 case tok::objc_protected:
1936 case tok::objc_package:
1937 visibility = Tok.getObjCKeywordID();
1942 Diag(Tok, diag::err_objc_unexpected_atend);
1943 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1944 Tok.setKind(tok::at);
1946 PP.EnterToken(Tok, /*IsReinject*/true);
1947 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1948 T, AllIvarDecls, true);
1952 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1957 if (Tok.is(tok::code_completion)) {
1958 Actions.CodeCompleteOrdinaryName(getCurScope(),
1959 Sema::PCC_ObjCInstanceVariableList);
1960 return cutOffParsing();
1963 // This needs to duplicate a small amount of code from
1964 // ParseStructUnionBody() for things that should work in both
1965 // C struct and in Objective-C class instance variables.
1966 if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
1967 SourceLocation DeclEnd;
1968 ParseStaticAssertDeclaration(DeclEnd);
1972 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1973 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1974 // Install the declarator into the interface decl.
1975 FD.D.setObjCIvar(true);
1976 Decl *Field = Actions.ActOnIvar(
1977 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1978 FD.BitfieldSize, visibility);
1979 Actions.ActOnObjCContainerFinishDefinition();
1981 AllIvarDecls.push_back(Field);
1985 // Parse all the comma separated declarators.
1986 ParsingDeclSpec DS(*this);
1987 ParseStructDeclaration(DS, ObjCIvarCallback);
1989 if (Tok.is(tok::semi)) {
1992 Diag(Tok, diag::err_expected_semi_decl_list);
1993 // Skip to end of block or statement
1994 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1997 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1998 T, AllIvarDecls, false);
2001 /// objc-protocol-declaration:
2002 /// objc-protocol-definition
2003 /// objc-protocol-forward-reference
2005 /// objc-protocol-definition:
2006 /// \@protocol identifier
2007 /// objc-protocol-refs[opt]
2008 /// objc-interface-decl-list
2011 /// objc-protocol-forward-reference:
2012 /// \@protocol identifier-list ';'
2014 /// "\@protocol identifier ;" should be resolved as "\@protocol
2015 /// identifier-list ;": objc-interface-decl-list may not start with a
2016 /// semicolon in the first alternative if objc-protocol-refs are omitted.
2017 Parser::DeclGroupPtrTy
2018 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2019 ParsedAttributes &attrs) {
2020 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2021 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2022 ConsumeToken(); // the "protocol" identifier
2024 if (Tok.is(tok::code_completion)) {
2025 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2030 MaybeSkipAttributes(tok::objc_protocol);
2032 if (expectIdentifier())
2033 return nullptr; // missing protocol name.
2034 // Save the protocol name, then consume it.
2035 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2036 SourceLocation nameLoc = ConsumeToken();
2038 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2039 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2040 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo, attrs);
2043 CheckNestedObjCContexts(AtLoc);
2045 if (Tok.is(tok::comma)) { // list of forward declarations.
2046 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2047 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2049 // Parse the list of forward declarations.
2051 ConsumeToken(); // the ','
2052 if (expectIdentifier()) {
2053 SkipUntil(tok::semi);
2056 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2057 Tok.getLocation()));
2058 ConsumeToken(); // the identifier
2060 if (Tok.isNot(tok::comma))
2064 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2067 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs, attrs);
2070 // Last, and definitely not least, parse a protocol declaration.
2071 SourceLocation LAngleLoc, EndProtoLoc;
2073 SmallVector<Decl *, 8> ProtocolRefs;
2074 SmallVector<SourceLocation, 8> ProtocolLocs;
2075 if (Tok.is(tok::less) &&
2076 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2077 LAngleLoc, EndProtoLoc,
2078 /*consumeLastToken=*/true))
2081 Decl *ProtoType = Actions.ActOnStartProtocolInterface(
2082 AtLoc, protocolName, nameLoc, ProtocolRefs.data(), ProtocolRefs.size(),
2083 ProtocolLocs.data(), EndProtoLoc, attrs);
2085 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2086 return Actions.ConvertDeclToDeclGroup(ProtoType);
2089 /// objc-implementation:
2090 /// objc-class-implementation-prologue
2091 /// objc-category-implementation-prologue
2093 /// objc-class-implementation-prologue:
2094 /// @implementation identifier objc-superclass[opt]
2095 /// objc-class-instance-variables[opt]
2097 /// objc-category-implementation-prologue:
2098 /// @implementation identifier ( identifier )
2099 Parser::DeclGroupPtrTy
2100 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
2101 ParsedAttributes &Attrs) {
2102 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2103 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2104 CheckNestedObjCContexts(AtLoc);
2105 ConsumeToken(); // the "implementation" identifier
2107 // Code completion after '@implementation'.
2108 if (Tok.is(tok::code_completion)) {
2109 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2114 MaybeSkipAttributes(tok::objc_implementation);
2116 if (expectIdentifier())
2117 return nullptr; // missing class or category name.
2118 // We have a class or category name - consume it.
2119 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2120 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2121 Decl *ObjCImpDecl = nullptr;
2123 // Neither a type parameter list nor a list of protocol references is
2124 // permitted here. Parse and diagnose them.
2125 if (Tok.is(tok::less)) {
2126 SourceLocation lAngleLoc, rAngleLoc;
2127 SmallVector<IdentifierLocPair, 8> protocolIdents;
2128 SourceLocation diagLoc = Tok.getLocation();
2129 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2130 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2131 protocolIdents, rAngleLoc)) {
2132 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2133 << SourceRange(diagLoc, PrevTokLocation);
2134 } else if (lAngleLoc.isValid()) {
2135 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2136 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2140 if (Tok.is(tok::l_paren)) {
2141 // we have a category implementation.
2143 SourceLocation categoryLoc, rparenLoc;
2144 IdentifierInfo *categoryId = nullptr;
2146 if (Tok.is(tok::code_completion)) {
2147 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2152 if (Tok.is(tok::identifier)) {
2153 categoryId = Tok.getIdentifierInfo();
2154 categoryLoc = ConsumeToken();
2156 Diag(Tok, diag::err_expected)
2157 << tok::identifier; // missing category name.
2160 if (Tok.isNot(tok::r_paren)) {
2161 Diag(Tok, diag::err_expected) << tok::r_paren;
2162 SkipUntil(tok::r_paren); // don't stop at ';'
2165 rparenLoc = ConsumeParen();
2166 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2167 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2168 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2169 SmallVector<Decl *, 4> protocols;
2170 SmallVector<SourceLocation, 4> protocolLocs;
2171 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2172 /*warnOnIncompleteProtocols=*/false,
2173 /*ForObjCContainer=*/false,
2174 protocolLAngleLoc, protocolRAngleLoc,
2175 /*consumeLastToken=*/true);
2177 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2178 AtLoc, nameId, nameLoc, categoryId, categoryLoc, Attrs);
2181 // We have a class implementation
2182 SourceLocation superClassLoc;
2183 IdentifierInfo *superClassId = nullptr;
2184 if (TryConsumeToken(tok::colon)) {
2185 // We have a super class
2186 if (expectIdentifier())
2187 return nullptr; // missing super class name.
2188 superClassId = Tok.getIdentifierInfo();
2189 superClassLoc = ConsumeToken(); // Consume super class name
2191 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2192 AtLoc, nameId, nameLoc, superClassId, superClassLoc, Attrs);
2194 if (Tok.is(tok::l_brace)) // we have ivars
2195 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2196 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2197 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2199 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2200 SmallVector<Decl *, 4> protocols;
2201 SmallVector<SourceLocation, 4> protocolLocs;
2202 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2203 /*warnOnIncompleteProtocols=*/false,
2204 /*ForObjCContainer=*/false,
2205 protocolLAngleLoc, protocolRAngleLoc,
2206 /*consumeLastToken=*/true);
2209 assert(ObjCImpDecl);
2211 SmallVector<Decl *, 8> DeclsInGroup;
2214 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2215 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2216 ParsedAttributesWithRange attrs(AttrFactory);
2217 MaybeParseCXX11Attributes(attrs);
2218 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2219 DeclGroupRef DG = DGP.get();
2220 DeclsInGroup.append(DG.begin(), DG.end());
2225 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2228 Parser::DeclGroupPtrTy
2229 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2230 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2231 "ParseObjCAtEndDeclaration(): Expected @end");
2232 ConsumeToken(); // the "end" identifier
2233 if (CurParsedObjCImpl)
2234 CurParsedObjCImpl->finish(atEnd);
2236 // missing @implementation
2237 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2241 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2243 finish(P.Tok.getLocation());
2244 if (P.isEofOrEom()) {
2245 P.Diag(P.Tok, diag::err_objc_missing_end)
2246 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2247 P.Diag(Dcl->getBeginLoc(), diag::note_objc_container_start)
2248 << Sema::OCK_Implementation;
2251 P.CurParsedObjCImpl = nullptr;
2252 assert(LateParsedObjCMethods.empty());
2255 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2257 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2258 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2259 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2262 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2265 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2266 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2267 false/*c-functions*/);
2269 /// Clear and free the cached objc methods.
2270 for (LateParsedObjCMethodContainer::iterator
2271 I = LateParsedObjCMethods.begin(),
2272 E = LateParsedObjCMethods.end(); I != E; ++I)
2274 LateParsedObjCMethods.clear();
2279 /// compatibility-alias-decl:
2280 /// @compatibility_alias alias-name class-name ';'
2282 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2283 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2284 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2285 ConsumeToken(); // consume compatibility_alias
2286 if (expectIdentifier())
2288 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2289 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2290 if (expectIdentifier())
2292 IdentifierInfo *classId = Tok.getIdentifierInfo();
2293 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2294 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2295 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2299 /// property-synthesis:
2300 /// @synthesize property-ivar-list ';'
2302 /// property-ivar-list:
2304 /// property-ivar-list ',' property-ivar
2308 /// identifier '=' identifier
2310 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2311 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2312 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2313 ConsumeToken(); // consume synthesize
2316 if (Tok.is(tok::code_completion)) {
2317 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2322 if (Tok.isNot(tok::identifier)) {
2323 Diag(Tok, diag::err_synthesized_property_name);
2324 SkipUntil(tok::semi);
2328 IdentifierInfo *propertyIvar = nullptr;
2329 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2330 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2331 SourceLocation propertyIvarLoc;
2332 if (TryConsumeToken(tok::equal)) {
2333 // property '=' ivar-name
2334 if (Tok.is(tok::code_completion)) {
2335 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2340 if (expectIdentifier())
2342 propertyIvar = Tok.getIdentifierInfo();
2343 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2345 Actions.ActOnPropertyImplDecl(
2346 getCurScope(), atLoc, propertyLoc, true,
2347 propertyId, propertyIvar, propertyIvarLoc,
2348 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2349 if (Tok.isNot(tok::comma))
2351 ConsumeToken(); // consume ','
2353 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2357 /// property-dynamic:
2358 /// @dynamic property-list
2362 /// property-list ',' identifier
2364 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2365 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2366 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2367 ConsumeToken(); // consume dynamic
2369 bool isClassProperty = false;
2370 if (Tok.is(tok::l_paren)) {
2372 const IdentifierInfo *II = Tok.getIdentifierInfo();
2375 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2376 SkipUntil(tok::r_paren, StopAtSemi);
2378 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2379 if (II->isStr("class")) {
2380 isClassProperty = true;
2381 if (Tok.isNot(tok::r_paren)) {
2382 Diag(Tok, diag::err_expected) << tok::r_paren;
2383 SkipUntil(tok::r_paren, StopAtSemi);
2387 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2388 SkipUntil(tok::r_paren, StopAtSemi);
2394 if (Tok.is(tok::code_completion)) {
2395 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2400 if (expectIdentifier()) {
2401 SkipUntil(tok::semi);
2405 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2406 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2407 Actions.ActOnPropertyImplDecl(
2408 getCurScope(), atLoc, propertyLoc, false,
2409 propertyId, nullptr, SourceLocation(),
2410 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2411 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2413 if (Tok.isNot(tok::comma))
2415 ConsumeToken(); // consume ','
2417 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2421 /// objc-throw-statement:
2422 /// throw expression[opt];
2424 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2426 ConsumeToken(); // consume throw
2427 if (Tok.isNot(tok::semi)) {
2428 Res = ParseExpression();
2429 if (Res.isInvalid()) {
2430 SkipUntil(tok::semi);
2435 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2436 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2439 /// objc-synchronized-statement:
2440 /// @synchronized '(' expression ')' compound-statement
2443 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2444 ConsumeToken(); // consume synchronized
2445 if (Tok.isNot(tok::l_paren)) {
2446 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2450 // The operand is surrounded with parentheses.
2451 ConsumeParen(); // '('
2452 ExprResult operand(ParseExpression());
2454 if (Tok.is(tok::r_paren)) {
2455 ConsumeParen(); // ')'
2457 if (!operand.isInvalid())
2458 Diag(Tok, diag::err_expected) << tok::r_paren;
2460 // Skip forward until we see a left brace, but don't consume it.
2461 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2464 // Require a compound statement.
2465 if (Tok.isNot(tok::l_brace)) {
2466 if (!operand.isInvalid())
2467 Diag(Tok, diag::err_expected) << tok::l_brace;
2471 // Check the @synchronized operand now.
2472 if (!operand.isInvalid())
2473 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2475 // Parse the compound statement within a new scope.
2476 ParseScope bodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2477 StmtResult body(ParseCompoundStatementBody());
2480 // If there was a semantic or parse error earlier with the
2481 // operand, fail now.
2482 if (operand.isInvalid())
2485 if (body.isInvalid())
2486 body = Actions.ActOnNullStmt(Tok.getLocation());
2488 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2491 /// objc-try-catch-statement:
2492 /// @try compound-statement objc-catch-list[opt]
2493 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2495 /// objc-catch-list:
2496 /// @catch ( parameter-declaration ) compound-statement
2497 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2498 /// catch-parameter-declaration:
2499 /// parameter-declaration
2502 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2503 bool catch_or_finally_seen = false;
2505 ConsumeToken(); // consume try
2506 if (Tok.isNot(tok::l_brace)) {
2507 Diag(Tok, diag::err_expected) << tok::l_brace;
2510 StmtVector CatchStmts;
2511 StmtResult FinallyStmt;
2512 ParseScope TryScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2513 StmtResult TryBody(ParseCompoundStatementBody());
2515 if (TryBody.isInvalid())
2516 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2518 while (Tok.is(tok::at)) {
2519 // At this point, we need to lookahead to determine if this @ is the start
2520 // of an @catch or @finally. We don't want to consume the @ token if this
2521 // is an @try or @encode or something else.
2522 Token AfterAt = GetLookAheadToken(1);
2523 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2524 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2527 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2528 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2529 Decl *FirstPart = nullptr;
2530 ConsumeToken(); // consume catch
2531 if (Tok.is(tok::l_paren)) {
2533 ParseScope CatchScope(this, Scope::DeclScope |
2534 Scope::CompoundStmtScope |
2535 Scope::AtCatchScope);
2536 if (Tok.isNot(tok::ellipsis)) {
2537 DeclSpec DS(AttrFactory);
2538 ParseDeclarationSpecifiers(DS);
2539 Declarator ParmDecl(DS, DeclaratorContext::ObjCCatchContext);
2540 ParseDeclarator(ParmDecl);
2542 // Inform the actions module about the declarator, so it
2543 // gets added to the current scope.
2544 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2546 ConsumeToken(); // consume '...'
2548 SourceLocation RParenLoc;
2550 if (Tok.is(tok::r_paren))
2551 RParenLoc = ConsumeParen();
2552 else // Skip over garbage, until we get to ')'. Eat the ')'.
2553 SkipUntil(tok::r_paren, StopAtSemi);
2555 StmtResult CatchBody(true);
2556 if (Tok.is(tok::l_brace))
2557 CatchBody = ParseCompoundStatementBody();
2559 Diag(Tok, diag::err_expected) << tok::l_brace;
2560 if (CatchBody.isInvalid())
2561 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2563 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2567 if (!Catch.isInvalid())
2568 CatchStmts.push_back(Catch.get());
2571 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2575 catch_or_finally_seen = true;
2577 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2578 ConsumeToken(); // consume finally
2579 ParseScope FinallyScope(this,
2580 Scope::DeclScope | Scope::CompoundStmtScope);
2582 bool ShouldCapture =
2583 getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2585 Actions.ActOnCapturedRegionStart(Tok.getLocation(), getCurScope(),
2586 CR_ObjCAtFinally, 1);
2588 StmtResult FinallyBody(true);
2589 if (Tok.is(tok::l_brace))
2590 FinallyBody = ParseCompoundStatementBody();
2592 Diag(Tok, diag::err_expected) << tok::l_brace;
2594 if (FinallyBody.isInvalid()) {
2595 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2597 Actions.ActOnCapturedRegionError();
2598 } else if (ShouldCapture) {
2599 FinallyBody = Actions.ActOnCapturedRegionEnd(FinallyBody.get());
2602 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2604 catch_or_finally_seen = true;
2608 if (!catch_or_finally_seen) {
2609 Diag(atLoc, diag::err_missing_catch_finally);
2613 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2618 /// objc-autoreleasepool-statement:
2619 /// @autoreleasepool compound-statement
2622 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2623 ConsumeToken(); // consume autoreleasepool
2624 if (Tok.isNot(tok::l_brace)) {
2625 Diag(Tok, diag::err_expected) << tok::l_brace;
2628 // Enter a scope to hold everything within the compound stmt. Compound
2629 // statements can always hold declarations.
2630 ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2632 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2635 if (AutoreleasePoolBody.isInvalid())
2636 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2637 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2638 AutoreleasePoolBody.get());
2641 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2642 /// for later parsing.
2643 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2644 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2645 trySkippingFunctionBody()) {
2646 Actions.ActOnSkippedFunctionBody(MDecl);
2650 LexedMethod* LM = new LexedMethod(this, MDecl);
2651 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2652 CachedTokens &Toks = LM->Toks;
2653 // Begin by storing the '{' or 'try' or ':' token.
2654 Toks.push_back(Tok);
2655 if (Tok.is(tok::kw_try)) {
2657 if (Tok.is(tok::colon)) {
2658 Toks.push_back(Tok);
2660 while (Tok.isNot(tok::l_brace)) {
2661 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2662 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2665 Toks.push_back(Tok); // also store '{'
2667 else if (Tok.is(tok::colon)) {
2669 // FIXME: This is wrong, due to C++11 braced initialization.
2670 while (Tok.isNot(tok::l_brace)) {
2671 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2672 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2674 Toks.push_back(Tok); // also store '{'
2677 // Consume everything up to (and including) the matching right brace.
2678 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2679 while (Tok.is(tok::kw_catch)) {
2680 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2681 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2685 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2687 Decl *Parser::ParseObjCMethodDefinition() {
2688 Decl *MDecl = ParseObjCMethodPrototype();
2690 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, MDecl, Tok.getLocation(),
2691 "parsing Objective-C method");
2693 // parse optional ';'
2694 if (Tok.is(tok::semi)) {
2695 if (CurParsedObjCImpl) {
2696 Diag(Tok, diag::warn_semicolon_before_method_body)
2697 << FixItHint::CreateRemoval(Tok.getLocation());
2702 // We should have an opening brace now.
2703 if (Tok.isNot(tok::l_brace)) {
2704 Diag(Tok, diag::err_expected_method_body);
2706 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2707 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2709 // If we didn't find the '{', bail out.
2710 if (Tok.isNot(tok::l_brace))
2716 SkipUntil(tok::r_brace);
2720 // Allow the rest of sema to find private method decl implementations.
2721 Actions.AddAnyMethodToGlobalPool(MDecl);
2722 assert (CurParsedObjCImpl
2723 && "ParseObjCMethodDefinition - Method out of @implementation");
2724 // Consume the tokens and store them for later parsing.
2725 StashAwayMethodOrFunctionBodyTokens(MDecl);
2729 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc,
2730 ParsedStmtContext StmtCtx) {
2731 if (Tok.is(tok::code_completion)) {
2732 Actions.CodeCompleteObjCAtStatement(getCurScope());
2737 if (Tok.isObjCAtKeyword(tok::objc_try))
2738 return ParseObjCTryStmt(AtLoc);
2740 if (Tok.isObjCAtKeyword(tok::objc_throw))
2741 return ParseObjCThrowStmt(AtLoc);
2743 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2744 return ParseObjCSynchronizedStmt(AtLoc);
2746 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2747 return ParseObjCAutoreleasePoolStmt(AtLoc);
2749 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2750 getLangOpts().DebuggerSupport) {
2751 SkipUntil(tok::semi);
2752 return Actions.ActOnNullStmt(Tok.getLocation());
2755 ExprStatementTokLoc = AtLoc;
2756 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2757 if (Res.isInvalid()) {
2758 // If the expression is invalid, skip ahead to the next semicolon. Not
2759 // doing this opens us up to the possibility of infinite loops if
2760 // ParseExpression does not consume any tokens.
2761 SkipUntil(tok::semi);
2765 // Otherwise, eat the semicolon.
2766 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2767 return handleExprStmt(Res, StmtCtx);
2770 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2771 switch (Tok.getKind()) {
2772 case tok::code_completion:
2773 Actions.CodeCompleteObjCAtExpression(getCurScope());
2779 tok::TokenKind Kind = Tok.getKind();
2780 SourceLocation OpLoc = ConsumeToken();
2782 if (!Tok.is(tok::numeric_constant)) {
2783 const char *Symbol = nullptr;
2785 case tok::minus: Symbol = "-"; break;
2786 case tok::plus: Symbol = "+"; break;
2787 default: llvm_unreachable("missing unary operator case");
2789 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2794 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2795 if (Lit.isInvalid()) {
2798 ConsumeToken(); // Consume the literal token.
2800 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2801 if (Lit.isInvalid())
2804 return ParsePostfixExpressionSuffix(
2805 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2808 case tok::string_literal: // primary-expression: string-literal
2809 case tok::wide_string_literal:
2810 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2812 case tok::char_constant:
2813 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2815 case tok::numeric_constant:
2816 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2818 case tok::kw_true: // Objective-C++, etc.
2819 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2820 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2821 case tok::kw_false: // Objective-C++, etc.
2822 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2823 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2826 // Objective-C array literal
2827 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2830 // Objective-C dictionary literal
2831 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2834 // Objective-C boxed expression
2835 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2838 if (Tok.getIdentifierInfo() == nullptr)
2839 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2841 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2842 case tok::objc_encode:
2843 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2844 case tok::objc_protocol:
2845 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2846 case tok::objc_selector:
2847 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2848 case tok::objc_available:
2849 return ParseAvailabilityCheckExpr(AtLoc);
2851 const char *str = nullptr;
2852 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2853 // that this is a proper statement where such directives could actually
2855 if (GetLookAheadToken(1).is(tok::l_brace) &&
2856 ExprStatementTokLoc == AtLoc) {
2857 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2860 : (ch == 'f' ? "finally"
2861 : (ch == 'a' ? "autoreleasepool" : nullptr));
2864 SourceLocation kwLoc = Tok.getLocation();
2865 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2866 FixItHint::CreateReplacement(kwLoc, str));
2869 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2875 /// Parse the receiver of an Objective-C++ message send.
2877 /// This routine parses the receiver of a message send in
2878 /// Objective-C++ either as a type or as an expression. Note that this
2879 /// routine must not be called to parse a send to 'super', since it
2880 /// has no way to return such a result.
2882 /// \param IsExpr Whether the receiver was parsed as an expression.
2884 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2885 /// IsExpr is true), the parsed expression. If the receiver was parsed
2886 /// as a type (\c IsExpr is false), the parsed type.
2888 /// \returns True if an error occurred during parsing or semantic
2889 /// analysis, in which case the arguments do not have valid
2890 /// values. Otherwise, returns false for a successful parse.
2892 /// objc-receiver: [C++]
2893 /// 'super' [not parsed here]
2895 /// simple-type-specifier
2896 /// typename-specifier
2897 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2898 InMessageExpressionRAIIObject InMessage(*this, true);
2900 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2901 tok::annot_cxxscope))
2902 TryAnnotateTypeOrScopeToken();
2904 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2907 // Make sure any typos in the receiver are corrected or diagnosed, so that
2908 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2909 // only the things that are valid ObjC receivers?
2910 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2911 if (Receiver.isInvalid())
2915 TypeOrExpr = Receiver.get();
2920 // typename-specifier
2921 // simple-type-specifier
2922 // expression (that starts with one of the above)
2923 DeclSpec DS(AttrFactory);
2924 ParseCXXSimpleTypeSpecifier(DS);
2926 if (Tok.is(tok::l_paren)) {
2927 // If we see an opening parentheses at this point, we are
2928 // actually parsing an expression that starts with a
2929 // function-style cast, e.g.,
2931 // postfix-expression:
2932 // simple-type-specifier ( expression-list [opt] )
2933 // typename-specifier ( expression-list [opt] )
2935 // Parse the remainder of this case, then the (optional)
2936 // postfix-expression suffix, followed by the (optional)
2937 // right-hand side of the binary expression. We have an
2939 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2940 if (!Receiver.isInvalid())
2941 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2942 if (!Receiver.isInvalid())
2943 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2944 if (Receiver.isInvalid())
2948 TypeOrExpr = Receiver.get();
2952 // We have a class message. Turn the simple-type-specifier or
2953 // typename-specifier we parsed into a type and parse the
2954 // remainder of the class message.
2955 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2956 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2957 if (Type.isInvalid())
2961 TypeOrExpr = Type.get().getAsOpaquePtr();
2965 /// Determine whether the parser is currently referring to a an
2966 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2968 /// This routine will only return true for a subset of valid message-send
2970 bool Parser::isSimpleObjCMessageExpression() {
2971 assert(Tok.is(tok::l_square) && getLangOpts().ObjC &&
2972 "Incorrect start for isSimpleObjCMessageExpression");
2973 return GetLookAheadToken(1).is(tok::identifier) &&
2974 GetLookAheadToken(2).is(tok::identifier);
2977 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2978 if (!getLangOpts().ObjC || !NextToken().is(tok::identifier) ||
2979 InMessageExpression)
2984 if (Tok.is(tok::annot_typename))
2985 Type = getTypeAnnotation(Tok);
2986 else if (Tok.is(tok::identifier))
2987 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2992 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2993 const Token &AfterNext = GetLookAheadToken(2);
2994 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2995 if (Tok.is(tok::identifier))
2996 TryAnnotateTypeOrScopeToken();
2998 return Tok.is(tok::annot_typename);
3005 /// objc-message-expr:
3006 /// '[' objc-receiver objc-message-args ']'
3008 /// objc-receiver: [C]
3014 ExprResult Parser::ParseObjCMessageExpression() {
3015 assert(Tok.is(tok::l_square) && "'[' expected");
3016 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3018 if (Tok.is(tok::code_completion)) {
3019 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3024 InMessageExpressionRAIIObject InMessage(*this, true);
3026 if (getLangOpts().CPlusPlus) {
3027 // We completely separate the C and C++ cases because C++ requires
3028 // more complicated (read: slower) parsing.
3030 // Handle send to super.
3031 // FIXME: This doesn't benefit from the same typo-correction we
3032 // get in Objective-C.
3033 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3034 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3035 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3038 // Parse the receiver, which is either a type or an expression.
3040 void *TypeOrExpr = nullptr;
3041 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3042 SkipUntil(tok::r_square, StopAtSemi);
3047 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3048 static_cast<Expr *>(TypeOrExpr));
3050 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3051 ParsedType::getFromOpaquePtr(TypeOrExpr),
3055 if (Tok.is(tok::identifier)) {
3056 IdentifierInfo *Name = Tok.getIdentifierInfo();
3057 SourceLocation NameLoc = Tok.getLocation();
3058 ParsedType ReceiverType;
3059 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3060 Name == Ident_super,
3061 NextToken().is(tok::period),
3063 case Sema::ObjCSuperMessage:
3064 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3067 case Sema::ObjCClassMessage:
3068 if (!ReceiverType) {
3069 SkipUntil(tok::r_square, StopAtSemi);
3073 ConsumeToken(); // the type name
3075 // Parse type arguments and protocol qualifiers.
3076 if (Tok.is(tok::less)) {
3077 SourceLocation NewEndLoc;
3078 TypeResult NewReceiverType
3079 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3080 /*consumeLastToken=*/true,
3082 if (!NewReceiverType.isUsable()) {
3083 SkipUntil(tok::r_square, StopAtSemi);
3087 ReceiverType = NewReceiverType.get();
3090 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3091 ReceiverType, nullptr);
3093 case Sema::ObjCInstanceMessage:
3094 // Fall through to parse an expression.
3099 // Otherwise, an arbitrary expression can be the receiver of a send.
3100 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3101 if (Res.isInvalid()) {
3102 SkipUntil(tok::r_square, StopAtSemi);
3106 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3110 /// Parse the remainder of an Objective-C message following the
3111 /// '[' objc-receiver.
3113 /// This routine handles sends to super, class messages (sent to a
3114 /// class name), and instance messages (sent to an object), and the
3115 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3116 /// ReceiverExpr, respectively. Only one of these parameters may have
3119 /// \param LBracLoc The location of the opening '['.
3121 /// \param SuperLoc If this is a send to 'super', the location of the
3122 /// 'super' keyword that indicates a send to the superclass.
3124 /// \param ReceiverType If this is a class message, the type of the
3125 /// class we are sending a message to.
3127 /// \param ReceiverExpr If this is an instance message, the expression
3128 /// used to compute the receiver object.
3130 /// objc-message-args:
3132 /// objc-keywordarg-list
3134 /// objc-keywordarg-list:
3136 /// objc-keywordarg-list objc-keywordarg
3138 /// objc-keywordarg:
3139 /// selector-name[opt] ':' objc-keywordexpr
3141 /// objc-keywordexpr:
3142 /// nonempty-expr-list
3144 /// nonempty-expr-list:
3145 /// assignment-expression
3146 /// nonempty-expr-list , assignment-expression
3149 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3150 SourceLocation SuperLoc,
3151 ParsedType ReceiverType,
3152 Expr *ReceiverExpr) {
3153 InMessageExpressionRAIIObject InMessage(*this, true);
3155 if (Tok.is(tok::code_completion)) {
3156 if (SuperLoc.isValid())
3157 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3159 else if (ReceiverType)
3160 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3163 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3169 // Parse objc-selector
3171 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3173 SmallVector<IdentifierInfo *, 12> KeyIdents;
3174 SmallVector<SourceLocation, 12> KeyLocs;
3175 ExprVector KeyExprs;
3177 if (Tok.is(tok::colon)) {
3179 // Each iteration parses a single keyword argument.
3180 KeyIdents.push_back(selIdent);
3181 KeyLocs.push_back(Loc);
3183 if (ExpectAndConsume(tok::colon)) {
3184 // We must manually skip to a ']', otherwise the expression skipper will
3185 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3186 // the enclosing expression.
3187 SkipUntil(tok::r_square, StopAtSemi);
3191 /// Parse the expression after ':'
3193 if (Tok.is(tok::code_completion)) {
3194 if (SuperLoc.isValid())
3195 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3197 /*AtArgumentExpression=*/true);
3198 else if (ReceiverType)
3199 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3201 /*AtArgumentExpression=*/true);
3203 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3205 /*AtArgumentExpression=*/true);
3212 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3213 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3214 Expr = ParseBraceInitializer();
3216 Expr = ParseAssignmentExpression();
3218 ExprResult Res(Expr);
3219 if (Res.isInvalid()) {
3220 // We must manually skip to a ']', otherwise the expression skipper will
3221 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3222 // the enclosing expression.
3223 SkipUntil(tok::r_square, StopAtSemi);
3227 // We have a valid expression.
3228 KeyExprs.push_back(Res.get());
3230 // Code completion after each argument.
3231 if (Tok.is(tok::code_completion)) {
3232 if (SuperLoc.isValid())
3233 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3235 /*AtArgumentExpression=*/false);
3236 else if (ReceiverType)
3237 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3239 /*AtArgumentExpression=*/false);
3241 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3243 /*AtArgumentExpression=*/false);
3248 // Check for another keyword selector.
3249 selIdent = ParseObjCSelectorPiece(Loc);
3250 if (!selIdent && Tok.isNot(tok::colon))
3252 // We have a selector or a colon, continue parsing.
3254 // Parse the, optional, argument list, comma separated.
3255 while (Tok.is(tok::comma)) {
3256 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3257 /// Parse the expression after ','
3258 ExprResult Res(ParseAssignmentExpression());
3259 if (Tok.is(tok::colon))
3260 Res = Actions.CorrectDelayedTyposInExpr(Res);
3261 if (Res.isInvalid()) {
3262 if (Tok.is(tok::colon)) {
3263 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3264 FixItHint::CreateRemoval(commaLoc);
3266 // We must manually skip to a ']', otherwise the expression skipper will
3267 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3268 // the enclosing expression.
3269 SkipUntil(tok::r_square, StopAtSemi);
3273 // We have a valid expression.
3274 KeyExprs.push_back(Res.get());
3276 } else if (!selIdent) {
3277 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3279 // We must manually skip to a ']', otherwise the expression skipper will
3280 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3281 // the enclosing expression.
3282 SkipUntil(tok::r_square, StopAtSemi);
3286 if (Tok.isNot(tok::r_square)) {
3287 Diag(Tok, diag::err_expected)
3288 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3289 // We must manually skip to a ']', otherwise the expression skipper will
3290 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3291 // the enclosing expression.
3292 SkipUntil(tok::r_square, StopAtSemi);
3296 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3298 unsigned nKeys = KeyIdents.size();
3300 KeyIdents.push_back(selIdent);
3301 KeyLocs.push_back(Loc);
3303 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3305 if (SuperLoc.isValid())
3306 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3307 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3308 else if (ReceiverType)
3309 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3310 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3311 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3312 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3315 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3316 ExprResult Res(ParseStringLiteralExpression());
3317 if (Res.isInvalid()) return Res;
3319 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3320 // expressions. At this point, we know that the only valid thing that starts
3321 // with '@' is an @"".
3322 SmallVector<SourceLocation, 4> AtLocs;
3323 ExprVector AtStrings;
3324 AtLocs.push_back(AtLoc);
3325 AtStrings.push_back(Res.get());
3327 while (Tok.is(tok::at)) {
3328 AtLocs.push_back(ConsumeToken()); // eat the @.
3330 // Invalid unless there is a string literal.
3331 if (!isTokenStringLiteral())
3332 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3334 ExprResult Lit(ParseStringLiteralExpression());
3335 if (Lit.isInvalid())
3338 AtStrings.push_back(Lit.get());
3341 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3344 /// ParseObjCBooleanLiteral -
3345 /// objc-scalar-literal : '@' boolean-keyword
3347 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3349 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3351 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3352 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3355 /// ParseObjCCharacterLiteral -
3356 /// objc-scalar-literal : '@' character-literal
3358 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3359 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3360 if (Lit.isInvalid()) {
3363 ConsumeToken(); // Consume the literal token.
3364 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3367 /// ParseObjCNumericLiteral -
3368 /// objc-scalar-literal : '@' scalar-literal
3370 /// scalar-literal : | numeric-constant /* any numeric constant. */
3372 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3373 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3374 if (Lit.isInvalid()) {
3377 ConsumeToken(); // Consume the literal token.
3378 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3381 /// ParseObjCBoxedExpr -
3382 /// objc-box-expression:
3383 /// @( assignment-expression )
3385 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3386 if (Tok.isNot(tok::l_paren))
3387 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3389 BalancedDelimiterTracker T(*this, tok::l_paren);
3391 ExprResult ValueExpr(ParseAssignmentExpression());
3392 if (T.consumeClose())
3395 if (ValueExpr.isInvalid())
3398 // Wrap the sub-expression in a parenthesized expression, to distinguish
3399 // a boxed expression from a literal.
3400 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3401 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3402 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3406 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3407 ExprVector ElementExprs; // array elements.
3408 ConsumeBracket(); // consume the l_square.
3410 bool HasInvalidEltExpr = false;
3411 while (Tok.isNot(tok::r_square)) {
3412 // Parse list of array element expressions (all must be id types).
3413 ExprResult Res(ParseAssignmentExpression());
3414 if (Res.isInvalid()) {
3415 // We must manually skip to a ']', otherwise the expression skipper will
3416 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3417 // the enclosing expression.
3418 SkipUntil(tok::r_square, StopAtSemi);
3422 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3423 if (Res.isInvalid())
3424 HasInvalidEltExpr = true;
3426 // Parse the ellipsis that indicates a pack expansion.
3427 if (Tok.is(tok::ellipsis))
3428 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3429 if (Res.isInvalid())
3430 HasInvalidEltExpr = true;
3432 ElementExprs.push_back(Res.get());
3434 if (Tok.is(tok::comma))
3435 ConsumeToken(); // Eat the ','.
3436 else if (Tok.isNot(tok::r_square))
3437 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3440 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3442 if (HasInvalidEltExpr)
3445 MultiExprArg Args(ElementExprs);
3446 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3449 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3450 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3451 ConsumeBrace(); // consume the l_square.
3452 bool HasInvalidEltExpr = false;
3453 while (Tok.isNot(tok::r_brace)) {
3454 // Parse the comma separated key : value expressions.
3457 ColonProtectionRAIIObject X(*this);
3458 KeyExpr = ParseAssignmentExpression();
3459 if (KeyExpr.isInvalid()) {
3460 // We must manually skip to a '}', otherwise the expression skipper will
3461 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3462 // the enclosing expression.
3463 SkipUntil(tok::r_brace, StopAtSemi);
3468 if (ExpectAndConsume(tok::colon)) {
3469 SkipUntil(tok::r_brace, StopAtSemi);
3473 ExprResult ValueExpr(ParseAssignmentExpression());
3474 if (ValueExpr.isInvalid()) {
3475 // We must manually skip to a '}', otherwise the expression skipper will
3476 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3477 // the enclosing expression.
3478 SkipUntil(tok::r_brace, StopAtSemi);
3482 // Check the key and value for possible typos
3483 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3484 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3485 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3486 HasInvalidEltExpr = true;
3488 // Parse the ellipsis that designates this as a pack expansion. Do not
3489 // ActOnPackExpansion here, leave it to template instantiation time where
3490 // we can get better diagnostics.
3491 SourceLocation EllipsisLoc;
3492 if (getLangOpts().CPlusPlus)
3493 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3495 // We have a valid expression. Collect it in a vector so we can
3496 // build the argument list.
3497 ObjCDictionaryElement Element = {
3498 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3500 Elements.push_back(Element);
3502 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3503 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3506 SourceLocation EndLoc = ConsumeBrace();
3508 if (HasInvalidEltExpr)
3511 // Create the ObjCDictionaryLiteral.
3512 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3516 /// objc-encode-expression:
3517 /// \@encode ( type-name )
3519 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3520 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3522 SourceLocation EncLoc = ConsumeToken();
3524 if (Tok.isNot(tok::l_paren))
3525 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3527 BalancedDelimiterTracker T(*this, tok::l_paren);
3530 TypeResult Ty = ParseTypeName();
3537 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3538 Ty.get(), T.getCloseLocation());
3541 /// objc-protocol-expression
3542 /// \@protocol ( protocol-name )
3544 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3545 SourceLocation ProtoLoc = ConsumeToken();
3547 if (Tok.isNot(tok::l_paren))
3548 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3550 BalancedDelimiterTracker T(*this, tok::l_paren);
3553 if (expectIdentifier())
3556 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3557 SourceLocation ProtoIdLoc = ConsumeToken();
3561 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3562 T.getOpenLocation(), ProtoIdLoc,
3563 T.getCloseLocation());
3566 /// objc-selector-expression
3567 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3568 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3569 SourceLocation SelectorLoc = ConsumeToken();
3571 if (Tok.isNot(tok::l_paren))
3572 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3574 SmallVector<IdentifierInfo *, 12> KeyIdents;
3575 SourceLocation sLoc;
3577 BalancedDelimiterTracker T(*this, tok::l_paren);
3579 bool HasOptionalParen = Tok.is(tok::l_paren);
3580 if (HasOptionalParen)
3583 if (Tok.is(tok::code_completion)) {
3584 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3589 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3590 if (!SelIdent && // missing selector name.
3591 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3592 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3594 KeyIdents.push_back(SelIdent);
3596 unsigned nColons = 0;
3597 if (Tok.isNot(tok::r_paren)) {
3599 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3601 KeyIdents.push_back(nullptr);
3602 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3606 if (Tok.is(tok::r_paren))
3609 if (Tok.is(tok::code_completion)) {
3610 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3615 // Check for another keyword selector.
3617 SelIdent = ParseObjCSelectorPiece(Loc);
3618 KeyIdents.push_back(SelIdent);
3619 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3623 if (HasOptionalParen && Tok.is(tok::r_paren))
3624 ConsumeParen(); // ')'
3626 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3627 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3628 T.getOpenLocation(),
3629 T.getCloseLocation(),
3633 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3634 // MCDecl might be null due to error in method or c-function prototype, etc.
3635 Decl *MCDecl = LM.D;
3636 bool skip = MCDecl &&
3637 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3638 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3642 // Save the current token position.
3643 SourceLocation OrigLoc = Tok.getLocation();
3645 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3646 // Store an artificial EOF token to ensure that we don't run off the end of
3647 // the method's body when we come to parse it.
3650 Eof.setKind(tok::eof);
3651 Eof.setEofData(MCDecl);
3652 Eof.setLocation(OrigLoc);
3653 LM.Toks.push_back(Eof);
3654 // Append the current token at the end of the new token stream so that it
3655 // doesn't get lost.
3656 LM.Toks.push_back(Tok);
3657 PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
3659 // Consume the previously pushed token.
3660 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3662 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3663 "Inline objective-c method not starting with '{' or 'try' or ':'");
3664 // Enter a scope for the method or c-function body.
3665 ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
3666 Scope::FnScope | Scope::DeclScope |
3667 Scope::CompoundStmtScope);
3669 // Tell the actions module that we have entered a method or c-function definition
3670 // with the specified Declarator for the method/function.
3672 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3674 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3675 if (Tok.is(tok::kw_try))
3676 ParseFunctionTryBlock(MCDecl, BodyScope);
3678 if (Tok.is(tok::colon))
3679 ParseConstructorInitializer(MCDecl);
3681 Actions.ActOnDefaultCtorInitializers(MCDecl);
3682 ParseFunctionStatementBody(MCDecl, BodyScope);
3685 if (Tok.getLocation() != OrigLoc) {
3686 // Due to parsing error, we either went over the cached tokens or
3687 // there are still cached tokens left. If it's the latter case skip the
3689 // Since this is an uncommon situation that should be avoided, use the
3690 // expensive isBeforeInTranslationUnit call.
3691 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3693 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3696 // Clean up the remaining EOF token.