1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Objective-C portions of the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/PrettyDeclStackTrace.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Parse/RAIIObjectsForParser.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
25 using namespace clang;
27 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
28 void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
29 ParsedAttributes attrs(AttrFactory);
30 if (Tok.is(tok::kw___attribute)) {
31 if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
32 Diag(Tok, diag::err_objc_postfix_attribute_hint)
33 << (Kind == tok::objc_protocol);
35 Diag(Tok, diag::err_objc_postfix_attribute);
36 ParseGNUAttributes(attrs);
40 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
41 /// external-declaration: [C99 6.9]
42 /// [OBJC] objc-class-definition
43 /// [OBJC] objc-class-declaration
44 /// [OBJC] objc-alias-declaration
45 /// [OBJC] objc-protocol-definition
46 /// [OBJC] objc-method-definition
48 Parser::DeclGroupPtrTy
49 Parser::ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs) {
50 SourceLocation AtLoc = ConsumeToken(); // the "@"
52 if (Tok.is(tok::code_completion)) {
53 Actions.CodeCompleteObjCAtDirective(getCurScope());
58 Decl *SingleDecl = nullptr;
59 switch (Tok.getObjCKeywordID()) {
61 return ParseObjCAtClassDeclaration(AtLoc);
62 case tok::objc_interface:
63 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, Attrs);
65 case tok::objc_protocol:
66 return ParseObjCAtProtocolDeclaration(AtLoc, Attrs);
67 case tok::objc_implementation:
68 return ParseObjCAtImplementationDeclaration(AtLoc);
70 return ParseObjCAtEndDeclaration(AtLoc);
71 case tok::objc_compatibility_alias:
72 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
74 case tok::objc_synthesize:
75 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
77 case tok::objc_dynamic:
78 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
80 case tok::objc_import:
81 if (getLangOpts().Modules || getLangOpts().DebuggerSupport) {
82 SingleDecl = ParseModuleImport(AtLoc);
85 Diag(AtLoc, diag::err_atimport);
87 return Actions.ConvertDeclToDeclGroup(nullptr);
89 Diag(AtLoc, diag::err_unexpected_at);
94 return Actions.ConvertDeclToDeclGroup(SingleDecl);
97 /// Class to handle popping type parameters when leaving the scope.
98 class Parser::ObjCTypeParamListScope {
101 ObjCTypeParamList *Params;
104 ObjCTypeParamListScope(Sema &Actions, Scope *S)
105 : Actions(Actions), S(S), Params(nullptr) {}
107 ~ObjCTypeParamListScope() {
111 void enter(ObjCTypeParamList *P) {
118 Actions.popObjCTypeParamList(S, Params);
124 /// objc-class-declaration:
125 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
127 /// objc-class-forward-decl:
128 /// identifier objc-type-parameter-list[opt]
130 Parser::DeclGroupPtrTy
131 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
132 ConsumeToken(); // the identifier "class"
133 SmallVector<IdentifierInfo *, 8> ClassNames;
134 SmallVector<SourceLocation, 8> ClassLocs;
135 SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
138 MaybeSkipAttributes(tok::objc_class);
139 if (expectIdentifier()) {
140 SkipUntil(tok::semi);
141 return Actions.ConvertDeclToDeclGroup(nullptr);
143 ClassNames.push_back(Tok.getIdentifierInfo());
144 ClassLocs.push_back(Tok.getLocation());
147 // Parse the optional objc-type-parameter-list.
148 ObjCTypeParamList *TypeParams = nullptr;
149 if (Tok.is(tok::less))
150 TypeParams = parseObjCTypeParamList();
151 ClassTypeParams.push_back(TypeParams);
152 if (!TryConsumeToken(tok::comma))
157 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
158 return Actions.ConvertDeclToDeclGroup(nullptr);
160 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
166 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
168 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
169 if (ock == Sema::OCK_None)
172 Decl *Decl = Actions.getObjCDeclContext();
173 if (CurParsedObjCImpl) {
174 CurParsedObjCImpl->finish(AtLoc);
176 Actions.ActOnAtEnd(getCurScope(), AtLoc);
178 Diag(AtLoc, diag::err_objc_missing_end)
179 << FixItHint::CreateInsertion(AtLoc, "@end\n");
181 Diag(Decl->getLocStart(), diag::note_objc_container_start)
187 /// objc-class-interface-attributes[opt] objc-class-interface
188 /// objc-category-interface
190 /// objc-class-interface:
191 /// '@' 'interface' identifier objc-type-parameter-list[opt]
192 /// objc-superclass[opt] objc-protocol-refs[opt]
193 /// objc-class-instance-variables[opt]
194 /// objc-interface-decl-list
197 /// objc-category-interface:
198 /// '@' 'interface' identifier objc-type-parameter-list[opt]
199 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
200 /// objc-interface-decl-list
204 /// ':' identifier objc-type-arguments[opt]
206 /// objc-class-interface-attributes:
207 /// __attribute__((visibility("default")))
208 /// __attribute__((visibility("hidden")))
209 /// __attribute__((deprecated))
210 /// __attribute__((unavailable))
211 /// __attribute__((objc_exception)) - used by NSException on 64-bit
212 /// __attribute__((objc_root_class))
214 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
215 ParsedAttributes &attrs) {
216 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
217 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
218 CheckNestedObjCContexts(AtLoc);
219 ConsumeToken(); // the "interface" identifier
221 // Code completion after '@interface'.
222 if (Tok.is(tok::code_completion)) {
223 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
228 MaybeSkipAttributes(tok::objc_interface);
230 if (expectIdentifier())
231 return nullptr; // missing class or category name.
233 // We have a class or category name - consume it.
234 IdentifierInfo *nameId = Tok.getIdentifierInfo();
235 SourceLocation nameLoc = ConsumeToken();
237 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
238 // case, LAngleLoc will be valid and ProtocolIdents will capture the
239 // protocol references (that have not yet been resolved).
240 SourceLocation LAngleLoc, EndProtoLoc;
241 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
242 ObjCTypeParamList *typeParameterList = nullptr;
243 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
244 if (Tok.is(tok::less))
245 typeParameterList = parseObjCTypeParamListOrProtocolRefs(
246 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
248 if (Tok.is(tok::l_paren) &&
249 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
251 BalancedDelimiterTracker T(*this, tok::l_paren);
254 SourceLocation categoryLoc;
255 IdentifierInfo *categoryId = nullptr;
256 if (Tok.is(tok::code_completion)) {
257 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
262 // For ObjC2, the category name is optional (not an error).
263 if (Tok.is(tok::identifier)) {
264 categoryId = Tok.getIdentifierInfo();
265 categoryLoc = ConsumeToken();
267 else if (!getLangOpts().ObjC2) {
268 Diag(Tok, diag::err_expected)
269 << tok::identifier; // missing category name.
274 if (T.getCloseLocation().isInvalid())
277 // Next, we need to check for any protocol references.
278 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
279 SmallVector<Decl *, 8> ProtocolRefs;
280 SmallVector<SourceLocation, 8> ProtocolLocs;
281 if (Tok.is(tok::less) &&
282 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
283 LAngleLoc, EndProtoLoc,
284 /*consumeLastToken=*/true))
287 Decl *CategoryType = Actions.ActOnStartCategoryInterface(
288 AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
289 ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
292 if (Tok.is(tok::l_brace))
293 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
295 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
299 // Parse a class interface.
300 IdentifierInfo *superClassId = nullptr;
301 SourceLocation superClassLoc;
302 SourceLocation typeArgsLAngleLoc;
303 SmallVector<ParsedType, 4> typeArgs;
304 SourceLocation typeArgsRAngleLoc;
305 SmallVector<Decl *, 4> protocols;
306 SmallVector<SourceLocation, 4> protocolLocs;
307 if (Tok.is(tok::colon)) { // a super class is specified.
310 // Code completion of superclass names.
311 if (Tok.is(tok::code_completion)) {
312 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
317 if (expectIdentifier())
318 return nullptr; // missing super class name.
319 superClassId = Tok.getIdentifierInfo();
320 superClassLoc = ConsumeToken();
322 // Type arguments for the superclass or protocol conformances.
323 if (Tok.is(tok::less)) {
324 parseObjCTypeArgsOrProtocolQualifiers(
325 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
326 protocols, protocolLocs, EndProtoLoc,
327 /*consumeLastToken=*/true,
328 /*warnOnIncompleteProtocols=*/true);
329 if (Tok.is(tok::eof))
334 // Next, we need to check for any protocol references.
335 if (LAngleLoc.isValid()) {
336 if (!ProtocolIdents.empty()) {
337 // We already parsed the protocols named when we thought we had a
338 // type parameter list. Translate them into actual protocol references.
339 for (const auto &pair : ProtocolIdents) {
340 protocolLocs.push_back(pair.second);
342 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
343 /*ForObjCContainer=*/true,
344 ProtocolIdents, protocols);
346 } else if (protocols.empty() && Tok.is(tok::less) &&
347 ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
348 LAngleLoc, EndProtoLoc,
349 /*consumeLastToken=*/true)) {
353 if (Tok.isNot(tok::less))
354 Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
355 superClassId, superClassLoc);
357 Decl *ClsType = Actions.ActOnStartClassInterface(
358 getCurScope(), AtLoc, nameId, nameLoc, typeParameterList, superClassId,
359 superClassLoc, typeArgs,
360 SourceRange(typeArgsLAngleLoc, typeArgsRAngleLoc), protocols.data(),
361 protocols.size(), protocolLocs.data(), EndProtoLoc, attrs);
363 if (Tok.is(tok::l_brace))
364 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
366 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
371 /// Add an attribute for a context-sensitive type nullability to the given
373 static void addContextSensitiveTypeNullability(Parser &P,
375 NullabilityKind nullability,
376 SourceLocation nullabilityLoc,
377 bool &addedToDeclSpec) {
378 // Create the attribute.
379 auto getNullabilityAttr = [&](AttributePool &Pool) -> ParsedAttr * {
380 return Pool.create(P.getNullabilityKeyword(nullability),
381 SourceRange(nullabilityLoc), nullptr, SourceLocation(),
382 nullptr, 0, ParsedAttr::AS_ContextSensitiveKeyword);
385 if (D.getNumTypeObjects() > 0) {
386 // Add the attribute to the declarator chunk nearest the declarator.
387 D.getTypeObject(0).getAttrs().addAtStart(
388 getNullabilityAttr(D.getAttributePool()));
389 } else if (!addedToDeclSpec) {
390 // Otherwise, just put it on the declaration specifiers (if one
391 // isn't there already).
392 D.getMutableDeclSpec().getAttributes().addAtStart(
393 getNullabilityAttr(D.getMutableDeclSpec().getAttributes().getPool()));
394 addedToDeclSpec = true;
398 /// Parse an Objective-C type parameter list, if present, or capture
399 /// the locations of the protocol identifiers for a list of protocol
402 /// objc-type-parameter-list:
403 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
405 /// objc-type-parameter:
406 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
408 /// objc-type-parameter-bound:
411 /// objc-type-parameter-variance:
413 /// '__contravariant'
415 /// \param lAngleLoc The location of the starting '<'.
417 /// \param protocolIdents Will capture the list of identifiers, if the
418 /// angle brackets contain a list of protocol references rather than a
419 /// type parameter list.
421 /// \param rAngleLoc The location of the ending '>'.
422 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
423 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
424 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
425 SourceLocation &rAngleLoc, bool mayBeProtocolList) {
426 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
428 // Within the type parameter list, don't treat '>' as an operator.
429 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
431 // Local function to "flush" the protocol identifiers, turning them into
433 SmallVector<Decl *, 4> typeParams;
434 auto makeProtocolIdentsIntoTypeParameters = [&]() {
436 for (const auto &pair : protocolIdents) {
437 DeclResult typeParam = Actions.actOnObjCTypeParam(
438 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
439 index++, pair.first, pair.second, SourceLocation(), nullptr);
440 if (typeParam.isUsable())
441 typeParams.push_back(typeParam.get());
444 protocolIdents.clear();
445 mayBeProtocolList = false;
448 bool invalid = false;
449 lAngleLoc = ConsumeToken();
452 // Parse the variance, if any.
453 SourceLocation varianceLoc;
454 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
455 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
456 variance = Tok.is(tok::kw___covariant)
457 ? ObjCTypeParamVariance::Covariant
458 : ObjCTypeParamVariance::Contravariant;
459 varianceLoc = ConsumeToken();
461 // Once we've seen a variance specific , we know this is not a
462 // list of protocol references.
463 if (mayBeProtocolList) {
464 // Up until now, we have been queuing up parameters because they
465 // might be protocol references. Turn them into parameters now.
466 makeProtocolIdentsIntoTypeParameters();
470 // Parse the identifier.
471 if (!Tok.is(tok::identifier)) {
473 if (Tok.is(tok::code_completion)) {
474 // FIXME: If these aren't protocol references, we'll need different
476 Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
479 // FIXME: Better recovery here?.
483 Diag(Tok, diag::err_objc_expected_type_parameter);
488 IdentifierInfo *paramName = Tok.getIdentifierInfo();
489 SourceLocation paramLoc = ConsumeToken();
491 // If there is a bound, parse it.
492 SourceLocation colonLoc;
493 TypeResult boundType;
494 if (TryConsumeToken(tok::colon, colonLoc)) {
495 // Once we've seen a bound, we know this is not a list of protocol
497 if (mayBeProtocolList) {
498 // Up until now, we have been queuing up parameters because they
499 // might be protocol references. Turn them into parameters now.
500 makeProtocolIdentsIntoTypeParameters();
504 boundType = ParseTypeName();
505 if (boundType.isInvalid())
507 } else if (mayBeProtocolList) {
508 // If this could still be a protocol list, just capture the identifier.
509 // We don't want to turn it into a parameter.
510 protocolIdents.push_back(std::make_pair(paramName, paramLoc));
514 // Create the type parameter.
515 DeclResult typeParam = Actions.actOnObjCTypeParam(
516 getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
517 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
518 if (typeParam.isUsable())
519 typeParams.push_back(typeParam.get());
520 } while (TryConsumeToken(tok::comma));
524 SkipUntil(tok::greater, tok::at, StopBeforeMatch);
525 if (Tok.is(tok::greater))
527 } else if (ParseGreaterThanInTemplateList(rAngleLoc,
528 /*ConsumeLastToken=*/true,
529 /*ObjCGenericList=*/true)) {
530 Diag(lAngleLoc, diag::note_matching) << "'<'";
531 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
532 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
533 tok::comma, tok::semi },
535 if (Tok.is(tok::greater))
539 if (mayBeProtocolList) {
540 // A type parameter list must be followed by either a ':' (indicating the
541 // presence of a superclass) or a '(' (indicating that this is a category
542 // or extension). This disambiguates between an objc-type-parameter-list
543 // and a objc-protocol-refs.
544 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
545 // Returning null indicates that we don't have a type parameter list.
546 // The results the caller needs to handle the protocol references are
547 // captured in the reference parameters already.
551 // We have a type parameter list that looks like a list of protocol
552 // references. Turn that parameter list into type parameters.
553 makeProtocolIdentsIntoTypeParameters();
556 // Form the type parameter list and enter its scope.
557 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
564 // Clear out the angle locations; they're used by the caller to indicate
565 // whether there are any protocol references.
566 lAngleLoc = SourceLocation();
567 rAngleLoc = SourceLocation();
568 return invalid ? nullptr : list;
571 /// Parse an objc-type-parameter-list.
572 ObjCTypeParamList *Parser::parseObjCTypeParamList() {
573 SourceLocation lAngleLoc;
574 SmallVector<IdentifierLocPair, 1> protocolIdents;
575 SourceLocation rAngleLoc;
577 ObjCTypeParamListScope Scope(Actions, getCurScope());
578 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
580 /*mayBeProtocolList=*/false);
583 /// objc-interface-decl-list:
585 /// objc-interface-decl-list objc-property-decl [OBJC2]
586 /// objc-interface-decl-list objc-method-requirement [OBJC2]
587 /// objc-interface-decl-list objc-method-proto ';'
588 /// objc-interface-decl-list declaration
589 /// objc-interface-decl-list ';'
591 /// objc-method-requirement: [OBJC2]
595 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
597 SmallVector<Decl *, 32> allMethods;
598 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
599 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
604 // If this is a method prototype, parse it.
605 if (Tok.isOneOf(tok::minus, tok::plus)) {
606 if (Decl *methodPrototype =
607 ParseObjCMethodPrototype(MethodImplKind, false))
608 allMethods.push_back(methodPrototype);
609 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
610 // method definitions.
611 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
612 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
613 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
614 if (Tok.is(tok::semi))
619 if (Tok.is(tok::l_paren)) {
620 Diag(Tok, diag::err_expected_minus_or_plus);
621 ParseObjCMethodDecl(Tok.getLocation(),
623 MethodImplKind, false);
626 // Ignore excess semicolons.
627 if (Tok.is(tok::semi)) {
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))
651 ParsedAttributesWithRange attrs(AttrFactory);
652 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
656 // Otherwise, we have an @ directive, eat the @.
657 SourceLocation AtLoc = ConsumeToken(); // the "@"
658 if (Tok.is(tok::code_completion)) {
659 Actions.CodeCompleteObjCAtDirective(getCurScope());
660 return cutOffParsing();
663 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
665 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
666 AtEnd.setBegin(AtLoc);
667 AtEnd.setEnd(Tok.getLocation());
669 } else if (DirectiveKind == tok::objc_not_keyword) {
670 Diag(Tok, diag::err_objc_unknown_at);
671 SkipUntil(tok::semi);
675 // Eat the identifier.
678 switch (DirectiveKind) {
680 // FIXME: If someone forgets an @end on a protocol, this loop will
681 // continue to eat up tons of stuff and spew lots of nonsense errors. It
682 // would probably be better to bail out if we saw an @class or @interface
683 // or something like that.
684 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
685 // Skip until we see an '@' or '}' or ';'.
686 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
689 case tok::objc_implementation:
690 case tok::objc_interface:
691 Diag(AtLoc, diag::err_objc_missing_end)
692 << FixItHint::CreateInsertion(AtLoc, "@end\n");
693 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
694 << (int) Actions.getObjCContainerKind();
698 case tok::objc_required:
699 case tok::objc_optional:
700 // This is only valid on protocols.
701 // FIXME: Should this check for ObjC2 being enabled?
702 if (contextKey != tok::objc_protocol)
703 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
705 MethodImplKind = DirectiveKind;
708 case tok::objc_property:
709 if (!getLangOpts().ObjC2)
710 Diag(AtLoc, diag::err_objc_properties_require_objc2);
713 SourceLocation LParenLoc;
714 // Parse property attribute list, if any.
715 if (Tok.is(tok::l_paren)) {
716 LParenLoc = Tok.getLocation();
717 ParseObjCPropertyAttribute(OCDS);
720 bool addedToDeclSpec = false;
721 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
722 if (FD.D.getIdentifier() == nullptr) {
723 Diag(AtLoc, diag::err_objc_property_requires_field_name)
724 << FD.D.getSourceRange();
727 if (FD.BitfieldSize) {
728 Diag(AtLoc, diag::err_objc_property_bitfield)
729 << FD.D.getSourceRange();
733 // Map a nullability property attribute to a context-sensitive keyword
735 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
736 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
737 OCDS.getNullabilityLoc(),
740 // Install the property declarator into interfaceDecl.
741 IdentifierInfo *SelName =
742 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
744 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
745 IdentifierInfo *SetterName = OCDS.getSetterName();
748 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
750 SetterSel = SelectorTable::constructSetterSelector(
751 PP.getIdentifierTable(), PP.getSelectorTable(),
752 FD.D.getIdentifier());
753 Decl *Property = Actions.ActOnProperty(
754 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
757 FD.complete(Property);
760 // Parse all the comma separated declarators.
761 ParsingDeclSpec DS(*this);
762 ParseStructDeclaration(DS, ObjCPropertyCallback);
764 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
769 // We break out of the big loop in two cases: when we see @end or when we see
770 // EOF. In the former case, eat the @end. In the later case, emit an error.
771 if (Tok.is(tok::code_completion)) {
772 Actions.CodeCompleteObjCAtDirective(getCurScope());
773 return cutOffParsing();
774 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
775 ConsumeToken(); // the "end" identifier
777 Diag(Tok, diag::err_objc_missing_end)
778 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
779 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
780 << (int) Actions.getObjCContainerKind();
781 AtEnd.setBegin(Tok.getLocation());
782 AtEnd.setEnd(Tok.getLocation());
785 // Insert collected methods declarations into the @interface object.
786 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
787 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
790 /// Diagnose redundant or conflicting nullability information.
791 static void diagnoseRedundantPropertyNullability(Parser &P,
793 NullabilityKind nullability,
794 SourceLocation nullabilityLoc){
795 if (DS.getNullability() == nullability) {
796 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
797 << DiagNullabilityKind(nullability, true)
798 << SourceRange(DS.getNullabilityLoc());
802 P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
803 << DiagNullabilityKind(nullability, true)
804 << DiagNullabilityKind(DS.getNullability(), true)
805 << SourceRange(DS.getNullabilityLoc());
808 /// Parse property attribute declarations.
810 /// property-attr-decl: '(' property-attrlist ')'
811 /// property-attrlist:
812 /// property-attribute
813 /// property-attrlist ',' property-attribute
814 /// property-attribute:
815 /// getter '=' identifier
816 /// setter '=' identifier ':'
826 /// unsafe_unretained
833 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
834 assert(Tok.getKind() == tok::l_paren);
835 BalancedDelimiterTracker T(*this, tok::l_paren);
839 if (Tok.is(tok::code_completion)) {
840 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
841 return cutOffParsing();
843 const IdentifierInfo *II = Tok.getIdentifierInfo();
845 // If this is not an identifier at all, bail out early.
851 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
853 if (II->isStr("readonly"))
854 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
855 else if (II->isStr("assign"))
856 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
857 else if (II->isStr("unsafe_unretained"))
858 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
859 else if (II->isStr("readwrite"))
860 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
861 else if (II->isStr("retain"))
862 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
863 else if (II->isStr("strong"))
864 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
865 else if (II->isStr("copy"))
866 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
867 else if (II->isStr("nonatomic"))
868 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
869 else if (II->isStr("atomic"))
870 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
871 else if (II->isStr("weak"))
872 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
873 else if (II->isStr("getter") || II->isStr("setter")) {
874 bool IsSetter = II->getNameStart()[0] == 's';
876 // getter/setter require extra treatment.
877 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
878 diag::err_objc_expected_equal_for_getter;
880 if (ExpectAndConsume(tok::equal, DiagID)) {
881 SkipUntil(tok::r_paren, StopAtSemi);
885 if (Tok.is(tok::code_completion)) {
887 Actions.CodeCompleteObjCPropertySetter(getCurScope());
889 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
890 return cutOffParsing();
893 SourceLocation SelLoc;
894 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
897 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
899 SkipUntil(tok::r_paren, StopAtSemi);
904 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
905 DS.setSetterName(SelIdent, SelLoc);
907 if (ExpectAndConsume(tok::colon,
908 diag::err_expected_colon_after_setter_name)) {
909 SkipUntil(tok::r_paren, StopAtSemi);
913 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
914 DS.setGetterName(SelIdent, SelLoc);
916 } else if (II->isStr("nonnull")) {
917 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
918 diagnoseRedundantPropertyNullability(*this, DS,
919 NullabilityKind::NonNull,
921 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
922 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
923 } else if (II->isStr("nullable")) {
924 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
925 diagnoseRedundantPropertyNullability(*this, DS,
926 NullabilityKind::Nullable,
928 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
929 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
930 } else if (II->isStr("null_unspecified")) {
931 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
932 diagnoseRedundantPropertyNullability(*this, DS,
933 NullabilityKind::Unspecified,
935 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
936 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
937 } else if (II->isStr("null_resettable")) {
938 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
939 diagnoseRedundantPropertyNullability(*this, DS,
940 NullabilityKind::Unspecified,
942 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
943 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
945 // Also set the null_resettable bit.
946 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable);
947 } else if (II->isStr("class")) {
948 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class);
950 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
951 SkipUntil(tok::r_paren, StopAtSemi);
955 if (Tok.isNot(tok::comma))
964 /// objc-method-proto:
965 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
966 /// objc-class-method objc-method-decl objc-method-attributes[opt]
968 /// objc-instance-method: '-'
969 /// objc-class-method: '+'
971 /// objc-method-attributes: [OBJC2]
972 /// __attribute__((deprecated))
974 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
975 bool MethodDefinition) {
976 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
978 tok::TokenKind methodType = Tok.getKind();
979 SourceLocation mLoc = ConsumeToken();
980 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
982 // Since this rule is used for both method declarations and definitions,
983 // the caller is (optionally) responsible for consuming the ';'.
990 /// enum struct union if else while do for switch case default
991 /// break continue return goto asm sizeof typeof __alignof
992 /// unsigned long const short volatile signed restrict _Complex
993 /// in out inout bycopy byref oneway int char float double void _Bool
995 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
997 switch (Tok.getKind()) {
1001 // Empty selector piece uses the location of the ':'.
1002 SelectorLoc = Tok.getLocation();
1010 case tok::exclaimequal:
1012 case tok::pipeequal:
1014 case tok::caretequal: {
1015 std::string ThisTok(PP.getSpelling(Tok));
1016 if (isLetter(ThisTok[0])) {
1017 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1018 Tok.setKind(tok::identifier);
1019 SelectorLoc = ConsumeToken();
1025 case tok::identifier:
1035 case tok::kw_const_cast:
1036 case tok::kw_continue:
1037 case tok::kw_default:
1038 case tok::kw_delete:
1040 case tok::kw_double:
1041 case tok::kw_dynamic_cast:
1044 case tok::kw_explicit:
1045 case tok::kw_export:
1046 case tok::kw_extern:
1050 case tok::kw_friend:
1053 case tok::kw_inline:
1056 case tok::kw_mutable:
1057 case tok::kw_namespace:
1059 case tok::kw_operator:
1060 case tok::kw_private:
1061 case tok::kw_protected:
1062 case tok::kw_public:
1063 case tok::kw_register:
1064 case tok::kw_reinterpret_cast:
1065 case tok::kw_restrict:
1066 case tok::kw_return:
1068 case tok::kw_signed:
1069 case tok::kw_sizeof:
1070 case tok::kw_static:
1071 case tok::kw_static_cast:
1072 case tok::kw_struct:
1073 case tok::kw_switch:
1074 case tok::kw_template:
1079 case tok::kw_typedef:
1080 case tok::kw_typeid:
1081 case tok::kw_typename:
1082 case tok::kw_typeof:
1084 case tok::kw_unsigned:
1086 case tok::kw_virtual:
1088 case tok::kw_volatile:
1089 case tok::kw_wchar_t:
1092 case tok::kw__Complex:
1093 case tok::kw___alignof:
1094 case tok::kw___auto_type:
1095 IdentifierInfo *II = Tok.getIdentifierInfo();
1096 SelectorLoc = ConsumeToken();
1101 /// objc-for-collection-in: 'in'
1103 bool Parser::isTokIdentifier_in() const {
1104 // FIXME: May have to do additional look-ahead to only allow for
1105 // valid tokens following an 'in'; such as an identifier, unary operators,
1107 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
1108 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1111 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1112 /// qualifier list and builds their bitmask representation in the input
1115 /// objc-type-qualifiers:
1116 /// objc-type-qualifier
1117 /// objc-type-qualifiers objc-type-qualifier
1119 /// objc-type-qualifier:
1128 /// 'null_unspecified'
1130 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1131 DeclaratorContext Context) {
1132 assert(Context == DeclaratorContext::ObjCParameterContext ||
1133 Context == DeclaratorContext::ObjCResultContext);
1136 if (Tok.is(tok::code_completion)) {
1137 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
1138 Context == DeclaratorContext::ObjCParameterContext);
1139 return cutOffParsing();
1142 if (Tok.isNot(tok::identifier))
1145 const IdentifierInfo *II = Tok.getIdentifierInfo();
1146 for (unsigned i = 0; i != objc_NumQuals; ++i) {
1147 if (II != ObjCTypeQuals[i] ||
1148 NextToken().is(tok::less) ||
1149 NextToken().is(tok::coloncolon))
1152 ObjCDeclSpec::ObjCDeclQualifier Qual;
1153 NullabilityKind Nullability;
1155 default: llvm_unreachable("Unknown decl qualifier");
1156 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
1157 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
1158 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
1159 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1160 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1161 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
1164 Qual = ObjCDeclSpec::DQ_CSNullability;
1165 Nullability = NullabilityKind::NonNull;
1169 Qual = ObjCDeclSpec::DQ_CSNullability;
1170 Nullability = NullabilityKind::Nullable;
1173 case objc_null_unspecified:
1174 Qual = ObjCDeclSpec::DQ_CSNullability;
1175 Nullability = NullabilityKind::Unspecified;
1179 // FIXME: Diagnose redundant specifiers.
1180 DS.setObjCDeclQualifier(Qual);
1181 if (Qual == ObjCDeclSpec::DQ_CSNullability)
1182 DS.setNullability(Tok.getLocation(), Nullability);
1189 // If this wasn't a recognized qualifier, bail out.
1194 /// Take all the decl attributes out of the given list and add
1195 /// them to the given attribute set.
1196 static void takeDeclAttributes(ParsedAttributesView &attrs,
1197 ParsedAttributesView &from) {
1198 for (auto &AL : llvm::reverse(from)) {
1199 if (!AL.isUsedAsTypeAttr()) {
1201 attrs.addAtStart(&AL);
1206 /// takeDeclAttributes - Take all the decl attributes from the given
1207 /// declarator and add them to the given list.
1208 static void takeDeclAttributes(ParsedAttributes &attrs,
1210 // First, take ownership of all attributes.
1211 attrs.getPool().takeAllFrom(D.getAttributePool());
1212 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1214 // Now actually move the attributes over.
1215 takeDeclAttributes(attrs, D.getMutableDeclSpec().getAttributes());
1216 takeDeclAttributes(attrs, D.getAttributes());
1217 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1218 takeDeclAttributes(attrs, D.getTypeObject(i).getAttrs());
1222 /// '(' objc-type-qualifiers[opt] type-name ')'
1223 /// '(' objc-type-qualifiers[opt] ')'
1225 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1226 DeclaratorContext context,
1227 ParsedAttributes *paramAttrs) {
1228 assert(context == DeclaratorContext::ObjCParameterContext ||
1229 context == DeclaratorContext::ObjCResultContext);
1230 assert((paramAttrs != nullptr) ==
1231 (context == DeclaratorContext::ObjCParameterContext));
1233 assert(Tok.is(tok::l_paren) && "expected (");
1235 BalancedDelimiterTracker T(*this, tok::l_paren);
1238 SourceLocation TypeStartLoc = Tok.getLocation();
1239 ObjCDeclContextSwitch ObjCDC(*this);
1241 // Parse type qualifiers, in, inout, etc.
1242 ParseObjCTypeQualifierList(DS, context);
1245 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1246 // Parse an abstract declarator.
1247 DeclSpec declSpec(AttrFactory);
1248 declSpec.setObjCQualifiers(&DS);
1249 DeclSpecContext dsContext = DeclSpecContext::DSC_normal;
1250 if (context == DeclaratorContext::ObjCResultContext)
1251 dsContext = DeclSpecContext::DSC_objc_method_result;
1252 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1253 Declarator declarator(declSpec, context);
1254 ParseDeclarator(declarator);
1256 // If that's not invalid, extract a type.
1257 if (!declarator.isInvalidType()) {
1258 // Map a nullability specifier to a context-sensitive keyword attribute.
1259 bool addedToDeclSpec = false;
1260 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1261 addContextSensitiveTypeNullability(*this, declarator,
1262 DS.getNullability(),
1263 DS.getNullabilityLoc(),
1266 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1267 if (!type.isInvalid())
1270 // If we're parsing a parameter, steal all the decl attributes
1271 // and add them to the decl spec.
1272 if (context == DeclaratorContext::ObjCParameterContext)
1273 takeDeclAttributes(*paramAttrs, declarator);
1277 if (Tok.is(tok::r_paren))
1279 else if (Tok.getLocation() == TypeStartLoc) {
1280 // If we didn't eat any tokens, then this isn't a type.
1281 Diag(Tok, diag::err_expected_type);
1282 SkipUntil(tok::r_paren, StopAtSemi);
1284 // Otherwise, we found *something*, but didn't get a ')' in the right
1285 // place. Emit an error then return what we have as the type.
1291 /// objc-method-decl:
1293 /// objc-keyword-selector objc-parmlist[opt]
1294 /// objc-type-name objc-selector
1295 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1297 /// objc-keyword-selector:
1298 /// objc-keyword-decl
1299 /// objc-keyword-selector objc-keyword-decl
1301 /// objc-keyword-decl:
1302 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1303 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1304 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1305 /// ':' objc-keyword-attributes[opt] identifier
1308 /// objc-parms objc-ellipsis[opt]
1311 /// objc-parms , parameter-declaration
1316 /// objc-keyword-attributes: [OBJC2]
1317 /// __attribute__((unused))
1319 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1320 tok::TokenKind mType,
1321 tok::ObjCKeywordKind MethodImplKind,
1322 bool MethodDefinition) {
1323 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1325 if (Tok.is(tok::code_completion)) {
1326 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1327 /*ReturnType=*/nullptr);
1332 // Parse the return type if present.
1333 ParsedType ReturnType;
1335 if (Tok.is(tok::l_paren))
1336 ReturnType = ParseObjCTypeName(DSRet, DeclaratorContext::ObjCResultContext,
1339 // If attributes exist before the method, parse them.
1340 ParsedAttributes methodAttrs(AttrFactory);
1341 if (getLangOpts().ObjC2)
1342 MaybeParseGNUAttributes(methodAttrs);
1343 MaybeParseCXX11Attributes(methodAttrs);
1345 if (Tok.is(tok::code_completion)) {
1346 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1352 // Now parse the selector.
1353 SourceLocation selLoc;
1354 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1356 // An unnamed colon is valid.
1357 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1358 Diag(Tok, diag::err_expected_selector_for_method)
1359 << SourceRange(mLoc, Tok.getLocation());
1360 // Skip until we get a ; or @.
1361 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1365 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1366 if (Tok.isNot(tok::colon)) {
1367 // If attributes exist after the method, parse them.
1368 if (getLangOpts().ObjC2)
1369 MaybeParseGNUAttributes(methodAttrs);
1370 MaybeParseCXX11Attributes(methodAttrs);
1372 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1373 Decl *Result = Actions.ActOnMethodDeclaration(
1374 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType,
1375 selLoc, Sel, nullptr, CParamInfo.data(), CParamInfo.size(), methodAttrs,
1376 MethodImplKind, false, MethodDefinition);
1377 PD.complete(Result);
1381 SmallVector<IdentifierInfo *, 12> KeyIdents;
1382 SmallVector<SourceLocation, 12> KeyLocs;
1383 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1384 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1385 Scope::FunctionDeclarationScope | Scope::DeclScope);
1387 AttributePool allParamAttrs(AttrFactory);
1389 ParsedAttributes paramAttrs(AttrFactory);
1390 Sema::ObjCArgInfo ArgInfo;
1392 // Each iteration parses a single keyword argument.
1393 if (ExpectAndConsume(tok::colon))
1396 ArgInfo.Type = nullptr;
1397 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1398 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1399 DeclaratorContext::ObjCParameterContext,
1402 // If attributes exist before the argument name, parse them.
1403 // Regardless, collect all the attributes we've parsed so far.
1404 if (getLangOpts().ObjC2)
1405 MaybeParseGNUAttributes(paramAttrs);
1406 MaybeParseCXX11Attributes(paramAttrs);
1407 ArgInfo.ArgAttrs = paramAttrs;
1409 // Code completion for the next piece of the selector.
1410 if (Tok.is(tok::code_completion)) {
1411 KeyIdents.push_back(SelIdent);
1412 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1413 mType == tok::minus,
1414 /*AtParameterName=*/true,
1415 ReturnType, KeyIdents);
1420 if (expectIdentifier())
1421 break; // missing argument name.
1423 ArgInfo.Name = Tok.getIdentifierInfo();
1424 ArgInfo.NameLoc = Tok.getLocation();
1425 ConsumeToken(); // Eat the identifier.
1427 ArgInfos.push_back(ArgInfo);
1428 KeyIdents.push_back(SelIdent);
1429 KeyLocs.push_back(selLoc);
1431 // Make sure the attributes persist.
1432 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1434 // Code completion for the next piece of the selector.
1435 if (Tok.is(tok::code_completion)) {
1436 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1437 mType == tok::minus,
1438 /*AtParameterName=*/false,
1439 ReturnType, KeyIdents);
1444 // Check for another keyword selector.
1445 SelIdent = ParseObjCSelectorPiece(selLoc);
1446 if (!SelIdent && Tok.isNot(tok::colon))
1449 SourceLocation ColonLoc = Tok.getLocation();
1450 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1451 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1452 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1453 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1456 // We have a selector or a colon, continue parsing.
1459 bool isVariadic = false;
1460 bool cStyleParamWarned = false;
1461 // Parse the (optional) parameter list.
1462 while (Tok.is(tok::comma)) {
1464 if (Tok.is(tok::ellipsis)) {
1469 if (!cStyleParamWarned) {
1470 Diag(Tok, diag::warn_cstyle_param);
1471 cStyleParamWarned = true;
1473 DeclSpec DS(AttrFactory);
1474 ParseDeclarationSpecifiers(DS);
1475 // Parse the declarator.
1476 Declarator ParmDecl(DS, DeclaratorContext::PrototypeContext);
1477 ParseDeclarator(ParmDecl);
1478 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1479 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1480 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1481 ParmDecl.getIdentifierLoc(),
1486 // FIXME: Add support for optional parameter list...
1487 // If attributes exist after the method, parse them.
1488 if (getLangOpts().ObjC2)
1489 MaybeParseGNUAttributes(methodAttrs);
1490 MaybeParseCXX11Attributes(methodAttrs);
1492 if (KeyIdents.size() == 0)
1495 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1497 Decl *Result = Actions.ActOnMethodDeclaration(
1498 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, KeyLocs,
1499 Sel, &ArgInfos[0], CParamInfo.data(), CParamInfo.size(), methodAttrs,
1500 MethodImplKind, isVariadic, MethodDefinition);
1502 PD.complete(Result);
1506 /// objc-protocol-refs:
1507 /// '<' identifier-list '>'
1510 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1511 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1512 bool WarnOnDeclarations, bool ForObjCContainer,
1513 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1514 bool consumeLastToken) {
1515 assert(Tok.is(tok::less) && "expected <");
1517 LAngleLoc = ConsumeToken(); // the "<"
1519 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1522 if (Tok.is(tok::code_completion)) {
1523 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1528 if (expectIdentifier()) {
1529 SkipUntil(tok::greater, StopAtSemi);
1532 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1533 Tok.getLocation()));
1534 ProtocolLocs.push_back(Tok.getLocation());
1537 if (!TryConsumeToken(tok::comma))
1542 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1543 /*ObjCGenericList=*/false))
1546 // Convert the list of protocols identifiers into a list of protocol decls.
1547 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1548 ProtocolIdents, Protocols);
1552 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1553 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1554 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1556 SourceLocation lAngleLoc;
1557 SmallVector<Decl *, 8> protocols;
1558 SmallVector<SourceLocation, 8> protocolLocs;
1559 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1560 lAngleLoc, rAngleLoc,
1561 /*consumeLastToken=*/true);
1562 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1566 if (result.isUsable()) {
1567 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1568 << FixItHint::CreateInsertion(lAngleLoc, "id")
1569 << SourceRange(lAngleLoc, rAngleLoc);
1575 /// Parse Objective-C type arguments or protocol qualifiers.
1577 /// objc-type-arguments:
1578 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1580 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1581 ParsedType baseType,
1582 SourceLocation &typeArgsLAngleLoc,
1583 SmallVectorImpl<ParsedType> &typeArgs,
1584 SourceLocation &typeArgsRAngleLoc,
1585 SourceLocation &protocolLAngleLoc,
1586 SmallVectorImpl<Decl *> &protocols,
1587 SmallVectorImpl<SourceLocation> &protocolLocs,
1588 SourceLocation &protocolRAngleLoc,
1589 bool consumeLastToken,
1590 bool warnOnIncompleteProtocols) {
1591 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1592 SourceLocation lAngleLoc = ConsumeToken();
1594 // Whether all of the elements we've parsed thus far are single
1595 // identifiers, which might be types or might be protocols.
1596 bool allSingleIdentifiers = true;
1597 SmallVector<IdentifierInfo *, 4> identifiers;
1598 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1600 // Parse a list of comma-separated identifiers, bailing out if we
1601 // see something different.
1603 // Parse a single identifier.
1604 if (Tok.is(tok::identifier) &&
1605 (NextToken().is(tok::comma) ||
1606 NextToken().is(tok::greater) ||
1607 NextToken().is(tok::greatergreater))) {
1608 identifiers.push_back(Tok.getIdentifierInfo());
1609 identifierLocs.push_back(ConsumeToken());
1613 if (Tok.is(tok::code_completion)) {
1614 // FIXME: Also include types here.
1615 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1616 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1617 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1618 identifierLocs[i]));
1621 QualType BaseT = Actions.GetTypeFromParser(baseType);
1622 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1623 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1625 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1631 allSingleIdentifiers = false;
1633 } while (TryConsumeToken(tok::comma));
1635 // If we parsed an identifier list, semantic analysis sorts out
1636 // whether it refers to protocols or to type arguments.
1637 if (allSingleIdentifiers) {
1638 // Parse the closing '>'.
1639 SourceLocation rAngleLoc;
1640 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1641 /*ObjCGenericList=*/true);
1643 // Let Sema figure out what we parsed.
1644 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1656 warnOnIncompleteProtocols);
1660 // We parsed an identifier list but stumbled into non single identifiers, this
1661 // means we might (a) check that what we already parsed is a legitimate type
1662 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1663 // must all be type args.
1665 // Convert the identifiers into type arguments.
1666 bool invalid = false;
1667 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1668 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1669 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1670 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1672 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1674 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1676 DeclSpec DS(AttrFactory);
1677 const char *prevSpec = nullptr;
1679 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1680 typeArg, Actions.getASTContext().getPrintingPolicy());
1682 // Form a declarator to turn this into a type.
1683 Declarator D(DS, DeclaratorContext::TypeNameContext);
1684 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1685 if (fullTypeArg.isUsable()) {
1686 typeArgs.push_back(fullTypeArg.get());
1687 if (!foundValidTypeId) {
1688 foundValidTypeId = identifiers[i];
1689 foundValidTypeSrcLoc = identifierLocs[i];
1693 unknownTypeArgs.push_back(identifiers[i]);
1694 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1698 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1699 unknownTypeArgs.push_back(identifiers[i]);
1700 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1701 } else if (!foundProtocolId) {
1702 foundProtocolId = identifiers[i];
1703 foundProtocolSrcLoc = identifierLocs[i];
1708 // Continue parsing type-names.
1710 Token CurTypeTok = Tok;
1711 TypeResult typeArg = ParseTypeName();
1713 // Consume the '...' for a pack expansion.
1714 SourceLocation ellipsisLoc;
1715 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1716 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1717 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1720 if (typeArg.isUsable()) {
1721 typeArgs.push_back(typeArg.get());
1722 if (!foundValidTypeId) {
1723 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1724 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1729 } while (TryConsumeToken(tok::comma));
1731 // Diagnose the mix between type args and protocols.
1732 if (foundProtocolId && foundValidTypeId)
1733 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1735 foundValidTypeSrcLoc);
1737 // Diagnose unknown arg types.
1739 if (unknownTypeArgs.size())
1740 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1741 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1742 getCurScope(), nullptr, T);
1744 // Parse the closing '>'.
1745 SourceLocation rAngleLoc;
1746 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1747 /*ObjCGenericList=*/true);
1754 // Record left/right angle locations.
1755 typeArgsLAngleLoc = lAngleLoc;
1756 typeArgsRAngleLoc = rAngleLoc;
1759 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1760 ParsedType baseType,
1761 SourceLocation &typeArgsLAngleLoc,
1762 SmallVectorImpl<ParsedType> &typeArgs,
1763 SourceLocation &typeArgsRAngleLoc,
1764 SourceLocation &protocolLAngleLoc,
1765 SmallVectorImpl<Decl *> &protocols,
1766 SmallVectorImpl<SourceLocation> &protocolLocs,
1767 SourceLocation &protocolRAngleLoc,
1768 bool consumeLastToken) {
1769 assert(Tok.is(tok::less));
1771 // Parse the first angle-bracket-delimited clause.
1772 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1781 /*warnOnIncompleteProtocols=*/false);
1782 if (Tok.is(tok::eof)) // Nothing else to do here...
1785 // An Objective-C object pointer followed by type arguments
1786 // can then be followed again by a set of protocol references, e.g.,
1787 // \c NSArray<NSView><NSTextDelegate>
1788 if ((consumeLastToken && Tok.is(tok::less)) ||
1789 (!consumeLastToken && NextToken().is(tok::less))) {
1790 // If we aren't consuming the last token, the prior '>' is still hanging
1791 // there. Consume it before we parse the protocol qualifiers.
1792 if (!consumeLastToken)
1795 if (!protocols.empty()) {
1796 SkipUntilFlags skipFlags = SkipUntilFlags();
1797 if (!consumeLastToken)
1798 skipFlags = skipFlags | StopBeforeMatch;
1799 Diag(Tok, diag::err_objc_type_args_after_protocols)
1800 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1801 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1803 ParseObjCProtocolReferences(protocols, protocolLocs,
1804 /*WarnOnDeclarations=*/false,
1805 /*ForObjCContainer=*/false,
1806 protocolLAngleLoc, protocolRAngleLoc,
1812 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1815 bool consumeLastToken,
1816 SourceLocation &endLoc) {
1817 assert(Tok.is(tok::less));
1818 SourceLocation typeArgsLAngleLoc;
1819 SmallVector<ParsedType, 4> typeArgs;
1820 SourceLocation typeArgsRAngleLoc;
1821 SourceLocation protocolLAngleLoc;
1822 SmallVector<Decl *, 4> protocols;
1823 SmallVector<SourceLocation, 4> protocolLocs;
1824 SourceLocation protocolRAngleLoc;
1826 // Parse type arguments and protocol qualifiers.
1827 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1828 typeArgsRAngleLoc, protocolLAngleLoc,
1829 protocols, protocolLocs,
1830 protocolRAngleLoc, consumeLastToken);
1832 if (Tok.is(tok::eof))
1833 return true; // Invalid type result.
1835 // Compute the location of the last token.
1836 if (consumeLastToken)
1837 endLoc = PrevTokLocation;
1839 endLoc = Tok.getLocation();
1841 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1854 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1855 BalancedDelimiterTracker &T,
1856 SmallVectorImpl<Decl *> &AllIvarDecls,
1857 bool RBraceMissing) {
1861 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1862 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1863 Actions.ActOnObjCContainerFinishDefinition();
1864 // Call ActOnFields() even if we don't have any decls. This is useful
1865 // for code rewriting tools that need to be aware of the empty list.
1866 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, AllIvarDecls,
1867 T.getOpenLocation(), T.getCloseLocation(),
1868 ParsedAttributesView());
1871 /// objc-class-instance-variables:
1872 /// '{' objc-instance-variable-decl-list[opt] '}'
1874 /// objc-instance-variable-decl-list:
1875 /// objc-visibility-spec
1876 /// objc-instance-variable-decl ';'
1878 /// objc-instance-variable-decl-list objc-visibility-spec
1879 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1880 /// objc-instance-variable-decl-list ';'
1882 /// objc-visibility-spec:
1886 /// @package [OBJC2]
1888 /// objc-instance-variable-decl:
1889 /// struct-declaration
1891 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1892 tok::ObjCKeywordKind visibility,
1893 SourceLocation atLoc) {
1894 assert(Tok.is(tok::l_brace) && "expected {");
1895 SmallVector<Decl *, 32> AllIvarDecls;
1897 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1898 ObjCDeclContextSwitch ObjCDC(*this);
1900 BalancedDelimiterTracker T(*this, tok::l_brace);
1902 // While we still have something to read, read the instance variables.
1903 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1904 // Each iteration of this loop reads one objc-instance-variable-decl.
1906 // Check for extraneous top-level semicolon.
1907 if (Tok.is(tok::semi)) {
1908 ConsumeExtraSemi(InstanceVariableList);
1912 // Set the default visibility to private.
1913 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1914 if (Tok.is(tok::code_completion)) {
1915 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1916 return cutOffParsing();
1919 switch (Tok.getObjCKeywordID()) {
1920 case tok::objc_private:
1921 case tok::objc_public:
1922 case tok::objc_protected:
1923 case tok::objc_package:
1924 visibility = Tok.getObjCKeywordID();
1929 Diag(Tok, diag::err_objc_unexpected_atend);
1930 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1931 Tok.setKind(tok::at);
1934 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1935 T, AllIvarDecls, true);
1939 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1944 if (Tok.is(tok::code_completion)) {
1945 Actions.CodeCompleteOrdinaryName(getCurScope(),
1946 Sema::PCC_ObjCInstanceVariableList);
1947 return cutOffParsing();
1950 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1951 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1952 // Install the declarator into the interface decl.
1953 FD.D.setObjCIvar(true);
1954 Decl *Field = Actions.ActOnIvar(
1955 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1956 FD.BitfieldSize, visibility);
1957 Actions.ActOnObjCContainerFinishDefinition();
1959 AllIvarDecls.push_back(Field);
1963 // Parse all the comma separated declarators.
1964 ParsingDeclSpec DS(*this);
1965 ParseStructDeclaration(DS, ObjCIvarCallback);
1967 if (Tok.is(tok::semi)) {
1970 Diag(Tok, diag::err_expected_semi_decl_list);
1971 // Skip to end of block or statement
1972 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1975 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1976 T, AllIvarDecls, false);
1979 /// objc-protocol-declaration:
1980 /// objc-protocol-definition
1981 /// objc-protocol-forward-reference
1983 /// objc-protocol-definition:
1984 /// \@protocol identifier
1985 /// objc-protocol-refs[opt]
1986 /// objc-interface-decl-list
1989 /// objc-protocol-forward-reference:
1990 /// \@protocol identifier-list ';'
1992 /// "\@protocol identifier ;" should be resolved as "\@protocol
1993 /// identifier-list ;": objc-interface-decl-list may not start with a
1994 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1995 Parser::DeclGroupPtrTy
1996 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1997 ParsedAttributes &attrs) {
1998 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1999 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2000 ConsumeToken(); // the "protocol" identifier
2002 if (Tok.is(tok::code_completion)) {
2003 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2008 MaybeSkipAttributes(tok::objc_protocol);
2010 if (expectIdentifier())
2011 return nullptr; // missing protocol name.
2012 // Save the protocol name, then consume it.
2013 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2014 SourceLocation nameLoc = ConsumeToken();
2016 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2017 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2018 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo, attrs);
2021 CheckNestedObjCContexts(AtLoc);
2023 if (Tok.is(tok::comma)) { // list of forward declarations.
2024 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2025 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2027 // Parse the list of forward declarations.
2029 ConsumeToken(); // the ','
2030 if (expectIdentifier()) {
2031 SkipUntil(tok::semi);
2034 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2035 Tok.getLocation()));
2036 ConsumeToken(); // the identifier
2038 if (Tok.isNot(tok::comma))
2042 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2045 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs, attrs);
2048 // Last, and definitely not least, parse a protocol declaration.
2049 SourceLocation LAngleLoc, EndProtoLoc;
2051 SmallVector<Decl *, 8> ProtocolRefs;
2052 SmallVector<SourceLocation, 8> ProtocolLocs;
2053 if (Tok.is(tok::less) &&
2054 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2055 LAngleLoc, EndProtoLoc,
2056 /*consumeLastToken=*/true))
2059 Decl *ProtoType = Actions.ActOnStartProtocolInterface(
2060 AtLoc, protocolName, nameLoc, ProtocolRefs.data(), ProtocolRefs.size(),
2061 ProtocolLocs.data(), EndProtoLoc, attrs);
2063 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2064 return Actions.ConvertDeclToDeclGroup(ProtoType);
2067 /// objc-implementation:
2068 /// objc-class-implementation-prologue
2069 /// objc-category-implementation-prologue
2071 /// objc-class-implementation-prologue:
2072 /// @implementation identifier objc-superclass[opt]
2073 /// objc-class-instance-variables[opt]
2075 /// objc-category-implementation-prologue:
2076 /// @implementation identifier ( identifier )
2077 Parser::DeclGroupPtrTy
2078 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
2079 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2080 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2081 CheckNestedObjCContexts(AtLoc);
2082 ConsumeToken(); // the "implementation" identifier
2084 // Code completion after '@implementation'.
2085 if (Tok.is(tok::code_completion)) {
2086 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2091 MaybeSkipAttributes(tok::objc_implementation);
2093 if (expectIdentifier())
2094 return nullptr; // missing class or category name.
2095 // We have a class or category name - consume it.
2096 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2097 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2098 Decl *ObjCImpDecl = nullptr;
2100 // Neither a type parameter list nor a list of protocol references is
2101 // permitted here. Parse and diagnose them.
2102 if (Tok.is(tok::less)) {
2103 SourceLocation lAngleLoc, rAngleLoc;
2104 SmallVector<IdentifierLocPair, 8> protocolIdents;
2105 SourceLocation diagLoc = Tok.getLocation();
2106 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2107 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2108 protocolIdents, rAngleLoc)) {
2109 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2110 << SourceRange(diagLoc, PrevTokLocation);
2111 } else if (lAngleLoc.isValid()) {
2112 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2113 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2117 if (Tok.is(tok::l_paren)) {
2118 // we have a category implementation.
2120 SourceLocation categoryLoc, rparenLoc;
2121 IdentifierInfo *categoryId = nullptr;
2123 if (Tok.is(tok::code_completion)) {
2124 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2129 if (Tok.is(tok::identifier)) {
2130 categoryId = Tok.getIdentifierInfo();
2131 categoryLoc = ConsumeToken();
2133 Diag(Tok, diag::err_expected)
2134 << tok::identifier; // missing category name.
2137 if (Tok.isNot(tok::r_paren)) {
2138 Diag(Tok, diag::err_expected) << tok::r_paren;
2139 SkipUntil(tok::r_paren); // don't stop at ';'
2142 rparenLoc = ConsumeParen();
2143 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2144 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2145 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2146 SmallVector<Decl *, 4> protocols;
2147 SmallVector<SourceLocation, 4> protocolLocs;
2148 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2149 /*warnOnIncompleteProtocols=*/false,
2150 /*ForObjCContainer=*/false,
2151 protocolLAngleLoc, protocolRAngleLoc,
2152 /*consumeLastToken=*/true);
2154 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2155 AtLoc, nameId, nameLoc, categoryId,
2159 // We have a class implementation
2160 SourceLocation superClassLoc;
2161 IdentifierInfo *superClassId = nullptr;
2162 if (TryConsumeToken(tok::colon)) {
2163 // We have a super class
2164 if (expectIdentifier())
2165 return nullptr; // missing super class name.
2166 superClassId = Tok.getIdentifierInfo();
2167 superClassLoc = ConsumeToken(); // Consume super class name
2169 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2170 AtLoc, nameId, nameLoc,
2171 superClassId, superClassLoc);
2173 if (Tok.is(tok::l_brace)) // we have ivars
2174 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2175 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2176 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2178 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2179 SmallVector<Decl *, 4> protocols;
2180 SmallVector<SourceLocation, 4> protocolLocs;
2181 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2182 /*warnOnIncompleteProtocols=*/false,
2183 /*ForObjCContainer=*/false,
2184 protocolLAngleLoc, protocolRAngleLoc,
2185 /*consumeLastToken=*/true);
2188 assert(ObjCImpDecl);
2190 SmallVector<Decl *, 8> DeclsInGroup;
2193 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2194 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2195 ParsedAttributesWithRange attrs(AttrFactory);
2196 MaybeParseCXX11Attributes(attrs);
2197 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2198 DeclGroupRef DG = DGP.get();
2199 DeclsInGroup.append(DG.begin(), DG.end());
2204 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2207 Parser::DeclGroupPtrTy
2208 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2209 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2210 "ParseObjCAtEndDeclaration(): Expected @end");
2211 ConsumeToken(); // the "end" identifier
2212 if (CurParsedObjCImpl)
2213 CurParsedObjCImpl->finish(atEnd);
2215 // missing @implementation
2216 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2220 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2222 finish(P.Tok.getLocation());
2223 if (P.isEofOrEom()) {
2224 P.Diag(P.Tok, diag::err_objc_missing_end)
2225 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2226 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
2227 << Sema::OCK_Implementation;
2230 P.CurParsedObjCImpl = nullptr;
2231 assert(LateParsedObjCMethods.empty());
2234 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2236 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2237 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2238 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2241 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2244 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2245 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2246 false/*c-functions*/);
2248 /// Clear and free the cached objc methods.
2249 for (LateParsedObjCMethodContainer::iterator
2250 I = LateParsedObjCMethods.begin(),
2251 E = LateParsedObjCMethods.end(); I != E; ++I)
2253 LateParsedObjCMethods.clear();
2258 /// compatibility-alias-decl:
2259 /// @compatibility_alias alias-name class-name ';'
2261 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2262 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2263 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2264 ConsumeToken(); // consume compatibility_alias
2265 if (expectIdentifier())
2267 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2268 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2269 if (expectIdentifier())
2271 IdentifierInfo *classId = Tok.getIdentifierInfo();
2272 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2273 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2274 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2278 /// property-synthesis:
2279 /// @synthesize property-ivar-list ';'
2281 /// property-ivar-list:
2283 /// property-ivar-list ',' property-ivar
2287 /// identifier '=' identifier
2289 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2290 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2291 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2292 ConsumeToken(); // consume synthesize
2295 if (Tok.is(tok::code_completion)) {
2296 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2301 if (Tok.isNot(tok::identifier)) {
2302 Diag(Tok, diag::err_synthesized_property_name);
2303 SkipUntil(tok::semi);
2307 IdentifierInfo *propertyIvar = nullptr;
2308 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2309 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2310 SourceLocation propertyIvarLoc;
2311 if (TryConsumeToken(tok::equal)) {
2312 // property '=' ivar-name
2313 if (Tok.is(tok::code_completion)) {
2314 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2319 if (expectIdentifier())
2321 propertyIvar = Tok.getIdentifierInfo();
2322 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2324 Actions.ActOnPropertyImplDecl(
2325 getCurScope(), atLoc, propertyLoc, true,
2326 propertyId, propertyIvar, propertyIvarLoc,
2327 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2328 if (Tok.isNot(tok::comma))
2330 ConsumeToken(); // consume ','
2332 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2336 /// property-dynamic:
2337 /// @dynamic property-list
2341 /// property-list ',' identifier
2343 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2344 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2345 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2346 ConsumeToken(); // consume dynamic
2348 bool isClassProperty = false;
2349 if (Tok.is(tok::l_paren)) {
2351 const IdentifierInfo *II = Tok.getIdentifierInfo();
2354 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2355 SkipUntil(tok::r_paren, StopAtSemi);
2357 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2358 if (II->isStr("class")) {
2359 isClassProperty = true;
2360 if (Tok.isNot(tok::r_paren)) {
2361 Diag(Tok, diag::err_expected) << tok::r_paren;
2362 SkipUntil(tok::r_paren, StopAtSemi);
2366 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2367 SkipUntil(tok::r_paren, StopAtSemi);
2373 if (Tok.is(tok::code_completion)) {
2374 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2379 if (expectIdentifier()) {
2380 SkipUntil(tok::semi);
2384 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2385 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2386 Actions.ActOnPropertyImplDecl(
2387 getCurScope(), atLoc, propertyLoc, false,
2388 propertyId, nullptr, SourceLocation(),
2389 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2390 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2392 if (Tok.isNot(tok::comma))
2394 ConsumeToken(); // consume ','
2396 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2400 /// objc-throw-statement:
2401 /// throw expression[opt];
2403 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2405 ConsumeToken(); // consume throw
2406 if (Tok.isNot(tok::semi)) {
2407 Res = ParseExpression();
2408 if (Res.isInvalid()) {
2409 SkipUntil(tok::semi);
2414 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2415 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2418 /// objc-synchronized-statement:
2419 /// @synchronized '(' expression ')' compound-statement
2422 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2423 ConsumeToken(); // consume synchronized
2424 if (Tok.isNot(tok::l_paren)) {
2425 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2429 // The operand is surrounded with parentheses.
2430 ConsumeParen(); // '('
2431 ExprResult operand(ParseExpression());
2433 if (Tok.is(tok::r_paren)) {
2434 ConsumeParen(); // ')'
2436 if (!operand.isInvalid())
2437 Diag(Tok, diag::err_expected) << tok::r_paren;
2439 // Skip forward until we see a left brace, but don't consume it.
2440 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2443 // Require a compound statement.
2444 if (Tok.isNot(tok::l_brace)) {
2445 if (!operand.isInvalid())
2446 Diag(Tok, diag::err_expected) << tok::l_brace;
2450 // Check the @synchronized operand now.
2451 if (!operand.isInvalid())
2452 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2454 // Parse the compound statement within a new scope.
2455 ParseScope bodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2456 StmtResult body(ParseCompoundStatementBody());
2459 // If there was a semantic or parse error earlier with the
2460 // operand, fail now.
2461 if (operand.isInvalid())
2464 if (body.isInvalid())
2465 body = Actions.ActOnNullStmt(Tok.getLocation());
2467 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2470 /// objc-try-catch-statement:
2471 /// @try compound-statement objc-catch-list[opt]
2472 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2474 /// objc-catch-list:
2475 /// @catch ( parameter-declaration ) compound-statement
2476 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2477 /// catch-parameter-declaration:
2478 /// parameter-declaration
2481 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2482 bool catch_or_finally_seen = false;
2484 ConsumeToken(); // consume try
2485 if (Tok.isNot(tok::l_brace)) {
2486 Diag(Tok, diag::err_expected) << tok::l_brace;
2489 StmtVector CatchStmts;
2490 StmtResult FinallyStmt;
2491 ParseScope TryScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2492 StmtResult TryBody(ParseCompoundStatementBody());
2494 if (TryBody.isInvalid())
2495 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2497 while (Tok.is(tok::at)) {
2498 // At this point, we need to lookahead to determine if this @ is the start
2499 // of an @catch or @finally. We don't want to consume the @ token if this
2500 // is an @try or @encode or something else.
2501 Token AfterAt = GetLookAheadToken(1);
2502 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2503 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2506 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2507 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2508 Decl *FirstPart = nullptr;
2509 ConsumeToken(); // consume catch
2510 if (Tok.is(tok::l_paren)) {
2512 ParseScope CatchScope(this, Scope::DeclScope |
2513 Scope::CompoundStmtScope |
2514 Scope::AtCatchScope);
2515 if (Tok.isNot(tok::ellipsis)) {
2516 DeclSpec DS(AttrFactory);
2517 ParseDeclarationSpecifiers(DS);
2518 Declarator ParmDecl(DS, DeclaratorContext::ObjCCatchContext);
2519 ParseDeclarator(ParmDecl);
2521 // Inform the actions module about the declarator, so it
2522 // gets added to the current scope.
2523 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2525 ConsumeToken(); // consume '...'
2527 SourceLocation RParenLoc;
2529 if (Tok.is(tok::r_paren))
2530 RParenLoc = ConsumeParen();
2531 else // Skip over garbage, until we get to ')'. Eat the ')'.
2532 SkipUntil(tok::r_paren, StopAtSemi);
2534 StmtResult CatchBody(true);
2535 if (Tok.is(tok::l_brace))
2536 CatchBody = ParseCompoundStatementBody();
2538 Diag(Tok, diag::err_expected) << tok::l_brace;
2539 if (CatchBody.isInvalid())
2540 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2542 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2546 if (!Catch.isInvalid())
2547 CatchStmts.push_back(Catch.get());
2550 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2554 catch_or_finally_seen = true;
2556 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2557 ConsumeToken(); // consume finally
2558 ParseScope FinallyScope(this,
2559 Scope::DeclScope | Scope::CompoundStmtScope);
2561 bool ShouldCapture =
2562 getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2564 Actions.ActOnCapturedRegionStart(Tok.getLocation(), getCurScope(),
2565 CR_ObjCAtFinally, 1);
2567 StmtResult FinallyBody(true);
2568 if (Tok.is(tok::l_brace))
2569 FinallyBody = ParseCompoundStatementBody();
2571 Diag(Tok, diag::err_expected) << tok::l_brace;
2573 if (FinallyBody.isInvalid()) {
2574 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2576 Actions.ActOnCapturedRegionError();
2577 } else if (ShouldCapture) {
2578 FinallyBody = Actions.ActOnCapturedRegionEnd(FinallyBody.get());
2581 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2583 catch_or_finally_seen = true;
2587 if (!catch_or_finally_seen) {
2588 Diag(atLoc, diag::err_missing_catch_finally);
2592 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2597 /// objc-autoreleasepool-statement:
2598 /// @autoreleasepool compound-statement
2601 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2602 ConsumeToken(); // consume autoreleasepool
2603 if (Tok.isNot(tok::l_brace)) {
2604 Diag(Tok, diag::err_expected) << tok::l_brace;
2607 // Enter a scope to hold everything within the compound stmt. Compound
2608 // statements can always hold declarations.
2609 ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2611 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2614 if (AutoreleasePoolBody.isInvalid())
2615 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2616 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2617 AutoreleasePoolBody.get());
2620 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2621 /// for later parsing.
2622 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2623 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2624 trySkippingFunctionBody()) {
2625 Actions.ActOnSkippedFunctionBody(MDecl);
2629 LexedMethod* LM = new LexedMethod(this, MDecl);
2630 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2631 CachedTokens &Toks = LM->Toks;
2632 // Begin by storing the '{' or 'try' or ':' token.
2633 Toks.push_back(Tok);
2634 if (Tok.is(tok::kw_try)) {
2636 if (Tok.is(tok::colon)) {
2637 Toks.push_back(Tok);
2639 while (Tok.isNot(tok::l_brace)) {
2640 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2641 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2644 Toks.push_back(Tok); // also store '{'
2646 else if (Tok.is(tok::colon)) {
2648 // FIXME: This is wrong, due to C++11 braced initialization.
2649 while (Tok.isNot(tok::l_brace)) {
2650 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2651 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2653 Toks.push_back(Tok); // also store '{'
2656 // Consume everything up to (and including) the matching right brace.
2657 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2658 while (Tok.is(tok::kw_catch)) {
2659 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2660 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2664 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2666 Decl *Parser::ParseObjCMethodDefinition() {
2667 Decl *MDecl = ParseObjCMethodPrototype();
2669 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, MDecl, Tok.getLocation(),
2670 "parsing Objective-C method");
2672 // parse optional ';'
2673 if (Tok.is(tok::semi)) {
2674 if (CurParsedObjCImpl) {
2675 Diag(Tok, diag::warn_semicolon_before_method_body)
2676 << FixItHint::CreateRemoval(Tok.getLocation());
2681 // We should have an opening brace now.
2682 if (Tok.isNot(tok::l_brace)) {
2683 Diag(Tok, diag::err_expected_method_body);
2685 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2686 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2688 // If we didn't find the '{', bail out.
2689 if (Tok.isNot(tok::l_brace))
2695 SkipUntil(tok::r_brace);
2699 // Allow the rest of sema to find private method decl implementations.
2700 Actions.AddAnyMethodToGlobalPool(MDecl);
2701 assert (CurParsedObjCImpl
2702 && "ParseObjCMethodDefinition - Method out of @implementation");
2703 // Consume the tokens and store them for later parsing.
2704 StashAwayMethodOrFunctionBodyTokens(MDecl);
2708 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2709 if (Tok.is(tok::code_completion)) {
2710 Actions.CodeCompleteObjCAtStatement(getCurScope());
2715 if (Tok.isObjCAtKeyword(tok::objc_try))
2716 return ParseObjCTryStmt(AtLoc);
2718 if (Tok.isObjCAtKeyword(tok::objc_throw))
2719 return ParseObjCThrowStmt(AtLoc);
2721 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2722 return ParseObjCSynchronizedStmt(AtLoc);
2724 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2725 return ParseObjCAutoreleasePoolStmt(AtLoc);
2727 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2728 getLangOpts().DebuggerSupport) {
2729 SkipUntil(tok::semi);
2730 return Actions.ActOnNullStmt(Tok.getLocation());
2733 ExprStatementTokLoc = AtLoc;
2734 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2735 if (Res.isInvalid()) {
2736 // If the expression is invalid, skip ahead to the next semicolon. Not
2737 // doing this opens us up to the possibility of infinite loops if
2738 // ParseExpression does not consume any tokens.
2739 SkipUntil(tok::semi);
2743 // Otherwise, eat the semicolon.
2744 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2745 return Actions.ActOnExprStmt(Res);
2748 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2749 switch (Tok.getKind()) {
2750 case tok::code_completion:
2751 Actions.CodeCompleteObjCAtExpression(getCurScope());
2757 tok::TokenKind Kind = Tok.getKind();
2758 SourceLocation OpLoc = ConsumeToken();
2760 if (!Tok.is(tok::numeric_constant)) {
2761 const char *Symbol = nullptr;
2763 case tok::minus: Symbol = "-"; break;
2764 case tok::plus: Symbol = "+"; break;
2765 default: llvm_unreachable("missing unary operator case");
2767 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2772 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2773 if (Lit.isInvalid()) {
2776 ConsumeToken(); // Consume the literal token.
2778 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2779 if (Lit.isInvalid())
2782 return ParsePostfixExpressionSuffix(
2783 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2786 case tok::string_literal: // primary-expression: string-literal
2787 case tok::wide_string_literal:
2788 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2790 case tok::char_constant:
2791 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2793 case tok::numeric_constant:
2794 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2796 case tok::kw_true: // Objective-C++, etc.
2797 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2798 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2799 case tok::kw_false: // Objective-C++, etc.
2800 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2801 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2804 // Objective-C array literal
2805 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2808 // Objective-C dictionary literal
2809 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2812 // Objective-C boxed expression
2813 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2816 if (Tok.getIdentifierInfo() == nullptr)
2817 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2819 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2820 case tok::objc_encode:
2821 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2822 case tok::objc_protocol:
2823 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2824 case tok::objc_selector:
2825 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2826 case tok::objc_available:
2827 return ParseAvailabilityCheckExpr(AtLoc);
2829 const char *str = nullptr;
2830 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2831 // that this is a proper statement where such directives could actually
2833 if (GetLookAheadToken(1).is(tok::l_brace) &&
2834 ExprStatementTokLoc == AtLoc) {
2835 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2838 : (ch == 'f' ? "finally"
2839 : (ch == 'a' ? "autoreleasepool" : nullptr));
2842 SourceLocation kwLoc = Tok.getLocation();
2843 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2844 FixItHint::CreateReplacement(kwLoc, str));
2847 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2853 /// Parse the receiver of an Objective-C++ message send.
2855 /// This routine parses the receiver of a message send in
2856 /// Objective-C++ either as a type or as an expression. Note that this
2857 /// routine must not be called to parse a send to 'super', since it
2858 /// has no way to return such a result.
2860 /// \param IsExpr Whether the receiver was parsed as an expression.
2862 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2863 /// IsExpr is true), the parsed expression. If the receiver was parsed
2864 /// as a type (\c IsExpr is false), the parsed type.
2866 /// \returns True if an error occurred during parsing or semantic
2867 /// analysis, in which case the arguments do not have valid
2868 /// values. Otherwise, returns false for a successful parse.
2870 /// objc-receiver: [C++]
2871 /// 'super' [not parsed here]
2873 /// simple-type-specifier
2874 /// typename-specifier
2875 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2876 InMessageExpressionRAIIObject InMessage(*this, true);
2878 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2879 tok::annot_cxxscope))
2880 TryAnnotateTypeOrScopeToken();
2882 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2885 // Make sure any typos in the receiver are corrected or diagnosed, so that
2886 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2887 // only the things that are valid ObjC receivers?
2888 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2889 if (Receiver.isInvalid())
2893 TypeOrExpr = Receiver.get();
2898 // typename-specifier
2899 // simple-type-specifier
2900 // expression (that starts with one of the above)
2901 DeclSpec DS(AttrFactory);
2902 ParseCXXSimpleTypeSpecifier(DS);
2904 if (Tok.is(tok::l_paren)) {
2905 // If we see an opening parentheses at this point, we are
2906 // actually parsing an expression that starts with a
2907 // function-style cast, e.g.,
2909 // postfix-expression:
2910 // simple-type-specifier ( expression-list [opt] )
2911 // typename-specifier ( expression-list [opt] )
2913 // Parse the remainder of this case, then the (optional)
2914 // postfix-expression suffix, followed by the (optional)
2915 // right-hand side of the binary expression. We have an
2917 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2918 if (!Receiver.isInvalid())
2919 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2920 if (!Receiver.isInvalid())
2921 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2922 if (Receiver.isInvalid())
2926 TypeOrExpr = Receiver.get();
2930 // We have a class message. Turn the simple-type-specifier or
2931 // typename-specifier we parsed into a type and parse the
2932 // remainder of the class message.
2933 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2934 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2935 if (Type.isInvalid())
2939 TypeOrExpr = Type.get().getAsOpaquePtr();
2943 /// Determine whether the parser is currently referring to a an
2944 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2946 /// This routine will only return true for a subset of valid message-send
2948 bool Parser::isSimpleObjCMessageExpression() {
2949 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2950 "Incorrect start for isSimpleObjCMessageExpression");
2951 return GetLookAheadToken(1).is(tok::identifier) &&
2952 GetLookAheadToken(2).is(tok::identifier);
2955 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2956 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2957 InMessageExpression)
2962 if (Tok.is(tok::annot_typename))
2963 Type = getTypeAnnotation(Tok);
2964 else if (Tok.is(tok::identifier))
2965 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2970 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2971 const Token &AfterNext = GetLookAheadToken(2);
2972 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2973 if (Tok.is(tok::identifier))
2974 TryAnnotateTypeOrScopeToken();
2976 return Tok.is(tok::annot_typename);
2983 /// objc-message-expr:
2984 /// '[' objc-receiver objc-message-args ']'
2986 /// objc-receiver: [C]
2992 ExprResult Parser::ParseObjCMessageExpression() {
2993 assert(Tok.is(tok::l_square) && "'[' expected");
2994 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2996 if (Tok.is(tok::code_completion)) {
2997 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3002 InMessageExpressionRAIIObject InMessage(*this, true);
3004 if (getLangOpts().CPlusPlus) {
3005 // We completely separate the C and C++ cases because C++ requires
3006 // more complicated (read: slower) parsing.
3008 // Handle send to super.
3009 // FIXME: This doesn't benefit from the same typo-correction we
3010 // get in Objective-C.
3011 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3012 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3013 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3016 // Parse the receiver, which is either a type or an expression.
3018 void *TypeOrExpr = nullptr;
3019 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3020 SkipUntil(tok::r_square, StopAtSemi);
3025 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3026 static_cast<Expr *>(TypeOrExpr));
3028 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3029 ParsedType::getFromOpaquePtr(TypeOrExpr),
3033 if (Tok.is(tok::identifier)) {
3034 IdentifierInfo *Name = Tok.getIdentifierInfo();
3035 SourceLocation NameLoc = Tok.getLocation();
3036 ParsedType ReceiverType;
3037 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3038 Name == Ident_super,
3039 NextToken().is(tok::period),
3041 case Sema::ObjCSuperMessage:
3042 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3045 case Sema::ObjCClassMessage:
3046 if (!ReceiverType) {
3047 SkipUntil(tok::r_square, StopAtSemi);
3051 ConsumeToken(); // the type name
3053 // Parse type arguments and protocol qualifiers.
3054 if (Tok.is(tok::less)) {
3055 SourceLocation NewEndLoc;
3056 TypeResult NewReceiverType
3057 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3058 /*consumeLastToken=*/true,
3060 if (!NewReceiverType.isUsable()) {
3061 SkipUntil(tok::r_square, StopAtSemi);
3065 ReceiverType = NewReceiverType.get();
3068 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3069 ReceiverType, nullptr);
3071 case Sema::ObjCInstanceMessage:
3072 // Fall through to parse an expression.
3077 // Otherwise, an arbitrary expression can be the receiver of a send.
3078 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3079 if (Res.isInvalid()) {
3080 SkipUntil(tok::r_square, StopAtSemi);
3084 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3088 /// Parse the remainder of an Objective-C message following the
3089 /// '[' objc-receiver.
3091 /// This routine handles sends to super, class messages (sent to a
3092 /// class name), and instance messages (sent to an object), and the
3093 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3094 /// ReceiverExpr, respectively. Only one of these parameters may have
3097 /// \param LBracLoc The location of the opening '['.
3099 /// \param SuperLoc If this is a send to 'super', the location of the
3100 /// 'super' keyword that indicates a send to the superclass.
3102 /// \param ReceiverType If this is a class message, the type of the
3103 /// class we are sending a message to.
3105 /// \param ReceiverExpr If this is an instance message, the expression
3106 /// used to compute the receiver object.
3108 /// objc-message-args:
3110 /// objc-keywordarg-list
3112 /// objc-keywordarg-list:
3114 /// objc-keywordarg-list objc-keywordarg
3116 /// objc-keywordarg:
3117 /// selector-name[opt] ':' objc-keywordexpr
3119 /// objc-keywordexpr:
3120 /// nonempty-expr-list
3122 /// nonempty-expr-list:
3123 /// assignment-expression
3124 /// nonempty-expr-list , assignment-expression
3127 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3128 SourceLocation SuperLoc,
3129 ParsedType ReceiverType,
3130 Expr *ReceiverExpr) {
3131 InMessageExpressionRAIIObject InMessage(*this, true);
3133 if (Tok.is(tok::code_completion)) {
3134 if (SuperLoc.isValid())
3135 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3137 else if (ReceiverType)
3138 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3141 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3147 // Parse objc-selector
3149 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3151 SmallVector<IdentifierInfo *, 12> KeyIdents;
3152 SmallVector<SourceLocation, 12> KeyLocs;
3153 ExprVector KeyExprs;
3155 if (Tok.is(tok::colon)) {
3157 // Each iteration parses a single keyword argument.
3158 KeyIdents.push_back(selIdent);
3159 KeyLocs.push_back(Loc);
3161 if (ExpectAndConsume(tok::colon)) {
3162 // We must manually skip to a ']', otherwise the expression skipper will
3163 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3164 // the enclosing expression.
3165 SkipUntil(tok::r_square, StopAtSemi);
3169 /// Parse the expression after ':'
3171 if (Tok.is(tok::code_completion)) {
3172 if (SuperLoc.isValid())
3173 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3175 /*AtArgumentEpression=*/true);
3176 else if (ReceiverType)
3177 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3179 /*AtArgumentEpression=*/true);
3181 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3183 /*AtArgumentEpression=*/true);
3190 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3191 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3192 Expr = ParseBraceInitializer();
3194 Expr = ParseAssignmentExpression();
3196 ExprResult Res(Expr);
3197 if (Res.isInvalid()) {
3198 // We must manually skip to a ']', otherwise the expression skipper will
3199 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3200 // the enclosing expression.
3201 SkipUntil(tok::r_square, StopAtSemi);
3205 // We have a valid expression.
3206 KeyExprs.push_back(Res.get());
3208 // Code completion after each argument.
3209 if (Tok.is(tok::code_completion)) {
3210 if (SuperLoc.isValid())
3211 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3213 /*AtArgumentEpression=*/false);
3214 else if (ReceiverType)
3215 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3217 /*AtArgumentEpression=*/false);
3219 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3221 /*AtArgumentEpression=*/false);
3226 // Check for another keyword selector.
3227 selIdent = ParseObjCSelectorPiece(Loc);
3228 if (!selIdent && Tok.isNot(tok::colon))
3230 // We have a selector or a colon, continue parsing.
3232 // Parse the, optional, argument list, comma separated.
3233 while (Tok.is(tok::comma)) {
3234 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3235 /// Parse the expression after ','
3236 ExprResult Res(ParseAssignmentExpression());
3237 if (Tok.is(tok::colon))
3238 Res = Actions.CorrectDelayedTyposInExpr(Res);
3239 if (Res.isInvalid()) {
3240 if (Tok.is(tok::colon)) {
3241 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3242 FixItHint::CreateRemoval(commaLoc);
3244 // We must manually skip to a ']', otherwise the expression skipper will
3245 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3246 // the enclosing expression.
3247 SkipUntil(tok::r_square, StopAtSemi);
3251 // We have a valid expression.
3252 KeyExprs.push_back(Res.get());
3254 } else if (!selIdent) {
3255 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3257 // We must manually skip to a ']', otherwise the expression skipper will
3258 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3259 // the enclosing expression.
3260 SkipUntil(tok::r_square, StopAtSemi);
3264 if (Tok.isNot(tok::r_square)) {
3265 Diag(Tok, diag::err_expected)
3266 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3267 // We must manually skip to a ']', otherwise the expression skipper will
3268 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3269 // the enclosing expression.
3270 SkipUntil(tok::r_square, StopAtSemi);
3274 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3276 unsigned nKeys = KeyIdents.size();
3278 KeyIdents.push_back(selIdent);
3279 KeyLocs.push_back(Loc);
3281 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3283 if (SuperLoc.isValid())
3284 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3285 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3286 else if (ReceiverType)
3287 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3288 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3289 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3290 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3293 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3294 ExprResult Res(ParseStringLiteralExpression());
3295 if (Res.isInvalid()) return Res;
3297 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3298 // expressions. At this point, we know that the only valid thing that starts
3299 // with '@' is an @"".
3300 SmallVector<SourceLocation, 4> AtLocs;
3301 ExprVector AtStrings;
3302 AtLocs.push_back(AtLoc);
3303 AtStrings.push_back(Res.get());
3305 while (Tok.is(tok::at)) {
3306 AtLocs.push_back(ConsumeToken()); // eat the @.
3308 // Invalid unless there is a string literal.
3309 if (!isTokenStringLiteral())
3310 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3312 ExprResult Lit(ParseStringLiteralExpression());
3313 if (Lit.isInvalid())
3316 AtStrings.push_back(Lit.get());
3319 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3322 /// ParseObjCBooleanLiteral -
3323 /// objc-scalar-literal : '@' boolean-keyword
3325 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3327 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3329 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3330 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3333 /// ParseObjCCharacterLiteral -
3334 /// objc-scalar-literal : '@' character-literal
3336 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3337 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3338 if (Lit.isInvalid()) {
3341 ConsumeToken(); // Consume the literal token.
3342 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3345 /// ParseObjCNumericLiteral -
3346 /// objc-scalar-literal : '@' scalar-literal
3348 /// scalar-literal : | numeric-constant /* any numeric constant. */
3350 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3351 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3352 if (Lit.isInvalid()) {
3355 ConsumeToken(); // Consume the literal token.
3356 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3359 /// ParseObjCBoxedExpr -
3360 /// objc-box-expression:
3361 /// @( assignment-expression )
3363 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3364 if (Tok.isNot(tok::l_paren))
3365 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3367 BalancedDelimiterTracker T(*this, tok::l_paren);
3369 ExprResult ValueExpr(ParseAssignmentExpression());
3370 if (T.consumeClose())
3373 if (ValueExpr.isInvalid())
3376 // Wrap the sub-expression in a parenthesized expression, to distinguish
3377 // a boxed expression from a literal.
3378 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3379 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3380 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3384 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3385 ExprVector ElementExprs; // array elements.
3386 ConsumeBracket(); // consume the l_square.
3388 bool HasInvalidEltExpr = false;
3389 while (Tok.isNot(tok::r_square)) {
3390 // Parse list of array element expressions (all must be id types).
3391 ExprResult Res(ParseAssignmentExpression());
3392 if (Res.isInvalid()) {
3393 // We must manually skip to a ']', otherwise the expression skipper will
3394 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3395 // the enclosing expression.
3396 SkipUntil(tok::r_square, StopAtSemi);
3400 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3401 if (Res.isInvalid())
3402 HasInvalidEltExpr = true;
3404 // Parse the ellipsis that indicates a pack expansion.
3405 if (Tok.is(tok::ellipsis))
3406 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3407 if (Res.isInvalid())
3408 HasInvalidEltExpr = true;
3410 ElementExprs.push_back(Res.get());
3412 if (Tok.is(tok::comma))
3413 ConsumeToken(); // Eat the ','.
3414 else if (Tok.isNot(tok::r_square))
3415 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3418 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3420 if (HasInvalidEltExpr)
3423 MultiExprArg Args(ElementExprs);
3424 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3427 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3428 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3429 ConsumeBrace(); // consume the l_square.
3430 bool HasInvalidEltExpr = false;
3431 while (Tok.isNot(tok::r_brace)) {
3432 // Parse the comma separated key : value expressions.
3435 ColonProtectionRAIIObject X(*this);
3436 KeyExpr = ParseAssignmentExpression();
3437 if (KeyExpr.isInvalid()) {
3438 // We must manually skip to a '}', otherwise the expression skipper will
3439 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3440 // the enclosing expression.
3441 SkipUntil(tok::r_brace, StopAtSemi);
3446 if (ExpectAndConsume(tok::colon)) {
3447 SkipUntil(tok::r_brace, StopAtSemi);
3451 ExprResult ValueExpr(ParseAssignmentExpression());
3452 if (ValueExpr.isInvalid()) {
3453 // We must manually skip to a '}', otherwise the expression skipper will
3454 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3455 // the enclosing expression.
3456 SkipUntil(tok::r_brace, StopAtSemi);
3460 // Check the key and value for possible typos
3461 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3462 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3463 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3464 HasInvalidEltExpr = true;
3466 // Parse the ellipsis that designates this as a pack expansion. Do not
3467 // ActOnPackExpansion here, leave it to template instantiation time where
3468 // we can get better diagnostics.
3469 SourceLocation EllipsisLoc;
3470 if (getLangOpts().CPlusPlus)
3471 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3473 // We have a valid expression. Collect it in a vector so we can
3474 // build the argument list.
3475 ObjCDictionaryElement Element = {
3476 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3478 Elements.push_back(Element);
3480 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3481 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3484 SourceLocation EndLoc = ConsumeBrace();
3486 if (HasInvalidEltExpr)
3489 // Create the ObjCDictionaryLiteral.
3490 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3494 /// objc-encode-expression:
3495 /// \@encode ( type-name )
3497 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3498 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3500 SourceLocation EncLoc = ConsumeToken();
3502 if (Tok.isNot(tok::l_paren))
3503 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3505 BalancedDelimiterTracker T(*this, tok::l_paren);
3508 TypeResult Ty = ParseTypeName();
3515 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3516 Ty.get(), T.getCloseLocation());
3519 /// objc-protocol-expression
3520 /// \@protocol ( protocol-name )
3522 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3523 SourceLocation ProtoLoc = ConsumeToken();
3525 if (Tok.isNot(tok::l_paren))
3526 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3528 BalancedDelimiterTracker T(*this, tok::l_paren);
3531 if (expectIdentifier())
3534 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3535 SourceLocation ProtoIdLoc = ConsumeToken();
3539 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3540 T.getOpenLocation(), ProtoIdLoc,
3541 T.getCloseLocation());
3544 /// objc-selector-expression
3545 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3546 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3547 SourceLocation SelectorLoc = ConsumeToken();
3549 if (Tok.isNot(tok::l_paren))
3550 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3552 SmallVector<IdentifierInfo *, 12> KeyIdents;
3553 SourceLocation sLoc;
3555 BalancedDelimiterTracker T(*this, tok::l_paren);
3557 bool HasOptionalParen = Tok.is(tok::l_paren);
3558 if (HasOptionalParen)
3561 if (Tok.is(tok::code_completion)) {
3562 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3567 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3568 if (!SelIdent && // missing selector name.
3569 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3570 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3572 KeyIdents.push_back(SelIdent);
3574 unsigned nColons = 0;
3575 if (Tok.isNot(tok::r_paren)) {
3577 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3579 KeyIdents.push_back(nullptr);
3580 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3584 if (Tok.is(tok::r_paren))
3587 if (Tok.is(tok::code_completion)) {
3588 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3593 // Check for another keyword selector.
3595 SelIdent = ParseObjCSelectorPiece(Loc);
3596 KeyIdents.push_back(SelIdent);
3597 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3601 if (HasOptionalParen && Tok.is(tok::r_paren))
3602 ConsumeParen(); // ')'
3604 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3605 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3606 T.getOpenLocation(),
3607 T.getCloseLocation(),
3611 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3612 // MCDecl might be null due to error in method or c-function prototype, etc.
3613 Decl *MCDecl = LM.D;
3614 bool skip = MCDecl &&
3615 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3616 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3620 // Save the current token position.
3621 SourceLocation OrigLoc = Tok.getLocation();
3623 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3624 // Store an artificial EOF token to ensure that we don't run off the end of
3625 // the method's body when we come to parse it.
3628 Eof.setKind(tok::eof);
3629 Eof.setEofData(MCDecl);
3630 Eof.setLocation(OrigLoc);
3631 LM.Toks.push_back(Eof);
3632 // Append the current token at the end of the new token stream so that it
3633 // doesn't get lost.
3634 LM.Toks.push_back(Tok);
3635 PP.EnterTokenStream(LM.Toks, true);
3637 // Consume the previously pushed token.
3638 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3640 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3641 "Inline objective-c method not starting with '{' or 'try' or ':'");
3642 // Enter a scope for the method or c-function body.
3643 ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
3644 Scope::FnScope | Scope::DeclScope |
3645 Scope::CompoundStmtScope);
3647 // Tell the actions module that we have entered a method or c-function definition
3648 // with the specified Declarator for the method/function.
3650 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3652 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3653 if (Tok.is(tok::kw_try))
3654 ParseFunctionTryBlock(MCDecl, BodyScope);
3656 if (Tok.is(tok::colon))
3657 ParseConstructorInitializer(MCDecl);
3659 Actions.ActOnDefaultCtorInitializers(MCDecl);
3660 ParseFunctionStatementBody(MCDecl, BodyScope);
3663 if (Tok.getLocation() != OrigLoc) {
3664 // Due to parsing error, we either went over the cached tokens or
3665 // there are still cached tokens left. If it's the latter case skip the
3667 // Since this is an uncommon situation that should be avoided, use the
3668 // expensive isBeforeInTranslationUnit call.
3669 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3671 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3674 // Clean up the remaining EOF token.